MapReduce Job Execution Process – Reduce Function

Hi Hadoopers,

We are in 6th circle today, which is the reducer function. A job is submitted by the user, which has been initiated in 2nd circle for which the setup is completed in 3rd circle.

Map Task was executed in 4th circle and sort & shuffle was completed in 5th circle.

hadoop037-job-submission-1

The reducer will collect the output from all the mappers to apply the user defined reduce function.

hadoop043-hadoop-reducer

  1. Task tracker launches the reduce task
  2. Reduce task (not reduce function) read the jar and xml of the job.
  3. It execute the shuffle. Because the time the reducer task started, all the mappers may not have completed the job. So it goes to individual mapper machines to collect the output and shuffles them.
  4. Once all the mapping activity is finished it invokes the user reducer function (one more reducers).
  5. Each reducers will complete their jobwrite the output records to HDFS.
  6. Those output would be stored in temporary output file first.
  7. Once all the reducers have completed their job, final output would be written to the reducer partition file.
Advertisements

MapReduce Job Execution Process – Sort & Spill

Hi Hadoopers,

Mappers run on individual machines and prepare intermediate results. They accept splits as inputs. Reducer accepts partition of data as inputs.  Preparing the partitions from the intermediate mapper results is the responsibility of this sort & spill phase, which is the 5th circle given below.

hadoop037-job-submission-1

 

During this phase, we find the keys from all the mappers, sort and shuffle them before sending them to one machine, where the reducer will run.

hadoop042-sort-n-spill

  1. The task tracker 1 initiates a reducer task.
  2. TT1 updates the job tracker about the completion status.
  3. Similarly TT2 or any other task trackers also updates the Job Tracker about completion status.
  4. The reducer task goes to TT1 where the mapping task is finished to collect the interim results.
  5. TT2 read the mapper output streams it to the reducer
  6. Task 4 and 5 is repeated for other task trackers also who are all involved in mapping tasks.
  7. Once the reducer received all the mapping results, it performs a sorting and spilling.

 

MapReduce Job Execution Process – Job scheduling

Hi Hadoopers,

We shall talk about 3rd circle today, as we talk about Job submission and Job initialilzation already.

hadoop037-job-submission-1

Scheduling the jobs is an interesting concept. I’m really excited to see the communication between Scheduler, Job tracker and  Task tracker.

hadoop040-job-schedule

  1. The task tracker keeps on sending heartbeats to Job Tracker about the status of the job. So, it says to Job Tracker that job is completed and it wants more jobs.
  2. Job Tracker updates the task status and make a note of Task Tracker’s message.
  3. Job Tracker goes to Scheduler asking for tasks.
  4. Scheduler updates the tasks scheduler record. Based on job scheduling policy, either it makes the job client to wait or process the job. It is based on execution policy, priority etc.
  5. Job tracker gets the task.
  6. It submits the task to the task tracker.

MapReduce Job Execution Process – Job initialization

Hi Hadoopers,

I wrote about the first step of the MR Job execution – Job Submission in my earlier post.

hadoop037-job-submission-1

In this post, we talk about 2nd circle, which is Job initialization.

I got the job, How will I execute it. This is what hadoop elephant is thinking with a yarn in its trunk!

hadoop039-job-init

  1. Once the job is submitted, it becomes Job Tracker’s responsibility to initialize it.
  2. The job xml uploaded at the staging directory created as given in my earlier post. Job Tracker reads it and perform the validation.
  3. Once the XML validation is completed, It goes to scheduler for job validations. Scheduler check is the user is authorized for this job, content is allowed etc.
  4. If the job validation is also successful, the job is added by the Scheduler. The schedule information is updated.
  5. Job Scheduler initializes the job.
  6. It reads the number of splits needed for the job to get executed.
  7. Tasks are created to exec the job. If we have many splits, that many map tasks would be spawned.

 

MapReduce Job Execution Process – Job Submission

Hi Hadoopers,

After publishing many posts about MapReduce code, we’ll see the MR internals like, how the MR job is submitted and executed.

hadoop037-job-submission-1

This post talks about first circle – Job Submission.

We compiled the MR code and jar is ready. We execute the job with hadoop jar xxxxxx. First the job is submitted to hadoop. There are schedulers which runs the job, based on cluster capacity and availability.

I want to scribble down quick notes on Job Submission using the below given gantt diagram.

hadoop038-job-submission-2

  1. The user submits the job to Job Client.
  2. Job client talks to Job Tracker to get the job id
  3. The job client creates a staging directory in HDFS. This is where all the files related to the job would get uploaded.
  4. The MR code and configurations with their 10 replicas of the blocks would be uploaded to Staging directory. Jar file of the job, job splits, split meta data and job.xml which has the job description would be uploaded.
  5. Splits are computed automatically and input is read.
  6. Meta data of split is uploaded to HDFS
  7. Job is submitted and it is ready to execute.

Lab 15: Writing unit test cases for MapReduce

Hi Hadoopers,

Here is the next interesting post. We already know (at least, we assume we already!) junit is the unit testing framework for Java. Based on that, hadoop offers us MRUnit to write unit test cases.

Here is a sample.

Our Input:

Blogger http://www.blogger.com      BSNLTeleServices | BSNL Broadband Plans, Bill Payment Selfcare Portal   noreply@blogger.com (BSNL TeleServices) http://www.bsnlteleservices.com/        Sat Sep 24 02:42:36 MYT 2016     BSNL 599 Broadband Plan | MP Combo Internet Tariff     noreply@blogger.com (BSNL TeleServices) http://feedproxy.google.com/~r/BSNLTeleservices/~3/3KqPtw353PM/bsnl-599-broadband-plan-mp-combo.html    Sat Sep 24 02:14:11 MYT 2016    [BSNL Broadband Plans, Broadband Tariff]

This reducer will identify the author of this article as highlighted.

Mapper

Mapper accepts the tab limited line and finds the appearance of the author name.

package org.grassfield.nandu.author;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.StringTokenizer;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.log4j.Logger;
import org.grassfield.hadoop.FeedCategoryCountMapper.MapperRCheck;
import org.grassfield.hadoop.entity.FeedEntryRecord;
import org.grassfield.hadoop.util.ParseUtil;

public class AuthorMapper
        extends Mapper<LongWritable, Text, Text, IntWritable> {
    String dateFormat = "EEE MMM dd HH:mm:ss z yyyy";
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    Logger logger = Logger.getLogger(AuthorMapper.class);
    IntWritable one = new IntWritable(1);

    @Override
    protected void map(LongWritable key, Text value,
            Mapper<LongWritable, Text, Text, IntWritable>.Context context)
            throws IOException, InterruptedException {
        String line = value.toString();
        StringTokenizer st = new StringTokenizer(line, "\t");
        int countTokens = st.countTokens();
        if (countTokens!=10){
            context.getCounter(MapperRCheck.INVALID).increment(1);
        }else{
            context.getCounter(MapperRCheck.VALID).increment(1);
        }
        
        try {
            FeedEntryRecord record = ParseUtil.populateRecord(line, sdf);
            String name = record.getEntryAuthor();
            if (name==null){
                name = record.getFeedAuthor();
            }
            context.write(new Text(name), one);
        } catch (Exception e) {
            logger.error("Error while mapping", e);
            context.getCounter(MapperRCheck.INVALID).increment(1);
        }
    }
}

Reducer

Reducer sums the occurrences of the author names.

package org.grassfield.nandu.author;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

public class AuthorReducer
        extends Reducer<Text, IntWritable, Text, IntWritable> {

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values,
            Reducer<Text, IntWritable, Text, IntWritable>.Context context)
            throws IOException, InterruptedException {
        
        int sum=0;
        for(IntWritable value:values){
            sum+=value.get();
        }
        context.write(key, new IntWritable(sum));
    }
}

Driver

Here is the driver class

package org.grassfield.nandu.author;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class AuthorDriver extends Configured 
    implements Tool{

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        GenericOptionsParser parser = new GenericOptionsParser(conf, args);
        args = parser.getRemainingArgs();
        
        Path input = new Path(args[0]);
        Path output = new Path(args[1]);
        
        Job job = new Job(conf, "Author count");
        job.setJarByClass(this.getClass());
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setMapperClass(AuthorMapper.class);
        job.setReducerClass(AuthorReducer.class);
        job.setNumReduceTasks(1);
        
        FileInputFormat.setInputPaths(job, input);
        FileOutputFormat.setOutputPath(job, output);
        
        return job.waitForCompletion(true)?0:1;
    }
    
    public static void main(String [] args) throws Exception{
        System.exit(ToolRunner.run(new Configuration(), new AuthorDriver(), args));
    }

}

Test Case

 

Let’s run the unit test case for this reducer.

package org.grassfield.nandu.author;


import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mrunit.mapreduce.MapReduceDriver;
import org.junit.Before;
import org.junit.Test;

public class AuthorDriverTest {
    private Mapper<LongWritable, Text, Text, IntWritable> mapper;
    private Reducer<Text, IntWritable, Text, IntWritable> reducer;
    private MapReduceDriver<LongWritable, Text,  Text, IntWritable,  Text, IntWritable> driver;
    
    @Before
    public void setUp() throws Exception{
        mapper = new AuthorMapper();
        reducer = new AuthorReducer();
        driver = MapReduceDriver.newMapReduceDriver(mapper, reducer);
    }
    
    @Test
    public void testRun() throws Exception{
        String line = "Blogger http://www.blogger.com      BSNLTeleServices | BSNL Broadband Plans, Bill Payment Selfcare Portal   noreply@blogger.com (BSNL TeleServices) http://www.bsnlteleservices.com/        Sat Sep 24 02:42:36 MYT 2016     BSNL 599 Broadband Plan | MP Combo Internet Tariff     noreply@blogger.com (BSNL TeleServices) http://feedproxy.google.com/~r/BSNLTeleservices/~3/3KqPtw353PM/bsnl-599-broadband-plan-mp-combo.html    Sat Sep 24 02:14:11 MYT 2016    [BSNL Broadband Plans, Broadband Tariff]";
        driver.withInput(new LongWritable(), new Text(line));
        driver.withOutput(new Text("author"), new IntWritable(1));
        driver.runTest();
    }
}

Let’s run this as a jUnit test case.

hadoop036-lab-15-mrunit

java.lang.Exception: java.io.IOException: Incorrect string value: ‘\xE0\xAE\xB5\xE0\xAF\x87…’

Hi Hadoopers,

This is a nasty exception which kicked off my reducer task, which updates my MySQL table with the reducer output.

The reason behind this is unicode character.

MySQL table was created with non-unicode wester encoding. I’m trying to insert multi lingual unicode text. After changing the table collation (if needed field collation also) to utf8_bin, it worked fine.

alter table FeedEntryRecord convert to character set utf8 collate utf8_bin;