You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tez.apache.org by bi...@apache.org on 2014/08/20 02:09:59 UTC
[2/2] git commit: TEZ-1465. Update and document IntersectExample.
Change name to JoinExample (bikas)
TEZ-1465. Update and document IntersectExample. Change name to JoinExample (bikas)
Project: http://git-wip-us.apache.org/repos/asf/tez/repo
Commit: http://git-wip-us.apache.org/repos/asf/tez/commit/b5497d7c
Tree: http://git-wip-us.apache.org/repos/asf/tez/tree/b5497d7c
Diff: http://git-wip-us.apache.org/repos/asf/tez/diff/b5497d7c
Branch: refs/heads/master
Commit: b5497d7c1992899f3bc46effb2dcbea3ccf62d82
Parents: fbca9f4
Author: Bikas Saha <bi...@apache.org>
Authored: Tue Aug 19 17:09:32 2014 -0700
Committer: Bikas Saha <bi...@apache.org>
Committed: Tue Aug 19 17:09:47 2014 -0700
----------------------------------------------------------------------
CHANGES.txt | 1 +
.../org/apache/tez/examples/ExampleDriver.java | 10 +-
.../apache/tez/examples/IntersectDataGen.java | 352 ------------------
.../apache/tez/examples/IntersectExample.java | 281 --------------
.../apache/tez/examples/IntersectValidate.java | 257 -------------
.../org/apache/tez/examples/JoinDataGen.java | 352 ++++++++++++++++++
.../org/apache/tez/examples/JoinExample.java | 364 +++++++++++++++++++
.../org/apache/tez/examples/JoinValidate.java | 257 +++++++++++++
.../apache/tez/examples/OrderedWordCount.java | 32 +-
.../java/org/apache/tez/examples/WordCount.java | 25 +-
.../java/org/apache/tez/test/TestTezJobs.java | 14 +-
11 files changed, 1026 insertions(+), 919 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/CHANGES.txt
----------------------------------------------------------------------
diff --git a/CHANGES.txt b/CHANGES.txt
index d07089c..e46867e 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -77,6 +77,7 @@ INCOMPATIBLE CHANGES
TEZ-1231. Clean up TezRuntimeConfiguration
TEZ-1246. Replace constructors with create() methods for DAG, Vertex, Edge etc in the API
TEZ-1455. Replace deprecated junit.framework.Assert with org.junit.Assert
+ TEZ-1465. Update and document IntersectExample. Change name to JoinExample
Release 0.4.0-incubating: 2014-04-05
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/ExampleDriver.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/ExampleDriver.java b/tez-examples/src/main/java/org/apache/tez/examples/ExampleDriver.java
index 88d180f..6f689e2 100644
--- a/tez-examples/src/main/java/org/apache/tez/examples/ExampleDriver.java
+++ b/tez-examples/src/main/java/org/apache/tez/examples/ExampleDriver.java
@@ -50,12 +50,12 @@ public class ExampleDriver {
"Word Count with words sorted on frequency");
pgd.addClass("simplesessionexample", SimpleSessionExample.class,
"Example to run multiple dags in a session");
- pgd.addClass("intersect", IntersectExample.class,
+ pgd.addClass("joinexample", JoinExample.class,
"Identify all occurences of lines in file1 which also occur in file2");
- pgd.addClass("intersectdatagen", IntersectDataGen.class,
- "Generate data to run the intersect example");
- pgd.addClass("intersectvalidate", IntersectValidate.class,
- "Validate data generated by intersect and intersectdatagen");
+ pgd.addClass("joindatagen", JoinDataGen.class,
+ "Generate data to run the joinexample");
+ pgd.addClass("joinvalidate", JoinValidate.class,
+ "Validate data generated by joinexample and joindatagen");
exitCode = pgd.run(argv);
} catch(Throwable e){
e.printStackTrace();
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/IntersectDataGen.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/IntersectDataGen.java b/tez-examples/src/main/java/org/apache/tez/examples/IntersectDataGen.java
deleted file mode 100644
index 435a914..0000000
--- a/tez-examples/src/main/java/org/apache/tez/examples/IntersectDataGen.java
+++ /dev/null
@@ -1,352 +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.tez.examples;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.Random;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.NullWritable;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.util.GenericOptionsParser;
-import org.apache.hadoop.util.Tool;
-import org.apache.hadoop.util.ToolRunner;
-import org.apache.tez.client.TezClient;
-import org.apache.tez.dag.api.DAG;
-import org.apache.tez.dag.api.ProcessorDescriptor;
-import org.apache.tez.dag.api.TezConfiguration;
-import org.apache.tez.dag.api.TezException;
-import org.apache.tez.dag.api.UserPayload;
-import org.apache.tez.dag.api.Vertex;
-import org.apache.tez.dag.api.client.DAGClient;
-import org.apache.tez.dag.api.client.DAGStatus;
-import org.apache.tez.mapreduce.output.MROutput;
-import org.apache.tez.mapreduce.processor.SimpleMRProcessor;
-import org.apache.tez.runtime.api.ProcessorContext;
-import org.apache.tez.runtime.library.api.KeyValueWriter;
-
-import com.google.common.base.Preconditions;
-
-public class IntersectDataGen extends Configured implements Tool {
-
- private static final Log LOG = LogFactory.getLog(IntersectDataGen.class);
-
- private static final String STREAM_OUTPUT_NAME = "streamoutput";
- private static final String HASH_OUTPUT_NAME = "hashoutput";
- private static final String EXPECTED_OUTPUT_NAME = "expectedoutput";
-
- public static void main(String[] args) throws Exception {
- IntersectDataGen dataGen = new IntersectDataGen();
- int status = ToolRunner.run(new Configuration(), dataGen, args);
- System.exit(status);
- }
-
- private static void printUsage() {
- System.err
- .println("Usage: "
- + "intersectdatagen <outPath1> <path1Size> <outPath2> <path2Size> <expectedResultPath> <numTasks>");
- ;
- ToolRunner.printGenericCommandUsage(System.err);
- }
-
- @Override
- public int run(String[] args) throws Exception {
- Configuration conf = getConf();
- String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
- int result = validateArgs(otherArgs);
- if (result != 0) {
- return result;
- }
- return execute(otherArgs);
- }
-
- public int run(Configuration conf, String[] args, TezClient tezSession) throws Exception {
- setConf(conf);
- String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
- int result = validateArgs(otherArgs);
- if (result != 0) {
- return result;
- }
- return execute(otherArgs, tezSession);
- }
-
- private int validateArgs(String[] otherArgs) {
- if (otherArgs.length != 6) {
- printUsage();
- return 2;
- }
- return 0;
- }
-
- private int execute(String [] args) throws TezException, IOException, InterruptedException {
- TezConfiguration tezConf = new TezConfiguration(getConf());
- TezClient tezSession = null;
- try {
- tezSession = createTezSession(tezConf);
- return execute(args, tezConf, tezSession);
- } finally {
- if (tezSession != null) {
- tezSession.stop();
- }
- }
- }
-
- private int execute(String[] args, TezClient tezSession) throws IOException, TezException,
- InterruptedException {
- TezConfiguration tezConf = new TezConfiguration(getConf());
- return execute(args, tezConf, tezSession);
- }
-
- private TezClient createTezSession(TezConfiguration tezConf) throws TezException, IOException {
- TezClient tezSession = TezClient.create("IntersectDataGenSession", tezConf);
- tezSession.start();
- return tezSession;
- }
-
- private int execute(String[] args, TezConfiguration tezConf, TezClient tezSession)
- throws IOException, TezException, InterruptedException {
- LOG.info("Running IntersectDataGen");
-
- UserGroupInformation.setConfiguration(tezConf);
-
- String outDir1 = args[0];
- long outDir1Size = Long.parseLong(args[1]);
- String outDir2 = args[2];
- long outDir2Size = Long.parseLong(args[3]);
- String expectedOutputDir = args[4];
- int numTasks = Integer.parseInt(args[5]);
-
- Path largeOutPath = null;
- Path smallOutPath = null;
- long largeOutSize = 0;
- long smallOutSize = 0;
-
- if (outDir1Size >= outDir2Size) {
- largeOutPath = new Path(outDir1);
- largeOutSize = outDir1Size;
- smallOutPath = new Path(outDir2);
- smallOutSize = outDir2Size;
- } else {
- largeOutPath = new Path(outDir2);
- largeOutSize = outDir2Size;
- smallOutPath = new Path(outDir1);
- smallOutSize = outDir1Size;
- }
-
- Path expectedOutputPath = new Path(expectedOutputDir);
-
- // Verify output path existence
- FileSystem fs = FileSystem.get(tezConf);
- int res = 0;
- res = checkOutputDirectory(fs, largeOutPath) + checkOutputDirectory(fs, smallOutPath)
- + checkOutputDirectory(fs, expectedOutputPath);
- if (res != 0) {
- return 3;
- }
-
- if (numTasks <= 0) {
- System.err.println("NumTasks must be > 0");
- return 4;
- }
-
- DAG dag = createDag(tezConf, largeOutPath, smallOutPath, expectedOutputPath, numTasks,
- largeOutSize, smallOutSize);
-
- tezSession.waitTillReady();
- DAGClient dagClient = tezSession.submitDAG(dag);
- DAGStatus dagStatus = dagClient.waitForCompletionWithStatusUpdates(null);
- if (dagStatus.getState() != DAGStatus.State.SUCCEEDED) {
- LOG.info("DAG diagnostics: " + dagStatus.getDiagnostics());
- return -1;
- }
- return 0;
-
- }
-
- private DAG createDag(TezConfiguration tezConf, Path largeOutPath, Path smallOutPath,
- Path expectedOutputPath, int numTasks, long largeOutSize, long smallOutSize)
- throws IOException {
-
- long largeOutSizePerTask = largeOutSize / numTasks;
- long smallOutSizePerTask = smallOutSize / numTasks;
-
- DAG dag = new DAG("IntersectDataGen");
-
- Vertex genDataVertex = Vertex.create("datagen", ProcessorDescriptor.create(
- GenDataProcessor.class.getName()).setUserPayload(
- UserPayload.create(ByteBuffer.wrap(GenDataProcessor.createConfiguration(largeOutSizePerTask,
- smallOutSizePerTask)))), numTasks);
- genDataVertex.addDataSink(STREAM_OUTPUT_NAME,
- MROutput.createConfigBuilder(new Configuration(tezConf),
- TextOutputFormat.class, largeOutPath.toUri().toString()).build());
- genDataVertex.addDataSink(HASH_OUTPUT_NAME,
- MROutput.createConfigBuilder(new Configuration(tezConf),
- TextOutputFormat.class, smallOutPath.toUri().toString()).build());
- genDataVertex.addDataSink(EXPECTED_OUTPUT_NAME,
- MROutput.createConfigBuilder(new Configuration(tezConf),
- TextOutputFormat.class, expectedOutputPath.toUri().toString()).build());
-
- dag.addVertex(genDataVertex);
-
- return dag;
- }
-
- public static class GenDataProcessor extends SimpleMRProcessor {
-
- private static final Log LOG = LogFactory.getLog(GenDataProcessor.class);
-
- long streamOutputFileSize;
- long hashOutputFileSize;
- float overlapApprox = 0.2f;
-
- public GenDataProcessor(ProcessorContext context) {
- super(context);
- }
-
- public static byte[] createConfiguration(long streamOutputFileSize, long hashOutputFileSize)
- throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(bos);
- dos.writeLong(streamOutputFileSize);
- dos.writeLong(hashOutputFileSize);
- dos.close();
- bos.close();
- return bos.toByteArray();
- }
-
- @Override
- public void initialize() throws Exception {
- byte[] payload = getContext().getUserPayload().deepCopyAsArray();
- ByteArrayInputStream bis = new ByteArrayInputStream(payload);
- DataInputStream dis = new DataInputStream(bis);
- streamOutputFileSize = dis.readLong();
- hashOutputFileSize = dis.readLong();
- LOG.info("Initialized with largeFileTargetSize=" + streamOutputFileSize
- + ", smallFileTragetSize=" + hashOutputFileSize);
- dis.close();
- bis.close();
- }
-
- @Override
- public void run() throws Exception {
- Preconditions.checkState(getInputs().size() == 0);
- Preconditions.checkState(getOutputs().size() == 3);
-
- KeyValueWriter streamOutputWriter = (KeyValueWriter) getOutputs().get(STREAM_OUTPUT_NAME)
- .getWriter();
- KeyValueWriter hashOutputWriter = (KeyValueWriter) getOutputs().get(HASH_OUTPUT_NAME)
- .getWriter();
- KeyValueWriter expectedOutputWriter = (KeyValueWriter) getOutputs().get(EXPECTED_OUTPUT_NAME)
- .getWriter();
-
- float fileSizeFraction = hashOutputFileSize / (float) streamOutputFileSize;
- Preconditions.checkState(fileSizeFraction > 0.0f && fileSizeFraction <= 1.0f);
- int mod = 1;
- int extraKeysMod = 0;
- if (fileSizeFraction > overlapApprox) {
- // Common keys capped by overlap. Additional ones required in the hashFile.
- mod = (int) (1 / overlapApprox);
- extraKeysMod = (int) (1 / (fileSizeFraction - overlapApprox));
- } else {
- // All keys in hashFile must exist in stream file.
- mod = (int) (1 / fileSizeFraction);
- }
- LOG.info("Using mod=" + mod + ", extraKeysMod=" + extraKeysMod);
-
- long count = 0;
- long sizeLarge = 0;
- long sizeSmall = 0;
- long numLargeFileKeys = 0;
- long numSmallFileKeys = 0;
- long numExpectedKeys = 0;
- while (sizeLarge < streamOutputFileSize) {
- String str = createOverlapString(13, count);
- Text text = new Text(str);
- int size = text.getLength();
- streamOutputWriter.write(text, NullWritable.get());
- sizeLarge += size;
- numLargeFileKeys++;
- if (count % mod == 0) {
- hashOutputWriter.write(text, NullWritable.get());
- sizeSmall += size;
- numSmallFileKeys++;
- expectedOutputWriter.write(text, NullWritable.get());
- numExpectedKeys++;
- }
- if (extraKeysMod != 0 && count % extraKeysMod == 0) {
- String nStr = createNonOverlaptring(13, count);
- Text nText = new Text(nStr);
- hashOutputWriter.write(nText, NullWritable.get());
- sizeSmall += nText.getLength();
- numSmallFileKeys++;
- }
- count++;
- }
- LOG.info("OutputStats: " + "largeFileNumKeys=" + numLargeFileKeys + ", smallFileNumKeys="
- + numSmallFileKeys + ", expFileNumKeys=" + numExpectedKeys + ", largeFileSize="
- + sizeLarge + ", smallFileSize=" + sizeSmall);
- }
-
- private String createOverlapString(int size, long count) {
- StringBuilder sb = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < size; i++) {
- int r = Math.abs(random.nextInt()) % 26;
- // Random a-z followed by the count
- sb.append((char) (97 + r));
- }
- sb.append("_").append(getContext().getTaskIndex()).append("_").append(count);
- return sb.toString();
- }
-
- private String createNonOverlaptring(int size, long count) {
- StringBuilder sb = new StringBuilder();
- Random random = new Random();
- for (int i = 0; i < size; i++) {
- int r = Math.abs(random.nextInt()) % 26;
- // Random A-Z followed by the count
- sb.append((char) (65 + r));
- }
- sb.append("_").append(getContext().getTaskIndex()).append("_").append(count);
- return sb.toString();
- }
-
- }
-
- private int checkOutputDirectory(FileSystem fs, Path path) throws IOException {
- if (fs.exists(path)) {
- System.err.println("Output directory: " + path + " already exists");
- return 2;
- }
- return 0;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/IntersectExample.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/IntersectExample.java b/tez-examples/src/main/java/org/apache/tez/examples/IntersectExample.java
deleted file mode 100644
index bf5897d..0000000
--- a/tez-examples/src/main/java/org/apache/tez/examples/IntersectExample.java
+++ /dev/null
@@ -1,281 +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.tez.examples;
-
-import java.io.IOException;
-import java.util.HashSet;
-
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.NullWritable;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
-import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.util.GenericOptionsParser;
-import org.apache.hadoop.util.Tool;
-import org.apache.hadoop.util.ToolRunner;
-import org.apache.tez.client.TezClient;
-import org.apache.tez.dag.api.DAG;
-import org.apache.tez.dag.api.Edge;
-import org.apache.tez.dag.api.ProcessorDescriptor;
-import org.apache.tez.dag.api.TezConfiguration;
-import org.apache.tez.dag.api.TezException;
-import org.apache.tez.dag.api.Vertex;
-import org.apache.tez.dag.api.client.DAGClient;
-import org.apache.tez.dag.api.client.DAGStatus;
-import org.apache.tez.mapreduce.input.MRInput;
-import org.apache.tez.mapreduce.output.MROutput;
-import org.apache.tez.mapreduce.processor.SimpleMRProcessor;
-import org.apache.tez.runtime.api.LogicalInput;
-import org.apache.tez.runtime.api.LogicalOutput;
-import org.apache.tez.runtime.api.Reader;
-import org.apache.tez.runtime.api.ProcessorContext;
-import org.apache.tez.runtime.library.api.KeyValueReader;
-import org.apache.tez.runtime.library.api.KeyValueWriter;
-import org.apache.tez.runtime.library.conf.UnorderedPartitionedKVEdgeConfig;
-import org.apache.tez.runtime.library.partitioner.HashPartitioner;
-import org.apache.tez.runtime.library.processor.SimpleProcessor;
-
-import com.google.common.base.Preconditions;
-
-public class IntersectExample extends Configured implements Tool {
-
- private static final Log LOG = LogFactory.getLog(IntersectExample.class);
-
- public static void main(String[] args) throws Exception {
- IntersectExample intersect = new IntersectExample();
- int status = ToolRunner.run(new Configuration(), intersect, args);
- System.exit(status);
- }
-
- private static void printUsage() {
- System.err.println("Usage: " + "intersect <file1> <file2> <numPartitions> <outPath>");
- ToolRunner.printGenericCommandUsage(System.err);
- }
-
- @Override
- public int run(String[] args) throws Exception {
- Configuration conf = getConf();
- String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
- int result = validateArgs(otherArgs);
- if (result != 0) {
- return result;
- }
- return execute(otherArgs);
- }
-
- public int run(Configuration conf, String[] args, TezClient tezSession) throws Exception {
- setConf(conf);
- String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
- int result = validateArgs(otherArgs);
- if (result != 0) {
- return result;
- }
- return execute(otherArgs, tezSession);
- }
-
- private int validateArgs(String[] otherArgs) {
- if (otherArgs.length != 4) {
- printUsage();
- return 2;
- }
- return 0;
- }
-
- private int execute(String[] args) throws TezException, IOException, InterruptedException {
- TezConfiguration tezConf = new TezConfiguration(getConf());
- TezClient tezSession = null;
- try {
- tezSession = createTezSession(tezConf);
- return execute(args, tezConf, tezSession);
- } finally {
- if (tezSession != null) {
- tezSession.stop();
- }
- }
- }
-
- private int execute(String[] args, TezClient tezSession) throws IOException, TezException,
- InterruptedException {
- TezConfiguration tezConf = new TezConfiguration(getConf());
- return execute(args, tezConf, tezSession);
- }
-
- private TezClient createTezSession(TezConfiguration tezConf) throws TezException, IOException {
- TezClient tezSession = TezClient.create("IntersectExampleSession", tezConf);
- tezSession.start();
- return tezSession;
- }
-
- private int execute(String[] args, TezConfiguration tezConf, TezClient tezSession)
- throws IOException, TezException, InterruptedException {
- LOG.info("Running IntersectExample");
-
- UserGroupInformation.setConfiguration(tezConf);
-
- String streamInputDir = args[0];
- String hashInputDir = args[1];
- int numPartitions = Integer.parseInt(args[2]);
- String outputDir = args[3];
-
- Path streamInputPath = new Path(streamInputDir);
- Path hashInputPath = new Path(hashInputDir);
- Path outputPath = new Path(outputDir);
-
- // Verify output path existence
- FileSystem fs = FileSystem.get(tezConf);
- if (fs.exists(outputPath)) {
- System.err.println("Output directory: " + outputDir + " already exists");
- return 3;
- }
- if (numPartitions <= 0) {
- System.err.println("NumPartitions must be > 0");
- return 4;
- }
-
- DAG dag = createDag(tezConf, streamInputPath, hashInputPath, outputPath, numPartitions);
-
- tezSession.waitTillReady();
- DAGClient dagClient = tezSession.submitDAG(dag);
- DAGStatus dagStatus = dagClient.waitForCompletionWithStatusUpdates(null);
- if (dagStatus.getState() != DAGStatus.State.SUCCEEDED) {
- LOG.info("DAG diagnostics: " + dagStatus.getDiagnostics());
- return -1;
- }
- return 0;
-
- }
-
- private DAG createDag(TezConfiguration tezConf, Path streamPath, Path hashPath, Path outPath,
- int numPartitions) throws IOException {
- DAG dag = new DAG("IntersectExample");
-
- // Configuration for intermediate output - shared by Vertex1 and Vertex2
- // This should only be setting selective keys from the underlying conf. Fix after there's a
- // better mechanism to configure the IOs.
-
- UnorderedPartitionedKVEdgeConfig edgeConf =
- UnorderedPartitionedKVEdgeConfig
- .newBuilder(Text.class.getName(), NullWritable.class.getName(),
- HashPartitioner.class.getName()).build();
-
- // Change the way resources are setup - no MRHelpers
- Vertex streamFileVertex = Vertex.create("partitioner1", ProcessorDescriptor.create(
- ForwardingProcessor.class.getName())).addDataSource(
- "streamfile",
- MRInput
- .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
- streamPath.toUri().toString()).groupSplits(false).build());
-
- Vertex hashFileVertex = Vertex.create("partitioner2", ProcessorDescriptor.create(
- ForwardingProcessor.class.getName())).addDataSource(
- "hashfile",
- MRInput
- .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
- hashPath.toUri().toString()).groupSplits(false).build());
-
- Vertex intersectVertex = Vertex.create("intersect", ProcessorDescriptor.create(
- IntersectProcessor.class.getName()), numPartitions).addDataSink("finalOutput",
- MROutput.createConfigBuilder(new Configuration(tezConf),
- TextOutputFormat.class, outPath.toUri().toString()).build());
-
- Edge e1 = Edge.create(streamFileVertex, intersectVertex, edgeConf.createDefaultEdgeProperty());
-
- Edge e2 = Edge.create(hashFileVertex, intersectVertex, edgeConf.createDefaultEdgeProperty());
-
- dag.addVertex(streamFileVertex).addVertex(hashFileVertex).addVertex(intersectVertex)
- .addEdge(e1).addEdge(e2);
- return dag;
- }
-
- // private void obtainTokens(Credentials credentials, Path... paths) throws IOException {
- // TokenCache.obtainTokensForNamenodes(credentials, paths, getConf());
- // }
-
- /**
- * Reads key-values from the source and forwards the value as the key for the output
- */
- public static class ForwardingProcessor extends SimpleProcessor {
- public ForwardingProcessor(ProcessorContext context) {
- super(context);
- }
-
- @Override
- public void run() throws Exception {
- Preconditions.checkState(getInputs().size() == 1);
- Preconditions.checkState(getOutputs().size() == 1);
- LogicalInput input = getInputs().values().iterator().next();
- Reader rawReader = input.getReader();
- Preconditions.checkState(rawReader instanceof KeyValueReader);
- LogicalOutput output = getOutputs().values().iterator().next();
-
- KeyValueReader reader = (KeyValueReader) rawReader;
- KeyValueWriter writer = (KeyValueWriter) output.getWriter();
-
- while (reader.next()) {
- Object val = reader.getCurrentValue();
- writer.write(val, NullWritable.get());
- }
- }
- }
-
- public static class IntersectProcessor extends SimpleMRProcessor {
-
- public IntersectProcessor(ProcessorContext context) {
- super(context);
- }
-
- @Override
- public void run() throws Exception {
- Preconditions.checkState(getInputs().size() == 2);
- Preconditions.checkState(getOutputs().size() == 1);
- LogicalInput streamInput = getInputs().get("partitioner1");
- LogicalInput hashInput = getInputs().get("partitioner2");
- Reader rawStreamReader = streamInput.getReader();
- Reader rawHashReader = hashInput.getReader();
- Preconditions.checkState(rawStreamReader instanceof KeyValueReader);
- Preconditions.checkState(rawHashReader instanceof KeyValueReader);
- LogicalOutput lo = getOutputs().values().iterator().next();
- Preconditions.checkState(lo instanceof MROutput);
- MROutput output = (MROutput) lo;
- KeyValueWriter writer = output.getWriter();
-
- KeyValueReader hashKvReader = (KeyValueReader) rawHashReader;
- Set<Text> keySet = new HashSet<Text>();
- while (hashKvReader.next()) {
- keySet.add(new Text((Text) hashKvReader.getCurrentKey()));
- }
-
- KeyValueReader streamKvReader = (KeyValueReader) rawStreamReader;
- while (streamKvReader.next()) {
- Text key = (Text) streamKvReader.getCurrentKey();
- if (keySet.contains(key)) {
- writer.write(key, NullWritable.get());
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/IntersectValidate.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/IntersectValidate.java b/tez-examples/src/main/java/org/apache/tez/examples/IntersectValidate.java
deleted file mode 100644
index 24ba2df..0000000
--- a/tez-examples/src/main/java/org/apache/tez/examples/IntersectValidate.java
+++ /dev/null
@@ -1,257 +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.tez.examples;
-
-import java.io.IOException;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.conf.Configured;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.io.NullWritable;
-import org.apache.hadoop.io.Text;
-import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.util.GenericOptionsParser;
-import org.apache.hadoop.util.Tool;
-import org.apache.hadoop.util.ToolRunner;
-import org.apache.tez.client.TezClient;
-import org.apache.tez.common.counters.TezCounter;
-import org.apache.tez.dag.api.DAG;
-import org.apache.tez.dag.api.Edge;
-import org.apache.tez.dag.api.ProcessorDescriptor;
-import org.apache.tez.dag.api.TezConfiguration;
-import org.apache.tez.dag.api.TezException;
-import org.apache.tez.dag.api.Vertex;
-import org.apache.tez.dag.api.client.DAGClient;
-import org.apache.tez.dag.api.client.DAGStatus;
-import org.apache.tez.dag.api.client.StatusGetOpts;
-import org.apache.tez.examples.IntersectExample.ForwardingProcessor;
-import org.apache.tez.mapreduce.input.MRInput;
-import org.apache.tez.runtime.api.LogicalInput;
-import org.apache.tez.runtime.api.Reader;
-import org.apache.tez.runtime.api.ProcessorContext;
-import org.apache.tez.runtime.library.api.KeyValuesReader;
-import org.apache.tez.runtime.library.conf.OrderedPartitionedKVEdgeConfig;
-import org.apache.tez.runtime.library.partitioner.HashPartitioner;
-import org.apache.tez.runtime.library.processor.SimpleProcessor;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
-
-public class IntersectValidate extends Configured implements Tool {
- private static final Log LOG = LogFactory.getLog(IntersectExample.class);
-
- private static final String LHS_INPUT_NAME = "lhsfile";
- private static final String RHS_INPUT_NAME = "rhsfile";
-
- private static final String COUNTER_GROUP_NAME = "INTERSECT_VALIDATE";
- private static final String MISSING_KEY_COUNTER_NAME = "MISSING_KEY_EXISTS";
-
- public static void main(String[] args) throws Exception {
- IntersectValidate validate = new IntersectValidate();
- int status = ToolRunner.run(new Configuration(), validate, args);
- System.exit(status);
- }
-
- private static void printUsage() {
- System.err.println("Usage: " + "intersectvalidate <path1> <path2>");
- ToolRunner.printGenericCommandUsage(System.err);
- }
-
- @Override
- public int run(String[] args) throws Exception {
- Configuration conf = getConf();
- String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
- int result = validateArgs(otherArgs);
- if (result != 0) {
- return result;
- }
- return execute(otherArgs);
- }
-
- public int run(Configuration conf, String[] args, TezClient tezSession) throws Exception {
- setConf(conf);
- String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
- int result = validateArgs(otherArgs);
- if (result != 0) {
- return result;
- }
- return execute(otherArgs, tezSession);
- }
-
- private int validateArgs(String[] otherArgs) {
- if (otherArgs.length != 3 && otherArgs.length != 2) {
- printUsage();
- return 2;
- }
- return 0;
- }
-
- private int execute(String[] args) throws TezException, IOException, InterruptedException {
- TezConfiguration tezConf = new TezConfiguration(getConf());
- TezClient tezSession = null;
- try {
- tezSession = createTezSession(tezConf);
- return execute(args, tezConf, tezSession);
- } finally {
- if (tezSession != null) {
- tezSession.stop();
- }
- }
- }
-
- private int execute(String[] args, TezClient tezSession) throws IOException, TezException,
- InterruptedException {
- TezConfiguration tezConf = new TezConfiguration(getConf());
- return execute(args, tezConf, tezSession);
- }
-
- private TezClient createTezSession(TezConfiguration tezConf) throws TezException, IOException {
- TezClient tezSession = TezClient.create("IntersectValidateSession", tezConf);
- tezSession.start();
- return tezSession;
- }
-
- private int execute(String[] args, TezConfiguration tezConf, TezClient tezSession)
- throws IOException, TezException, InterruptedException {
- LOG.info("Running IntersectValidate");
- UserGroupInformation.setConfiguration(tezConf);
-
- String lhsDir = args[0];
- String rhsDir = args[1];
- int numPartitions = 1;
- if (args.length == 3) {
- numPartitions = Integer.parseInt(args[2]);
- }
-
- if (numPartitions <= 0) {
- System.err.println("NumPartitions must be > 0");
- return 4;
- }
-
- Path lhsPath = new Path(lhsDir);
- Path rhsPath = new Path(rhsDir);
-
- DAG dag = createDag(tezConf, lhsPath, rhsPath, numPartitions);
-
- tezSession.waitTillReady();
- DAGClient dagClient = tezSession.submitDAG(dag);
- DAGStatus dagStatus = dagClient.waitForCompletionWithStatusUpdates(null);
- if (dagStatus.getState() != DAGStatus.State.SUCCEEDED) {
- LOG.info("DAG diagnostics: " + dagStatus.getDiagnostics());
- return -1;
- } else {
- dagStatus = dagClient.getDAGStatus(Sets.newHashSet(StatusGetOpts.GET_COUNTERS));
- TezCounter counter = dagStatus.getDAGCounters().findCounter(COUNTER_GROUP_NAME,
- MISSING_KEY_COUNTER_NAME);
- if (counter == null) {
- LOG.info("Unable to determing equality");
- return -2;
- } else {
- if (counter.getValue() != 0) {
- LOG.info("Validate failed. The two sides are not equivalent");
- return -3;
- } else {
- LOG.info("Validation successful. The two sides are equivalent");
- return 0;
- }
- }
- }
- }
-
- private DAG createDag(TezConfiguration tezConf, Path lhs, Path rhs, int numPartitions)
- throws IOException {
- DAG dag = new DAG("IntersectValidate");
-
- // Configuration for intermediate output - shared by Vertex1 and Vertex2
- // This should only be setting selective keys from the underlying conf. Fix after there's a
- // better mechanism to configure the IOs.
- OrderedPartitionedKVEdgeConfig edgeConf = OrderedPartitionedKVEdgeConfig
- .newBuilder(Text.class.getName(), NullWritable.class.getName(),
- HashPartitioner.class.getName()).build();
-
- Vertex lhsVertex = Vertex.create(LHS_INPUT_NAME, ProcessorDescriptor.create(
- ForwardingProcessor.class.getName())).addDataSource("lhs",
- MRInput
- .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
- lhs.toUri().toString()).groupSplits(false).build());
-
- Vertex rhsVertex = Vertex.create(RHS_INPUT_NAME, ProcessorDescriptor.create(
- ForwardingProcessor.class.getName())).addDataSource("rhs",
- MRInput
- .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
- rhs.toUri().toString()).groupSplits(false).build());
-
- Vertex intersectValidateVertex = Vertex.create("intersectvalidate", ProcessorDescriptor.create(
- IntersectValidateProcessor.class.getName()), numPartitions);
-
- Edge e1 = Edge.create(lhsVertex, intersectValidateVertex, edgeConf.createDefaultEdgeProperty());
- Edge e2 = Edge.create(rhsVertex, intersectValidateVertex, edgeConf.createDefaultEdgeProperty());
-
- dag.addVertex(lhsVertex).addVertex(rhsVertex).addVertex(intersectValidateVertex).addEdge(e1)
- .addEdge(e2);
- return dag;
- }
-
- public static class IntersectValidateProcessor extends SimpleProcessor {
-
- private static final Log LOG = LogFactory.getLog(IntersectValidateProcessor.class);
-
- public IntersectValidateProcessor(ProcessorContext context) {
- super(context);
- }
-
- @Override
- public void run() throws Exception {
- Preconditions.checkState(getInputs().size() == 2);
- Preconditions.checkState(getOutputs().size() == 0);
- LogicalInput lhsInput = getInputs().get(LHS_INPUT_NAME);
- LogicalInput rhsInput = getInputs().get(RHS_INPUT_NAME);
- Reader lhsReaderRaw = lhsInput.getReader();
- Reader rhsReaderRaw = rhsInput.getReader();
- Preconditions.checkState(lhsReaderRaw instanceof KeyValuesReader);
- Preconditions.checkState(rhsReaderRaw instanceof KeyValuesReader);
- KeyValuesReader lhsReader = (KeyValuesReader) lhsReaderRaw;
- KeyValuesReader rhsReader = (KeyValuesReader) rhsReaderRaw;
-
- TezCounter lhsMissingKeyCounter = getContext().getCounters().findCounter(COUNTER_GROUP_NAME,
- MISSING_KEY_COUNTER_NAME);
-
- while (lhsReader.next()) {
- if (rhsReader.next()) {
- if (!lhsReader.getCurrentKey().equals(rhsReader.getCurrentKey())) {
- LOG.info("MismatchedKeys: " + "lhs=" + lhsReader.getCurrentKey() + ", rhs=" + rhsReader.getCurrentKey());
- lhsMissingKeyCounter.increment(1);
- }
- } else {
- lhsMissingKeyCounter.increment(1);
- LOG.info("ExtraKey in lhs: " + lhsReader.getClass());
- break;
- }
- }
- if (rhsReader.next()) {
- lhsMissingKeyCounter.increment(1);
- LOG.info("ExtraKey in rhs: " + lhsReader.getClass());
- }
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/JoinDataGen.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/JoinDataGen.java b/tez-examples/src/main/java/org/apache/tez/examples/JoinDataGen.java
new file mode 100644
index 0000000..c20f24b
--- /dev/null
+++ b/tez-examples/src/main/java/org/apache/tez/examples/JoinDataGen.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 org.apache.tez.examples;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.Random;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.NullWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.util.GenericOptionsParser;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.tez.client.TezClient;
+import org.apache.tez.dag.api.DAG;
+import org.apache.tez.dag.api.ProcessorDescriptor;
+import org.apache.tez.dag.api.TezConfiguration;
+import org.apache.tez.dag.api.TezException;
+import org.apache.tez.dag.api.UserPayload;
+import org.apache.tez.dag.api.Vertex;
+import org.apache.tez.dag.api.client.DAGClient;
+import org.apache.tez.dag.api.client.DAGStatus;
+import org.apache.tez.mapreduce.output.MROutput;
+import org.apache.tez.mapreduce.processor.SimpleMRProcessor;
+import org.apache.tez.runtime.api.ProcessorContext;
+import org.apache.tez.runtime.library.api.KeyValueWriter;
+
+import com.google.common.base.Preconditions;
+
+public class JoinDataGen extends Configured implements Tool {
+
+ private static final Log LOG = LogFactory.getLog(JoinDataGen.class);
+
+ private static final String STREAM_OUTPUT_NAME = "streamoutput";
+ private static final String HASH_OUTPUT_NAME = "hashoutput";
+ private static final String EXPECTED_OUTPUT_NAME = "expectedoutput";
+
+ public static void main(String[] args) throws Exception {
+ JoinDataGen dataGen = new JoinDataGen();
+ int status = ToolRunner.run(new Configuration(), dataGen, args);
+ System.exit(status);
+ }
+
+ private static void printUsage() {
+ System.err
+ .println("Usage: "
+ + "joindatagen <outPath1> <path1Size> <outPath2> <path2Size> <expectedResultPath> <numTasks>");
+ ;
+ ToolRunner.printGenericCommandUsage(System.err);
+ }
+
+ @Override
+ public int run(String[] args) throws Exception {
+ Configuration conf = getConf();
+ String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
+ int result = validateArgs(otherArgs);
+ if (result != 0) {
+ return result;
+ }
+ return execute(otherArgs);
+ }
+
+ public int run(Configuration conf, String[] args, TezClient tezClient) throws Exception {
+ setConf(conf);
+ String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
+ int result = validateArgs(otherArgs);
+ if (result != 0) {
+ return result;
+ }
+ return execute(otherArgs, tezClient);
+ }
+
+ private int validateArgs(String[] otherArgs) {
+ if (otherArgs.length != 6) {
+ printUsage();
+ return 2;
+ }
+ return 0;
+ }
+
+ private int execute(String [] args) throws TezException, IOException, InterruptedException {
+ TezConfiguration tezConf = new TezConfiguration(getConf());
+ TezClient tezClient = null;
+ try {
+ tezClient = createTezClient(tezConf);
+ return execute(args, tezConf, tezClient);
+ } finally {
+ if (tezClient != null) {
+ tezClient.stop();
+ }
+ }
+ }
+
+ private int execute(String[] args, TezClient tezClient) throws IOException, TezException,
+ InterruptedException {
+ TezConfiguration tezConf = new TezConfiguration(getConf());
+ return execute(args, tezConf, tezClient);
+ }
+
+ private TezClient createTezClient(TezConfiguration tezConf) throws TezException, IOException {
+ TezClient tezClient = TezClient.create("JoinDataGen", tezConf);
+ tezClient.start();
+ return tezClient;
+ }
+
+ private int execute(String[] args, TezConfiguration tezConf, TezClient tezClient)
+ throws IOException, TezException, InterruptedException {
+ LOG.info("Running JoinDataGen");
+
+ UserGroupInformation.setConfiguration(tezConf);
+
+ String outDir1 = args[0];
+ long outDir1Size = Long.parseLong(args[1]);
+ String outDir2 = args[2];
+ long outDir2Size = Long.parseLong(args[3]);
+ String expectedOutputDir = args[4];
+ int numTasks = Integer.parseInt(args[5]);
+
+ Path largeOutPath = null;
+ Path smallOutPath = null;
+ long largeOutSize = 0;
+ long smallOutSize = 0;
+
+ if (outDir1Size >= outDir2Size) {
+ largeOutPath = new Path(outDir1);
+ largeOutSize = outDir1Size;
+ smallOutPath = new Path(outDir2);
+ smallOutSize = outDir2Size;
+ } else {
+ largeOutPath = new Path(outDir2);
+ largeOutSize = outDir2Size;
+ smallOutPath = new Path(outDir1);
+ smallOutSize = outDir1Size;
+ }
+
+ Path expectedOutputPath = new Path(expectedOutputDir);
+
+ // Verify output path existence
+ FileSystem fs = FileSystem.get(tezConf);
+ int res = 0;
+ res = checkOutputDirectory(fs, largeOutPath) + checkOutputDirectory(fs, smallOutPath)
+ + checkOutputDirectory(fs, expectedOutputPath);
+ if (res != 0) {
+ return 3;
+ }
+
+ if (numTasks <= 0) {
+ System.err.println("NumTasks must be > 0");
+ return 4;
+ }
+
+ DAG dag = createDag(tezConf, largeOutPath, smallOutPath, expectedOutputPath, numTasks,
+ largeOutSize, smallOutSize);
+
+ tezClient.waitTillReady();
+ DAGClient dagClient = tezClient.submitDAG(dag);
+ DAGStatus dagStatus = dagClient.waitForCompletionWithStatusUpdates(null);
+ if (dagStatus.getState() != DAGStatus.State.SUCCEEDED) {
+ LOG.info("DAG diagnostics: " + dagStatus.getDiagnostics());
+ return -1;
+ }
+ return 0;
+
+ }
+
+ private DAG createDag(TezConfiguration tezConf, Path largeOutPath, Path smallOutPath,
+ Path expectedOutputPath, int numTasks, long largeOutSize, long smallOutSize)
+ throws IOException {
+
+ long largeOutSizePerTask = largeOutSize / numTasks;
+ long smallOutSizePerTask = smallOutSize / numTasks;
+
+ DAG dag = new DAG("JoinDataGen");
+
+ Vertex genDataVertex = Vertex.create("datagen", ProcessorDescriptor.create(
+ GenDataProcessor.class.getName()).setUserPayload(
+ UserPayload.create(ByteBuffer.wrap(GenDataProcessor.createConfiguration(largeOutSizePerTask,
+ smallOutSizePerTask)))), numTasks);
+ genDataVertex.addDataSink(STREAM_OUTPUT_NAME,
+ MROutput.createConfigBuilder(new Configuration(tezConf),
+ TextOutputFormat.class, largeOutPath.toUri().toString()).build());
+ genDataVertex.addDataSink(HASH_OUTPUT_NAME,
+ MROutput.createConfigBuilder(new Configuration(tezConf),
+ TextOutputFormat.class, smallOutPath.toUri().toString()).build());
+ genDataVertex.addDataSink(EXPECTED_OUTPUT_NAME,
+ MROutput.createConfigBuilder(new Configuration(tezConf),
+ TextOutputFormat.class, expectedOutputPath.toUri().toString()).build());
+
+ dag.addVertex(genDataVertex);
+
+ return dag;
+ }
+
+ public static class GenDataProcessor extends SimpleMRProcessor {
+
+ private static final Log LOG = LogFactory.getLog(GenDataProcessor.class);
+
+ long streamOutputFileSize;
+ long hashOutputFileSize;
+ float overlapApprox = 0.2f;
+
+ public GenDataProcessor(ProcessorContext context) {
+ super(context);
+ }
+
+ public static byte[] createConfiguration(long streamOutputFileSize, long hashOutputFileSize)
+ throws IOException {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ DataOutputStream dos = new DataOutputStream(bos);
+ dos.writeLong(streamOutputFileSize);
+ dos.writeLong(hashOutputFileSize);
+ dos.close();
+ bos.close();
+ return bos.toByteArray();
+ }
+
+ @Override
+ public void initialize() throws Exception {
+ byte[] payload = getContext().getUserPayload().deepCopyAsArray();
+ ByteArrayInputStream bis = new ByteArrayInputStream(payload);
+ DataInputStream dis = new DataInputStream(bis);
+ streamOutputFileSize = dis.readLong();
+ hashOutputFileSize = dis.readLong();
+ LOG.info("Initialized with largeFileTargetSize=" + streamOutputFileSize
+ + ", smallFileTragetSize=" + hashOutputFileSize);
+ dis.close();
+ bis.close();
+ }
+
+ @Override
+ public void run() throws Exception {
+ Preconditions.checkState(getInputs().size() == 0);
+ Preconditions.checkState(getOutputs().size() == 3);
+
+ KeyValueWriter streamOutputWriter = (KeyValueWriter) getOutputs().get(STREAM_OUTPUT_NAME)
+ .getWriter();
+ KeyValueWriter hashOutputWriter = (KeyValueWriter) getOutputs().get(HASH_OUTPUT_NAME)
+ .getWriter();
+ KeyValueWriter expectedOutputWriter = (KeyValueWriter) getOutputs().get(EXPECTED_OUTPUT_NAME)
+ .getWriter();
+
+ float fileSizeFraction = hashOutputFileSize / (float) streamOutputFileSize;
+ Preconditions.checkState(fileSizeFraction > 0.0f && fileSizeFraction <= 1.0f);
+ int mod = 1;
+ int extraKeysMod = 0;
+ if (fileSizeFraction > overlapApprox) {
+ // Common keys capped by overlap. Additional ones required in the hashFile.
+ mod = (int) (1 / overlapApprox);
+ extraKeysMod = (int) (1 / (fileSizeFraction - overlapApprox));
+ } else {
+ // All keys in hashFile must exist in stream file.
+ mod = (int) (1 / fileSizeFraction);
+ }
+ LOG.info("Using mod=" + mod + ", extraKeysMod=" + extraKeysMod);
+
+ long count = 0;
+ long sizeLarge = 0;
+ long sizeSmall = 0;
+ long numLargeFileKeys = 0;
+ long numSmallFileKeys = 0;
+ long numExpectedKeys = 0;
+ while (sizeLarge < streamOutputFileSize) {
+ String str = createOverlapString(13, count);
+ Text text = new Text(str);
+ int size = text.getLength();
+ streamOutputWriter.write(text, NullWritable.get());
+ sizeLarge += size;
+ numLargeFileKeys++;
+ if (count % mod == 0) {
+ hashOutputWriter.write(text, NullWritable.get());
+ sizeSmall += size;
+ numSmallFileKeys++;
+ expectedOutputWriter.write(text, NullWritable.get());
+ numExpectedKeys++;
+ }
+ if (extraKeysMod != 0 && count % extraKeysMod == 0) {
+ String nStr = createNonOverlaptring(13, count);
+ Text nText = new Text(nStr);
+ hashOutputWriter.write(nText, NullWritable.get());
+ sizeSmall += nText.getLength();
+ numSmallFileKeys++;
+ }
+ count++;
+ }
+ LOG.info("OutputStats: " + "largeFileNumKeys=" + numLargeFileKeys + ", smallFileNumKeys="
+ + numSmallFileKeys + ", expFileNumKeys=" + numExpectedKeys + ", largeFileSize="
+ + sizeLarge + ", smallFileSize=" + sizeSmall);
+ }
+
+ private String createOverlapString(int size, long count) {
+ StringBuilder sb = new StringBuilder();
+ Random random = new Random();
+ for (int i = 0; i < size; i++) {
+ int r = Math.abs(random.nextInt()) % 26;
+ // Random a-z followed by the count
+ sb.append((char) (97 + r));
+ }
+ sb.append("_").append(getContext().getTaskIndex()).append("_").append(count);
+ return sb.toString();
+ }
+
+ private String createNonOverlaptring(int size, long count) {
+ StringBuilder sb = new StringBuilder();
+ Random random = new Random();
+ for (int i = 0; i < size; i++) {
+ int r = Math.abs(random.nextInt()) % 26;
+ // Random A-Z followed by the count
+ sb.append((char) (65 + r));
+ }
+ sb.append("_").append(getContext().getTaskIndex()).append("_").append(count);
+ return sb.toString();
+ }
+
+ }
+
+ private int checkOutputDirectory(FileSystem fs, Path path) throws IOException {
+ if (fs.exists(path)) {
+ System.err.println("Output directory: " + path + " already exists");
+ return 2;
+ }
+ return 0;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/JoinExample.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/JoinExample.java b/tez-examples/src/main/java/org/apache/tez/examples/JoinExample.java
new file mode 100644
index 0000000..083cc4b
--- /dev/null
+++ b/tez-examples/src/main/java/org/apache/tez/examples/JoinExample.java
@@ -0,0 +1,364 @@
+/**
+ * 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.tez.examples;
+
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.NullWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.util.GenericOptionsParser;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.tez.client.TezClient;
+import org.apache.tez.dag.api.DAG;
+import org.apache.tez.dag.api.Edge;
+import org.apache.tez.dag.api.EdgeProperty;
+import org.apache.tez.dag.api.ProcessorDescriptor;
+import org.apache.tez.dag.api.TezConfiguration;
+import org.apache.tez.dag.api.TezException;
+import org.apache.tez.dag.api.Vertex;
+import org.apache.tez.dag.api.client.DAGClient;
+import org.apache.tez.dag.api.client.DAGStatus;
+import org.apache.tez.mapreduce.input.MRInput;
+import org.apache.tez.mapreduce.output.MROutput;
+import org.apache.tez.mapreduce.processor.SimpleMRProcessor;
+import org.apache.tez.runtime.api.LogicalInput;
+import org.apache.tez.runtime.api.LogicalOutput;
+import org.apache.tez.runtime.api.Reader;
+import org.apache.tez.runtime.api.ProcessorContext;
+import org.apache.tez.runtime.library.api.KeyValueReader;
+import org.apache.tez.runtime.library.api.KeyValueWriter;
+import org.apache.tez.runtime.library.conf.UnorderedKVEdgeConfig;
+import org.apache.tez.runtime.library.conf.UnorderedPartitionedKVEdgeConfig;
+import org.apache.tez.runtime.library.partitioner.HashPartitioner;
+import org.apache.tez.runtime.library.processor.SimpleProcessor;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * Simple example of joining 2 data sets.
+ * <br>The example shows a vertex with multiple inputs that represent the two
+ * data sets that need to be joined.
+ * <br>The join can be performed using a broadcast (or replicate-fragment) join in
+ * which the small side of the join is broadcast in total to fragments of the
+ * larger side. Each fragment of the larger side can perform the join operation
+ * independently using the full data of the smaller side. This shows the usage
+ * of the broadcast edge property in Tez.
+ * <br>The join can be performed using the regular repartition join where both
+ * sides are partitioned according to the same scheme into the same number of
+ * fragments. Then the keys in the same fragment are joined with each other. This
+ * is the default join strategy.
+ *
+ */
+public class JoinExample extends Configured implements Tool {
+
+ private static final Log LOG = LogFactory.getLog(JoinExample.class);
+
+ private static final String broadcastOption = "doBroadcast";
+ private static final String streamingSide = "streamingSide";
+ private static final String hashSide = "hashSide";
+ private static final String inputFile = "inputFile";
+ private static final String joiner = "joiner";
+ private static final String joinOutput = "joinOutput";
+
+
+ public static void main(String[] args) throws Exception {
+ JoinExample job = new JoinExample();
+ int status = ToolRunner.run(new Configuration(), job, args);
+ System.exit(status);
+ }
+
+ private static void printUsage() {
+ System.err.println("Usage: " + "joinexample <file1> <file2> <numPartitions> <outPath> ["
+ + broadcastOption + "(default false)]");
+ ToolRunner.printGenericCommandUsage(System.err);
+ }
+
+ @Override
+ public int run(String[] args) throws Exception {
+ Configuration conf = getConf();
+ String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
+ int result = validateArgs(otherArgs);
+ if (result != 0) {
+ return result;
+ }
+ return execute(otherArgs);
+ }
+
+ public int run(Configuration conf, String[] args, TezClient tezClient) throws Exception {
+ setConf(conf);
+ String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
+ int result = validateArgs(otherArgs);
+ if (result != 0) {
+ return result;
+ }
+ return execute(otherArgs, tezClient);
+ }
+
+ private int validateArgs(String[] otherArgs) {
+ if (otherArgs.length > 5) {
+ printUsage();
+ return 2;
+ }
+ return 0;
+ }
+
+ private int execute(String[] args) throws TezException, IOException, InterruptedException {
+ TezConfiguration tezConf = new TezConfiguration(getConf());
+ TezClient tezClient = null;
+ try {
+ tezClient = createTezClient(tezConf);
+ return execute(args, tezConf, tezClient);
+ } finally {
+ if (tezClient != null) {
+ tezClient.stop();
+ }
+ }
+ }
+
+ private int execute(String[] args, TezClient tezClient) throws IOException, TezException,
+ InterruptedException {
+ TezConfiguration tezConf = new TezConfiguration(getConf());
+ return execute(args, tezConf, tezClient);
+ }
+
+ private TezClient createTezClient(TezConfiguration tezConf) throws TezException, IOException {
+ TezClient tezClient = TezClient.create("JoinExample", tezConf);
+ tezClient.start();
+ return tezClient;
+ }
+
+ private int execute(String[] args, TezConfiguration tezConf, TezClient tezClient)
+ throws IOException, TezException, InterruptedException {
+ boolean doBroadcast = args.length == 5 && args[4].equals(broadcastOption) ? true : false;
+ LOG.info("Running JoinExample" + (doBroadcast ? "-WithBroadcast" : ""));
+
+ UserGroupInformation.setConfiguration(tezConf);
+
+ String streamInputDir = args[0];
+ String hashInputDir = args[1];
+ int numPartitions = Integer.parseInt(args[2]);
+ String outputDir = args[3];
+
+ Path streamInputPath = new Path(streamInputDir);
+ Path hashInputPath = new Path(hashInputDir);
+ Path outputPath = new Path(outputDir);
+
+ // Verify output path existence
+ FileSystem fs = FileSystem.get(tezConf);
+ if (fs.exists(outputPath)) {
+ System.err.println("Output directory: " + outputDir + " already exists");
+ return 3;
+ }
+ if (numPartitions <= 0) {
+ System.err.println("NumPartitions must be > 0");
+ return 4;
+ }
+
+ DAG dag = createDag(tezConf, streamInputPath, hashInputPath, outputPath, numPartitions, doBroadcast);
+
+ tezClient.waitTillReady();
+ DAGClient dagClient = tezClient.submitDAG(dag);
+ DAGStatus dagStatus = dagClient.waitForCompletionWithStatusUpdates(null);
+ if (dagStatus.getState() != DAGStatus.State.SUCCEEDED) {
+ LOG.info("DAG diagnostics: " + dagStatus.getDiagnostics());
+ return -1;
+ }
+ return 0;
+
+ }
+
+ private DAG createDag(TezConfiguration tezConf, Path streamPath, Path hashPath, Path outPath,
+ int numPartitions, boolean doBroadcast) throws IOException {
+ DAG dag = new DAG("JoinExample" + (doBroadcast ? "-WithBroadcast" : ""));
+
+ /**
+ * This vertex represents the side of the join that will be accumulated in a hash
+ * table in order to join it against the other side. It reads text data using the
+ * TextInputFormat. ForwardingProcessor simply forwards the data downstream as is.
+ */
+ Vertex hashFileVertex = Vertex.create(hashSide, ProcessorDescriptor.create(
+ ForwardingProcessor.class.getName())).addDataSource(
+ inputFile,
+ MRInput
+ .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
+ hashPath.toUri().toString()).groupSplits(false).build());
+
+ /**
+ * This vertex represents that side of the data that will be streamed and joined
+ * against the other side that has been accumulated into a hash table. It reads
+ * text data using the TextInputFormat. ForwardingProcessor simply forwards the data
+ * downstream as is.
+ */
+ Vertex streamFileVertex = Vertex.create(streamingSide, ProcessorDescriptor.create(
+ ForwardingProcessor.class.getName())).addDataSource(
+ inputFile,
+ MRInput
+ .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
+ streamPath.toUri().toString()).groupSplits(false).build());
+
+ /**
+ * This vertex represents the join operation. It writes the join output as text using
+ * the TextOutputFormat. The JoinProcessor is going to perform the join of the
+ * streaming side and the hash side. It is load balanced across numPartitions
+ */
+ Vertex joinVertex = Vertex.create(joiner, ProcessorDescriptor.create(
+ JoinProcessor.class.getName()), numPartitions).addDataSink(joinOutput,
+ MROutput.createConfigBuilder(new Configuration(tezConf),
+ TextOutputFormat.class, outPath.toUri().toString()).build());
+
+ /**
+ * The streamed side will be partitioned into fragments with the same keys going to
+ * the same fragments using hash partitioning. The data to be joined is the key itself
+ * and so the value is null. The number of fragments is initially inferred from the
+ * number of tasks running in the join vertex because each task will be handling one
+ * fragment.
+ */
+ UnorderedPartitionedKVEdgeConfig streamConf =
+ UnorderedPartitionedKVEdgeConfig
+ .newBuilder(Text.class.getName(), NullWritable.class.getName(),
+ HashPartitioner.class.getName()).build();
+
+ /**
+ * Connect the join vertex with the stream side
+ */
+ Edge e1 = Edge.create(streamFileVertex, joinVertex, streamConf.createDefaultEdgeProperty());
+
+ EdgeProperty hashSideEdgeProperty = null;
+ if (doBroadcast) {
+ /**
+ * This option can be used when the hash side is small. We can broadcast the entire data to
+ * all fragments of the stream side. This avoids re-partitioning the fragments of the stream
+ * side to match the partitioning scheme of the hash side and avoids costly network data
+ * transfer. However, in this example the stream side is being partitioned in both cases for
+ * brevity of code. The join task can perform the join of its fragment of keys with all the
+ * keys of the hash side.
+ * Using an unpartitioned edge to transfer the complete output of the hash side to be
+ * broadcasted to all fragments of the streamed side. Again, since the data is the key, the
+ * value is null.
+ */
+ UnorderedKVEdgeConfig broadcastConf = UnorderedKVEdgeConfig.newBuilder(Text.class.getName(),
+ NullWritable.class.getName()).build();
+ hashSideEdgeProperty = broadcastConf.createDefaultBroadcastEdgeProperty();
+ } else {
+ /**
+ * The hash side is also being partitioned into fragments with the same key going to the same
+ * fragment using hash partitioning. This way all keys with the same hash value will go to the
+ * same fragment from both sides. Thus the join task handling that fragment can join both data
+ * set fragments.
+ */
+ hashSideEdgeProperty = streamConf.createDefaultEdgeProperty();
+ }
+
+ /**
+ * Connect the join vertex to the hash side.
+ * The join vertex is connected with 2 upstream vertices that provide it with inputs
+ */
+ Edge e2 = Edge.create(hashFileVertex, joinVertex, hashSideEdgeProperty);
+
+ /**
+ * Connect everything up by adding them to the DAG
+ */
+ dag.addVertex(streamFileVertex).addVertex(hashFileVertex).addVertex(joinVertex)
+ .addEdge(e1).addEdge(e2);
+ return dag;
+ }
+
+ /**
+ * Reads key-values from the source and forwards the value as the key for the output
+ */
+ public static class ForwardingProcessor extends SimpleProcessor {
+ public ForwardingProcessor(ProcessorContext context) {
+ super(context);
+ }
+
+ @Override
+ public void run() throws Exception {
+ Preconditions.checkState(getInputs().size() == 1);
+ Preconditions.checkState(getOutputs().size() == 1);
+ // not looking up inputs and outputs by name because there is just one
+ // instance and this processor is used in many different DAGs with
+ // different names for inputs and outputs
+ LogicalInput input = getInputs().values().iterator().next();
+ Reader rawReader = input.getReader();
+ Preconditions.checkState(rawReader instanceof KeyValueReader);
+ LogicalOutput output = getOutputs().values().iterator().next();
+
+ KeyValueReader reader = (KeyValueReader) rawReader;
+ KeyValueWriter writer = (KeyValueWriter) output.getWriter();
+
+ while (reader.next()) {
+ Object val = reader.getCurrentValue();
+ // The data value itself is the join key. Simply write it out as the key.
+ // The output value is null.
+ writer.write(val, NullWritable.get());
+ }
+ }
+ }
+
+ public static class JoinProcessor extends SimpleMRProcessor {
+
+ public JoinProcessor(ProcessorContext context) {
+ super(context);
+ }
+
+ @Override
+ public void run() throws Exception {
+ Preconditions.checkState(getInputs().size() == 2);
+ Preconditions.checkState(getOutputs().size() == 1);
+ // Get the input data for the 2 sides of the join from the 2 inputs
+ LogicalInput streamInput = getInputs().get(streamingSide);
+ LogicalInput hashInput = getInputs().get(hashSide);
+ Reader rawStreamReader = streamInput.getReader();
+ Reader rawHashReader = hashInput.getReader();
+ Preconditions.checkState(rawStreamReader instanceof KeyValueReader);
+ Preconditions.checkState(rawHashReader instanceof KeyValueReader);
+ LogicalOutput lo = getOutputs().get(joinOutput);
+ Preconditions.checkState(lo.getWriter() instanceof KeyValueWriter);
+ KeyValueWriter writer = (KeyValueWriter) lo.getWriter();
+
+ // create a hash table for the hash side
+ KeyValueReader hashKvReader = (KeyValueReader) rawHashReader;
+ Set<Text> keySet = new HashSet<Text>();
+ while (hashKvReader.next()) {
+ keySet.add(new Text((Text) hashKvReader.getCurrentKey()));
+ }
+
+ // read the stream side and join it using the hash table
+ KeyValueReader streamKvReader = (KeyValueReader) rawStreamReader;
+ while (streamKvReader.next()) {
+ Text key = (Text) streamKvReader.getCurrentKey();
+ if (keySet.contains(key)) {
+ writer.write(key, NullWritable.get());
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/JoinValidate.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/JoinValidate.java b/tez-examples/src/main/java/org/apache/tez/examples/JoinValidate.java
new file mode 100644
index 0000000..6eae72e
--- /dev/null
+++ b/tez-examples/src/main/java/org/apache/tez/examples/JoinValidate.java
@@ -0,0 +1,257 @@
+/**
+ * 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.tez.examples;
+
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.io.NullWritable;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.util.GenericOptionsParser;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+import org.apache.tez.client.TezClient;
+import org.apache.tez.common.counters.TezCounter;
+import org.apache.tez.dag.api.DAG;
+import org.apache.tez.dag.api.Edge;
+import org.apache.tez.dag.api.ProcessorDescriptor;
+import org.apache.tez.dag.api.TezConfiguration;
+import org.apache.tez.dag.api.TezException;
+import org.apache.tez.dag.api.Vertex;
+import org.apache.tez.dag.api.client.DAGClient;
+import org.apache.tez.dag.api.client.DAGStatus;
+import org.apache.tez.dag.api.client.StatusGetOpts;
+import org.apache.tez.examples.JoinExample.ForwardingProcessor;
+import org.apache.tez.mapreduce.input.MRInput;
+import org.apache.tez.runtime.api.LogicalInput;
+import org.apache.tez.runtime.api.Reader;
+import org.apache.tez.runtime.api.ProcessorContext;
+import org.apache.tez.runtime.library.api.KeyValuesReader;
+import org.apache.tez.runtime.library.conf.OrderedPartitionedKVEdgeConfig;
+import org.apache.tez.runtime.library.partitioner.HashPartitioner;
+import org.apache.tez.runtime.library.processor.SimpleProcessor;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+
+public class JoinValidate extends Configured implements Tool {
+ private static final Log LOG = LogFactory.getLog(JoinExample.class);
+
+ private static final String LHS_INPUT_NAME = "lhsfile";
+ private static final String RHS_INPUT_NAME = "rhsfile";
+
+ private static final String COUNTER_GROUP_NAME = "JOIN_VALIDATE";
+ private static final String MISSING_KEY_COUNTER_NAME = "MISSING_KEY_EXISTS";
+
+ public static void main(String[] args) throws Exception {
+ JoinValidate validate = new JoinValidate();
+ int status = ToolRunner.run(new Configuration(), validate, args);
+ System.exit(status);
+ }
+
+ private static void printUsage() {
+ System.err.println("Usage: " + "joinvalidate <path1> <path2>");
+ ToolRunner.printGenericCommandUsage(System.err);
+ }
+
+ @Override
+ public int run(String[] args) throws Exception {
+ Configuration conf = getConf();
+ String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
+ int result = validateArgs(otherArgs);
+ if (result != 0) {
+ return result;
+ }
+ return execute(otherArgs);
+ }
+
+ public int run(Configuration conf, String[] args, TezClient tezClient) throws Exception {
+ setConf(conf);
+ String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
+ int result = validateArgs(otherArgs);
+ if (result != 0) {
+ return result;
+ }
+ return execute(otherArgs, tezClient);
+ }
+
+ private int validateArgs(String[] otherArgs) {
+ if (otherArgs.length != 3 && otherArgs.length != 2) {
+ printUsage();
+ return 2;
+ }
+ return 0;
+ }
+
+ private int execute(String[] args) throws TezException, IOException, InterruptedException {
+ TezConfiguration tezConf = new TezConfiguration(getConf());
+ TezClient tezClient = null;
+ try {
+ tezClient = createTezClient(tezConf);
+ return execute(args, tezConf, tezClient);
+ } finally {
+ if (tezClient != null) {
+ tezClient.stop();
+ }
+ }
+ }
+
+ private int execute(String[] args, TezClient tezClient) throws IOException, TezException,
+ InterruptedException {
+ TezConfiguration tezConf = new TezConfiguration(getConf());
+ return execute(args, tezConf, tezClient);
+ }
+
+ private TezClient createTezClient(TezConfiguration tezConf) throws TezException, IOException {
+ TezClient tezClient = TezClient.create("JoinValidate", tezConf);
+ tezClient.start();
+ return tezClient;
+ }
+
+ private int execute(String[] args, TezConfiguration tezConf, TezClient tezClient)
+ throws IOException, TezException, InterruptedException {
+ LOG.info("Running JoinValidate");
+ UserGroupInformation.setConfiguration(tezConf);
+
+ String lhsDir = args[0];
+ String rhsDir = args[1];
+ int numPartitions = 1;
+ if (args.length == 3) {
+ numPartitions = Integer.parseInt(args[2]);
+ }
+
+ if (numPartitions <= 0) {
+ System.err.println("NumPartitions must be > 0");
+ return 4;
+ }
+
+ Path lhsPath = new Path(lhsDir);
+ Path rhsPath = new Path(rhsDir);
+
+ DAG dag = createDag(tezConf, lhsPath, rhsPath, numPartitions);
+
+ tezClient.waitTillReady();
+ DAGClient dagClient = tezClient.submitDAG(dag);
+ DAGStatus dagStatus = dagClient.waitForCompletionWithStatusUpdates(null);
+ if (dagStatus.getState() != DAGStatus.State.SUCCEEDED) {
+ LOG.info("DAG diagnostics: " + dagStatus.getDiagnostics());
+ return -1;
+ } else {
+ dagStatus = dagClient.getDAGStatus(Sets.newHashSet(StatusGetOpts.GET_COUNTERS));
+ TezCounter counter = dagStatus.getDAGCounters().findCounter(COUNTER_GROUP_NAME,
+ MISSING_KEY_COUNTER_NAME);
+ if (counter == null) {
+ LOG.info("Unable to determing equality");
+ return -2;
+ } else {
+ if (counter.getValue() != 0) {
+ LOG.info("Validate failed. The two sides are not equivalent");
+ return -3;
+ } else {
+ LOG.info("Validation successful. The two sides are equivalent");
+ return 0;
+ }
+ }
+ }
+ }
+
+ private DAG createDag(TezConfiguration tezConf, Path lhs, Path rhs, int numPartitions)
+ throws IOException {
+ DAG dag = new DAG("JoinValidate");
+
+ // Configuration for intermediate output - shared by Vertex1 and Vertex2
+ // This should only be setting selective keys from the underlying conf. Fix after there's a
+ // better mechanism to configure the IOs.
+ OrderedPartitionedKVEdgeConfig edgeConf = OrderedPartitionedKVEdgeConfig
+ .newBuilder(Text.class.getName(), NullWritable.class.getName(),
+ HashPartitioner.class.getName()).build();
+
+ Vertex lhsVertex = Vertex.create(LHS_INPUT_NAME, ProcessorDescriptor.create(
+ ForwardingProcessor.class.getName())).addDataSource("lhs",
+ MRInput
+ .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
+ lhs.toUri().toString()).groupSplits(false).build());
+
+ Vertex rhsVertex = Vertex.create(RHS_INPUT_NAME, ProcessorDescriptor.create(
+ ForwardingProcessor.class.getName())).addDataSource("rhs",
+ MRInput
+ .createConfigBuilder(new Configuration(tezConf), TextInputFormat.class,
+ rhs.toUri().toString()).groupSplits(false).build());
+
+ Vertex joinValidateVertex = Vertex.create("joinvalidate", ProcessorDescriptor.create(
+ JoinValidateProcessor.class.getName()), numPartitions);
+
+ Edge e1 = Edge.create(lhsVertex, joinValidateVertex, edgeConf.createDefaultEdgeProperty());
+ Edge e2 = Edge.create(rhsVertex, joinValidateVertex, edgeConf.createDefaultEdgeProperty());
+
+ dag.addVertex(lhsVertex).addVertex(rhsVertex).addVertex(joinValidateVertex).addEdge(e1)
+ .addEdge(e2);
+ return dag;
+ }
+
+ public static class JoinValidateProcessor extends SimpleProcessor {
+
+ private static final Log LOG = LogFactory.getLog(JoinValidateProcessor.class);
+
+ public JoinValidateProcessor(ProcessorContext context) {
+ super(context);
+ }
+
+ @Override
+ public void run() throws Exception {
+ Preconditions.checkState(getInputs().size() == 2);
+ Preconditions.checkState(getOutputs().size() == 0);
+ LogicalInput lhsInput = getInputs().get(LHS_INPUT_NAME);
+ LogicalInput rhsInput = getInputs().get(RHS_INPUT_NAME);
+ Reader lhsReaderRaw = lhsInput.getReader();
+ Reader rhsReaderRaw = rhsInput.getReader();
+ Preconditions.checkState(lhsReaderRaw instanceof KeyValuesReader);
+ Preconditions.checkState(rhsReaderRaw instanceof KeyValuesReader);
+ KeyValuesReader lhsReader = (KeyValuesReader) lhsReaderRaw;
+ KeyValuesReader rhsReader = (KeyValuesReader) rhsReaderRaw;
+
+ TezCounter lhsMissingKeyCounter = getContext().getCounters().findCounter(COUNTER_GROUP_NAME,
+ MISSING_KEY_COUNTER_NAME);
+
+ while (lhsReader.next()) {
+ if (rhsReader.next()) {
+ if (!lhsReader.getCurrentKey().equals(rhsReader.getCurrentKey())) {
+ LOG.info("MismatchedKeys: " + "lhs=" + lhsReader.getCurrentKey() + ", rhs=" + rhsReader.getCurrentKey());
+ lhsMissingKeyCounter.increment(1);
+ }
+ } else {
+ lhsMissingKeyCounter.increment(1);
+ LOG.info("ExtraKey in lhs: " + lhsReader.getClass());
+ break;
+ }
+ }
+ if (rhsReader.next()) {
+ lhsMissingKeyCounter.increment(1);
+ LOG.info("ExtraKey in rhs: " + lhsReader.getClass());
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/tez/blob/b5497d7c/tez-examples/src/main/java/org/apache/tez/examples/OrderedWordCount.java
----------------------------------------------------------------------
diff --git a/tez-examples/src/main/java/org/apache/tez/examples/OrderedWordCount.java b/tez-examples/src/main/java/org/apache/tez/examples/OrderedWordCount.java
index 9b3d864..c3ea105 100644
--- a/tez-examples/src/main/java/org/apache/tez/examples/OrderedWordCount.java
+++ b/tez-examples/src/main/java/org/apache/tez/examples/OrderedWordCount.java
@@ -26,6 +26,7 @@ import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
+import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
@@ -58,6 +59,12 @@ import com.google.common.base.Preconditions;
*/
public class OrderedWordCount extends Configured implements Tool {
+ private static String INPUT = WordCount.INPUT;
+ private static String OUTPUT = WordCount.OUTPUT;
+ private static String TOKENIZER = WordCount.TOKENIZER;
+ private static String SUMMATION = WordCount.SUMMATION;
+ private static String SORTER = "Sorter";
+
/*
* SumProcessor similar to WordCount except that it writes the count as key and the
* word as value. This is because we can and ordered partitioned key value edge to group the
@@ -72,8 +79,13 @@ public class OrderedWordCount extends Configured implements Tool {
public void run() throws Exception {
Preconditions.checkArgument(getInputs().size() == 1);
Preconditions.checkArgument(getOutputs().size() == 1);
- KeyValueWriter kvWriter = (KeyValueWriter) getOutputs().values().iterator().next().getWriter();
- KeyValuesReader kvReader = (KeyValuesReader) getInputs().values().iterator().next().getReader();
+ // the recommended approach is to cast the reader/writer to a specific type instead
+ // of casting the input/output. This allows the actual input/output type to be replaced
+ // without affecting the semantic guarantees of the data type that are represented by
+ // the reader and writer.
+ // The inputs/outputs are referenced via the names assigned in the DAG.
+ KeyValueWriter kvWriter = (KeyValueWriter) getOutputs().get(SORTER).getWriter();
+ KeyValuesReader kvReader = (KeyValuesReader) getInputs().get(TOKENIZER).getReader();
while (kvReader.next()) {
Text word = (Text) kvReader.getCurrentKey();
int sum = 0;
@@ -100,8 +112,8 @@ public class OrderedWordCount extends Configured implements Tool {
public void run() throws Exception {
Preconditions.checkArgument(getInputs().size() == 1);
Preconditions.checkArgument(getOutputs().size() == 1);
- KeyValueWriter kvWriter = (KeyValueWriter) getOutputs().values().iterator().next().getWriter();
- KeyValuesReader kvReader = (KeyValuesReader) getInputs().values().iterator().next().getReader();
+ KeyValueWriter kvWriter = (KeyValueWriter) getOutputs().get(OUTPUT).getWriter();
+ KeyValuesReader kvReader = (KeyValuesReader) getInputs().get(SUMMATION).getReader();
while (kvReader.next()) {
Object sum = kvReader.getCurrentKey();
for (Object word : kvReader.getCurrentValues()) {
@@ -121,9 +133,9 @@ public class OrderedWordCount extends Configured implements Tool {
DataSinkDescriptor dataSink = MROutput.createConfigBuilder(new Configuration(tezConf),
TextOutputFormat.class, outputPath).build();
- Vertex tokenizerVertex = Vertex.create("Tokenizer", ProcessorDescriptor.create(
+ Vertex tokenizerVertex = Vertex.create(TOKENIZER, ProcessorDescriptor.create(
TokenProcessor.class.getName()));
- tokenizerVertex.addDataSource("MRInput", dataSource);
+ tokenizerVertex.addDataSource(INPUT, dataSource);
// Use Text key and IntWritable value to bring counts for each word in the same partition
OrderedPartitionedKVEdgeConfig summationEdgeConf = OrderedPartitionedKVEdgeConfig
@@ -132,7 +144,7 @@ public class OrderedWordCount extends Configured implements Tool {
// This vertex will be reading intermediate data via an input edge and writing intermediate data
// via an output edge.
- Vertex summationVertex = Vertex.create("Summation", ProcessorDescriptor.create(
+ Vertex summationVertex = Vertex.create(SUMMATION, ProcessorDescriptor.create(
SumProcessor.class.getName()), numPartitions);
// Use IntWritable key and Text value to bring all words with the same count in the same
@@ -143,9 +155,9 @@ public class OrderedWordCount extends Configured implements Tool {
// Use 1 task to bring all the data in one place for global sorted order. Essentially the number
// of partitions is 1. So the NoOpSorter can be used to produce the globally ordered output
- Vertex sorterVertex = Vertex.create("Sorter", ProcessorDescriptor.create(
+ Vertex sorterVertex = Vertex.create(SORTER, ProcessorDescriptor.create(
NoOpSorter.class.getName()), 1);
- sorterVertex.addDataSink("MROutput", dataSink);
+ sorterVertex.addDataSink(OUTPUT, dataSink);
// No need to add jar containing this class as assumed to be part of the tez jars.
@@ -176,6 +188,8 @@ public class OrderedWordCount extends Configured implements Tool {
tezConf = new TezConfiguration();
}
+ UserGroupInformation.setConfiguration(tezConf);
+
TezClient tezClient = TezClient.create("OrderedWordCount", tezConf);
tezClient.start();