+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

vijaygarg1init07ca65d

master
7.6 KiB239 linesraw
1/**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19package org.apache.hadoop.examples;
20
21import java.io.DataInput;
22import java.io.DataOutput;
23import java.io.IOException;
24import java.util.StringTokenizer;
25
26import org.apache.hadoop.conf.Configuration;
27import org.apache.hadoop.fs.Path;
28import org.apache.hadoop.io.IntWritable;
29import org.apache.hadoop.io.LongWritable;
30import org.apache.hadoop.io.RawComparator;
31import org.apache.hadoop.io.Text;
32import org.apache.hadoop.io.WritableComparable;
33import org.apache.hadoop.io.WritableComparator;
34import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
35import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
36import org.apache.hadoop.mapreduce.Job;
37import org.apache.hadoop.mapreduce.Mapper;
38import org.apache.hadoop.mapreduce.Partitioner;
39import org.apache.hadoop.mapreduce.Reducer;
40import org.apache.hadoop.util.GenericOptionsParser;
41
42/**
43 * This is an example Hadoop Map/Reduce application.
44 * It reads the text input files that must contain two integers per a line.
45 * The output is sorted by the first and second number and grouped on the 
46 * first number.
47 *
48 * To run: bin/hadoop jar build/hadoop-examples.jar secondarysort
49 *            <i>in-dir</i> <i>out-dir</i> 
50 */
51public class SecondarySort {
52 
53  /**
54   * Define a pair of integers that are writable.
55   * They are serialized in a byte comparable format.
56   */
57  public static class IntPair 
58                      implements WritableComparable<IntPair> {
59    private int first = 0;
60    private int second = 0;
61    
62    /**
63     * Set the left and right values.
64     */
65    public void set(int left, int right) {
66      first = left;
67      second = right;
68    }
69    public int getFirst() {
70      return first;
71    }
72    public int getSecond() {
73      return second;
74    }
75    /**
76     * Read the two integers. 
77     * Encoded as: MIN_VALUE -&gt; 0, 0 -&gt; -MIN_VALUE, MAX_VALUE-&gt; -1
78     */
79    @Override
80    public void readFields(DataInput in) throws IOException {
81      first = in.readInt() + Integer.MIN_VALUE;
82      second = in.readInt() + Integer.MIN_VALUE;
83    }
84    @Override
85    public void write(DataOutput out) throws IOException {
86      out.writeInt(first - Integer.MIN_VALUE);
87      out.writeInt(second - Integer.MIN_VALUE);
88    }
89    @Override
90    public int hashCode() {
91      return first * 157 + second;
92    }
93    @Override
94    public boolean equals(Object right) {
95      if (right instanceof IntPair) {
96        IntPair r = (IntPair) right;
97        return r.first == first && r.second == second;
98      } else {
99        return false;
100      }
101    }
102    /** A Comparator that compares serialized IntPair. */ 
103    public static class Comparator extends WritableComparator {
104      public Comparator() {
105        super(IntPair.class);
106      }
107
108      public int compare(byte[] b1, int s1, int l1,
109                         byte[] b2, int s2, int l2) {
110        return compareBytes(b1, s1, l1, b2, s2, l2);
111      }
112    }
113
114    static {                                        // register this comparator
115      WritableComparator.define(IntPair.class, new Comparator());
116    }
117
118    @Override
119    public int compareTo(IntPair o) {
120      if (first != o.first) {
121        return first < o.first ? -1 : 1;
122      } else if (second != o.second) {
123        return second < o.second ? -1 : 1;
124      } else {
125        return 0;
126      }
127    }
128  }
129  
130  /**
131   * Partition based on the first part of the pair.
132   */
133  public static class FirstPartitioner extends Partitioner<IntPair,IntWritable>{
134    @Override
135    public int getPartition(IntPair key, IntWritable value, 
136                            int numPartitions) {
137      return Math.abs(key.getFirst() * 127) % numPartitions;
138    }
139  }
140
141  /**
142   * Compare only the first part of the pair, so that reduce is called once
143   * for each value of the first part.
144   */
145  public static class FirstGroupingComparator 
146                implements RawComparator<IntPair> {
147    @Override
148    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
149      return WritableComparator.compareBytes(b1, s1, Integer.SIZE/8, 
150                                             b2, s2, Integer.SIZE/8);
151    }
152
153    @Override
154    public int compare(IntPair o1, IntPair o2) {
155      int l = o1.getFirst();
156      int r = o2.getFirst();
157      return l == r ? 0 : (l < r ? -1 : 1);
158    }
159  }
160
161  /**
162   * Read two integers from each line and generate a key, value pair
163   * as ((left, right), right).
164   */
165  public static class MapClass 
166         extends Mapper<LongWritable, Text, IntPair, IntWritable> {
167    
168    private final IntPair key = new IntPair();
169    private final IntWritable value = new IntWritable();
170    
171    @Override
172    public void map(LongWritable inKey, Text inValue, 
173                    Context context) throws IOException, InterruptedException {
174      StringTokenizer itr = new StringTokenizer(inValue.toString());
175      int left = 0;
176      int right = 0;
177      if (itr.hasMoreTokens()) {
178        left = Integer.parseInt(itr.nextToken());
179        if (itr.hasMoreTokens()) {
180          right = Integer.parseInt(itr.nextToken());
181        }
182        key.set(left, right);
183        value.set(right);
184        context.write(key, value);
185      }
186    }
187  }
188  
189  /**
190   * A reducer class that just emits the sum of the input values.
191   */
192  public static class Reduce 
193         extends Reducer<IntPair, IntWritable, Text, IntWritable> {
194    private static final Text SEPARATOR = 
195      new Text("------------------------------------------------");
196    private final Text first = new Text();
197    
198    @Override
199    public void reduce(IntPair key, Iterable<IntWritable> values,
200                       Context context
201                       ) throws IOException, InterruptedException {
202      context.write(SEPARATOR, null);
203      first.set(Integer.toString(key.getFirst()));
204      for(IntWritable value: values) {
205        context.write(first, value);
206      }
207    }
208  }
209  
210  public static void main(String[] args) throws Exception {
211    Configuration conf = new Configuration();
212    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
213    if (otherArgs.length != 2) {
214      System.err.println("Usage: secondarysort <in> <out>");
215      System.exit(2);
216    }
217    Job job = Job.getInstance(conf, "secondary sort");
218    job.setJarByClass(SecondarySort.class);
219    job.setMapperClass(MapClass.class);
220    job.setReducerClass(Reduce.class);
221
222    // group and partition by the first int in the pair
223    job.setPartitionerClass(FirstPartitioner.class);
224    job.setGroupingComparatorClass(FirstGroupingComparator.class);
225
226    // the map output is IntPair, IntWritable
227    job.setMapOutputKeyClass(IntPair.class);
228    job.setMapOutputValueClass(IntWritable.class);
229
230    // the reduce output is Text, IntWritable
231    job.setOutputKeyClass(Text.class);
232    job.setOutputValueClass(IntWritable.class);
233    
234    FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
235    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
236    System.exit(job.waitForCompletion(true) ? 0 : 1);
237  }
238
239}