Introduction to MapReduce
Jerome Simeon
IBM Watson Research
Content obtained from many sources,
Our Plan Today
1. Background: Cloud and distributed computing 2. Foundations of MapReduce
3. Back to functional programming
4. MapReduce Concretely
“Big Ideas”
¢ Scale “out”, not “up”
l Limits of SMP and large shared-memory machines
¢ Move processing to the data
l Cluster have limited bandwidth
¢ Process data sequentially, avoid random access
l Seeks are expensive, disk throughput is reasonable
¢ Seamless scalability
Building Blocks
Storage Hierarchy
Funny story about sense of scale…
Storage Hierarchy
Funny story about sense of scale…
Anatomy of a Datacenter
Why commodity machines?
What about communication?
¢ Nodes need to talk to each other!
l SMP: latencies ~100 ns
l LAN: latencies ~100 µs
¢ Scaling “up” vs. scaling “out”
l Smaller cluster of SMP machines vs. larger cluster of commodity
machines
l E.g., 8 128-core machines vs. 128 8-core machines
l Note: no single SMP machine is big enough
¢ Let’s model communication overhead…
Modeling Communication Costs
¢ Simple execution cost model:
l Total cost = cost of computation + cost to access global data
l Fraction of local access inversely proportional to size of cluster
l n nodes (ignore cores for now)
l Light communication: f =1
l Medium communication: f =10
l Heavy communication: f =100
¢ What are the costs in parallelization?
Advantages of scaling “up”
Seeks vs. Scans
¢ Consider a 1 TB database with 100 byte records
l We want to update 1 percent of the records
¢ Scenario 1: random access
l Each update takes ~30 ms (seek, read, write)
l 108 updates = ~35 days
¢ Scenario 2: rewrite all records
l Assume 100 MB/s throughput
l Time = 5.6 hours(!)
¢ Lesson: avoid random seeks!
Justifying the “Big Ideas”
¢ Scale “out”, not “up”
l Limits of SMP and large shared-memory machines
¢ Move processing to the data
l Cluster have limited bandwidth
¢ Process data sequentially, avoid random access
l Seeks are expensive, disk throughput is reasonable
¢ Seamless scalability
Numbers Everyone Should Know*
L1 cache reference 0.5 ns
Branch mispredict 5 ns
L2 cache reference 7 ns
Mutex lock/unlock 25 ns
Main memory reference 100 ns
Send 2K bytes over 1 Gbps network 20,000 ns
Read 1 MB sequentially from memory 250,000 ns
Round trip within same datacenter 500,000 ns
Disk seek 10,000,000 ns
Read 1 MB sequentially from disk 20,000,000 ns
Send packet CA → Netherlands → CA 150,000,000 ns
What Is ?
ñ Distributed computing framework
- For clusters of computers
- Thousands of Compute Nodes - Petabytes of data
ñ Open source, Java
ñ Google’s MapReduce inspired Yahoo’s Hadoop.
Map and Reduce
ñ The idea of Map, and Reduce is 40+ year old
- Present in all Functional Programming Languages. - See, e.g., APL, Lisp and ML
ñ Alternate names for Map: Apply-All ñ Higher Order Functions
- take function definitions as arguments, or - return a function as output
Map: A Higher Order Function
ñ F(x: int) returns r: int
ñ Let V be an array of integers. ñ W = map(F, V)
- W[i] = F(V[i]) for all I
Map Examples in Haskell
ñ map (+1) [1,2,3,4,5] == [2, 3, 4, 5, 6]
ñ map (toLower) "abcDEFG12!@#“ == "abcdefg12!@#“
ñ map (`mod` 3) [1..10]
reduce: A Higher Order Function
ñ reduce also known as fold, accumulate,
compress or inject
ñ Reduce/fold takes in a function and folds it in between the elements of a list.
Fold-Left in Haskell
ñ Definition - foldl f z [] = z - foldl f z (x:xs) = foldl f (f z x) xs ñ Examples - foldl (+) 0 [1..5] ==15 - foldl (+) 10 [1..5] == 25 - foldl (div) 7 [34,56,12,4,23] == 0Fold-Right in Haskell
ñ Definition - foldr f z [] = z - foldr f z (x:xs) = f x (foldr f z xs) ñ Example - foldr (div) 7 [34,56,12,4,23] == 8Examples of
Word Count Example
ñ Read text files and count how often words occur.
- The input is text files - The output is a text file
ñ each line: word, tab, count
ñ Map: Produce pairs of (word, count = 1) from files
ñ Reduce: For each word, sum up up the counts (i.e., fold).
Grep Example
ñ Search input files for a given pattern ñ Map: emits a line if pattern is matched ñ Reduce: Copies results to output
Inverted Index Example
(this was the original Google's usecase)
ñ Generate an inverted index of words from a given set of files
ñ Map: parses a document and emits <word, docId> pairs
ñ Reduce: takes all pairs for a given word, sorts the docId values, and emits a <word, list(docId)> pair
MapReduce principle
applied to BigData
Adapt MapReduce for BigData
1. Always maps/reduces on list of key/value pairs 2. Map/Reduce execute in parallel on a cluster
3. Fault tolerance is built in the framework
4. Specific systems/implementation aspects matters – How is data partitioned as input to map
– How is data serialized between processes 5. Cloud specific improvements:
– Handle elasticity
– Take cluster topology (e.g., node proximity, node size) into account
Execution on Clusters
1. Input files split (M splits) 2. Assign Master & Workers 3. Map tasks
4. Writing intermediate data to disk (R regions)
5. Intermediate data read & sort 6. Reduce tasks
Data Flow in a MapReduce
Program in Hadoop
InputFormat Map function Partitioner
Sorting & Merging Combiner Shuffling Merging Reduce function OutputFormat à 1:many
Map/Reduce Cluster
Implementation
split 0 split 1 split 2 split 3 split 4 Output 0 Output 1 Input files Output files M maptasks Intermediate files R reduce tasks
Several map or reduce tasks can run on a single computer
Each intermediate file is divided into R partitions, by
partitioning function
Each reduce task corresponds to one partition
Automatic Parallel Execution in
MapReduce (Google)
Handles failures automatically, e.g., restarts tasks if a node fails; runs multiples copies of the same task to avoid a slow
Fault Recovery
ñ Workers are pinged by master periodically
- Non-responsive workers are marked as failed - All tasks in-progress or completed by failed
worker become eligible for rescheduling
ñ Master could periodically checkpoint
- Current implementations abort on master failure
ñ http://hadoop.apache.org/ ñ Open source Java
ñ Scale
- Thousands of nodes and - petabytes of data
ñ 27 December, 2011: release 1.0.0
Hadoop
ñ MapReduce and Distributed File System framework for large commodity clusters ñ Master/Slave relationship
- JobTracker handles all scheduling & data flow between TaskTrackers
- TaskTracker handles all worker tasks on a node
- Individual worker task runs map or reduce operation
Hadoop Supported File Systems
ñ HDFS: Hadoop's own file system. ñ Amazon S3 file system.
- Targeted at clusters hosted on the Amazon Elastic Compute Cloud server-on-demand infrastructure - Not rack-aware
ñ CloudStore
- previously Kosmos Distributed File System - like HDFS, this is rack-aware.
ñ FTP Filesystem
- stored on remote FTP servers.
"Rack awareness"
ñ optimization which takes into account the geographic clustering of servers
ñ network traffic between servers in different geographic clusters is minimized.
Goals of HDFS
Very Large Distributed File System
– 10K nodes, 100 million files, 10 PB Assumes Commodity Hardware
– Files are replicated to handle hardware failure – Detect failures and recovers from them
Optimized for Batch Processing
– Data locations exposed so that computations can move to where data resides
– Provides very high aggregate bandwidth
HDFS: Hadoop Distr File System
ñ Designed to scale to petabytes of storage, and run on top of the file systems of the underlying OS.
ñ Master (“NameNode”) handles replication, deletion, creation
ñ Slave (“DataNode”) handles data retrieval ñ Files stored in many blocks
- Each block has a block Id
- Block Id associated with several nodes hostname:port (depending on level of replication)
Secondary NameNode Client HDFS Architecture NameNode DataNodes 2. BlckId, Da taNodes o 3.Read data Cluster Membership Cluster Membership
NameNode : Maps a file to a file-id and list of MapNodes DataNode : Maps a block-id to a physical location on disk SecondaryNameNode: Periodic merge of Transaction log
Distributed File System
Single Namespace for entire cluster Data Coherency
– Write-once-read-many access model – Client can only append to existing files
Files are broken up into blocks
– Typically 128 MB block size
– Each block replicated on multiple DataNodes
Intelligent Client
– Client can find location of blocks
NameNode Metadata
Meta-data in Memory
– The entire metadata is in main memory – No demand paging of meta-data
Types of Metadata
– List of files
– List of Blocks for each file
– List of DataNodes for each block
– File attributes, e.g creation time, replication factor
A Transaction Log
DataNode
A Block Server
– Stores data in the local file system (e.g. ext3) – Stores meta-data of a block (e.g. CRC)
– Serves data and meta-data to Clients
Block Report
– Periodically sends a report of all existing blocks to the NameNode
Facilitates Pipelining of Data
Block Placement
Current Strategy
-- One replica on local node
-- Second replica on a remote rack -- Third replica on same remote rack
-- Additional replicas are randomly placed
Clients read from nearest replica
Data Correctness
Use Checksums to validate data
– Use CRC32
File Creation
– Client computes checksum per 512 byte
– DataNode stores the checksum
File access
– Client retrieves the data and checksum from
DataNode
NameNode Failure
A single point of failure
Transaction Log stored in multiple directories
– A directory on the local file system
– A directory on a remote file system (NFS/CIFS)
Data Pipelining
Client retrieves a list of DataNodes on which to place replicas of a block
Client writes block to the first DataNode
The first DataNode forwards the data to the next DataNode in the Pipeline
When all replicas are written, the Client moves on to write the next block in file
Rebalancer
Goal: % disk full on DataNodes should be similar
Usually run when new DataNodes are added Cluster is online when Rebalancer is active
Rebalancer is throttled to avoid network congestion Command line tool
Hadoop v. ‘MapReduce’
ñ MapReduce is also the name of a framework developed by Google
ñ Hadoop was initially developed by Yahoo and now part of the Apache group.
ñ Hadoop was inspired by Google's
MapReduce and Google File System (GFS) papers.
MapReduce v. Hadoop
MapReduce Hadoop
Org Google Yahoo/Apache
Impl C++ Java
Distributed
File Sys GFS HDFS
Data Base Bigtable HBase Distributed
wordCount
A Simple Hadoop Example
Word Count Example
ñ Read text files and count how often words occur.
- The input is text files - The output is a text file
ñ each line: word, tab, count
ñ Map: Produce pairs of (word, count) ñ Reduce: For each word, sum up the
Word Count over a Given Set of Web
Pages
see bob throw see 1
bob 1 throw 1 see 1 spot 1 run 1 bob 1 run 1 see 2 spot 1 throw 1
see spot run
WordCount Overview
3 import ...
12 public class WordCount { 13
14 public static class Map extends MapReduceBase implements Mapper ... {
17
18 public void map ...
26 }
27
28 public static class Reduce extends MapReduceBase implements Reducer ... {
29
30 public void reduce ...
37 }
38
39 public static void main(String[] args) throws Exception {
40 JobConf conf = new JobConf(WordCount.class);
41 ...
53 FileInputFormat.setInputPaths(conf, new Path(args[0]));
54 FileOutputFormat.setOutputPath(conf, new Path(args[1]));
55
56 JobClient.runJob(conf);
57 }
58 59 }
wordCount Reducer
28 public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
29
30 public void reduce(Text key, Iterator<IntWritable> values, OutputCollector<Text, IntWritable> output,
Reporter reporter) throws IOException { 31 int sum = 0; 32 while (values.hasNext()) { 33 sum += values.next().get(); 34 }
35 output.collect(key, new IntWritable(sum)); 36 }
wordCount JobConf
40 JobConf conf = new JobConf(WordCount.class); 41 conf.setJobName("wordcount"); 42 43 conf.setOutputKeyClass(Text.class); 44 conf.setOutputValueClass(IntWritable.class); 45 46 conf.setMapperClass(Map.class); 47 conf.setCombinerClass(Reduce.class); 48 conf.setReducerClass(Reduce.class); 49 50 conf.setInputFormat(TextInputFormat.class); 51 conf.setOutputFormat(TextOutputFormat.class);
WordCount main
39 public static void main(String[] args) throws Exception { 40 JobConf conf = new JobConf(WordCount.class); 41 conf.setJobName("wordcount"); 42 43 conf.setOutputKeyClass(Text.class); 44 conf.setOutputValueClass(IntWritable.class); 45 46 conf.setMapperClass(Map.class); 47 conf.setCombinerClass(Reduce.class); 48 conf.setReducerClass(Reduce.class); 49 50 conf.setInputFormat(TextInputFormat.class); 51 conf.setOutputFormat(TextOutputFormat.class); 52
53 FileInputFormat.setInputPaths(conf, new Path(args[0])); 54 FileOutputFormat.setOutputPath(conf, new Path(args[1])); 55
56 JobClient.runJob(conf); 57 }
Invocation of wordcount
1. /usr/local/bin/hadoop dfs -mkdir <hdfs-dir>
2. /usr/local/bin/hadoop dfs -copyFromLocal <local-dir> <hdfs-dir> 3. /usr/local/bin/hadoop jar hadoop-*-examples.jar wordcount [-m <#maps>] [-r <#reducers>] <in-dir> <out-dir>
Lifecycle of a MapReduce Job
Map function
Reduce function
Run this program as a MapReduce job
Map
Wave 1 Wave 2 Map Reduce Wave 1 Reduce Wave 2 Input
Splits
Lifecycle of a MapReduce Job
Time
How are the number of splits, number of map and reduce
Job Configuration Parameters
190+ parameters in Hadoop
Set manually or defaults are used
Mechanics of Programming
Hadoop Jobs
Job Launch: Client
ñ Client program creates a JobConf
- Identify classes implementing Mapper and
Reducer interfaces
ñ setMapperClass(), setReducerClass()
- Specify inputs, outputs
ñ setInputPath(), setOutputPath()
- Optionally, other options too:
Job Launch: JobClient
ñ Pass JobConf to
- JobClient.runJob() // blocks
- JobClient.submitJob() // does not block
ñ JobClient:
- Determines proper division of input into
InputSplits
Job Launch: JobTracker
ñ JobTracker:
- Inserts jar and JobConf (serialized to XML) in shared location
Job Launch: TaskTracker
ñ TaskTrackers running on slave nodes periodically query JobTracker for work ñ Retrieve job-specific jar and config
ñ Launch task in separate instance of Java
Job Launch: Task
ñ TaskTracker.Child.main():
- Sets up the child TaskInProgress attempt - Reads XML configuration
- Connects back to necessary MapReduce components via RPC
Job Launch: TaskRunner
ñ TaskRunner, MapTaskRunner,
MapRunner work in a daisy-chain to
launch Mapper
- Task knows ahead of time which InputSplits it should be mapping
- Calls Mapper once for each record retrieved from the InputSplit
Creating the Mapper
ñ Your instance of Mapper should extend
MapReduceBase
ñ One instance of your Mapper is initialized by the MapTaskRunner for a
TaskInProgress
- Exists in separate process from all other instances of Mapper – no data sharing!
Mapper
void map ( WritableComparable key, Writable value, OutputCollector output, Reporter reporter )What is Writable?
ñ Hadoop defines its own “box” classes for strings (Text), integers (IntWritable), etc. ñ All values are instances of Writable
ñ All keys are instances of
Writing For Cache Coherency
while (more input exists) {
myIntermediate = new intermediate(input); myIntermediate.process();
export outputs; }
Getting Data To The Mapper
Input file
InputSplit InputSplit InputSplit InputSplit
Input file
RecordReader RecordReader RecordReader RecordReader
Mapper (intermediates) Mapper (intermediates) Mapper (intermediates) Mapper (intermediates) In pu tF or m at
Reading Data
ñ Data sets are specified by InputFormats
- Defines input data (e.g., a directory)
- Identifies partitions of the data that form an InputSplit
- Factory for RecordReader objects to extract (k, v) records from the input source
FileInputFormat and Friends
ñ TextInputFormat
- Treats each ‘\n’-terminated line of a file as a value
ñ KeyValueTextInputFormat
- Maps ‘\n’- terminated text lines of “k SEP v”
ñ SequenceFileInputFormat
- Binary file of (k, v) pairs with some add’l metadata
ñ SequenceFileAsTextInputFormat
Filtering File Inputs
ñ FileInputFormat will read all files out of a specified directory and send them to the mapper
ñ Delegates filtering this file list to a method subclasses may override
- e.g., Create your own “xyzFileInputFormat” to read *.xyz from directory list
Record Readers
ñ Each InputFormat provides its own
RecordReader implementation
- Provides (unused?) capability multiplexing
ñ LineRecordReader
- Reads a line from a text file
ñ KeyValueRecordReader
Input Split Size
ñ FileInputFormat will divide large files into chunks
- Exact size controlled by mapred.min.split.size
ñ RecordReaders receive file, offset, and length of chunk
ñ Custom InputFormat implementations may override split size
Sending Data To Reducers
ñ Map function receives OutputCollector object
- OutputCollector.collect() takes (k, v) elements
ñ Any (WritableComparable, Writable) can be used
WritableComparator
ñ Compares WritableComparable data
- Will call WritableComparable.compare() - Can provide fast path for serialized data
Sending Data To The Client
ñ Reporter object sent to Mapper allows simple asynchronous feedback
- incrCounter(Enum key, long amount) - setStatus(String msg)
ñ Allows self-identification of input
Partition And Shuffle
Mapper (intermediates) Mapper (intermediates) Mapper (intermediates) Mapper (intermediates)Reducer Reducer Reducer
(intermediates) (intermediates) (intermediates)
Partitioner Partitioner Partitioner Partitioner
sh
uf
fli
Partitioner
ñ int getPartition(key, val, numPartitions)
- Outputs the partition number for a given key - One partition == values sent to one Reduce
task
ñ HashPartitioner used by default
- Uses key.hashCode() to return partition num
Reduction
ñ reduce( WritableComparable key, Iterator values,
OutputCollector output, Reporter reporter)
ñ Keys & values sent to one partition all go to the same reduce task
ñ Calls are sorted by key – “earlier” keys are reduced and output before “later” keys
Finally: Writing The Output
Reducer Reducer Reducer
RecordWriter RecordWriter RecordWriter
output file output file output file
O ut pu tF or m at
OutputFormat
ñ Analogous to InputFormat ñ TextOutputFormat
- Writes “key val\n” strings to output file
ñ SequenceFileOutputFormat
- Uses a binary format to pack (k, v) pairs
ñ NullOutputFormat
HDFS Limitations
ñ “Almost” GFS (Google FS)
- No file update options (record append, etc); all files are write-once
ñ Does not implement demand replication ñ Designed for streaming
NameNode
ñ “Head” interface to HDFS cluster ñ Records all global metadata
Secondary NameNode
ñ Not a failover NameNode!
ñ Records metadata snapshots from “real” NameNode
- Can merge update logs in flight
NameNode Death
ñ No new requests can be served while NameNode is down
- Secondary will not fail over as new primary
NameNode Death, cont’d
ñ If NameNode dies from software glitch, just reboot
ñ But if machine is hosed, metadata for cluster is irretrievable!
Bringing the Cluster Back
ñ If original NameNode can be restored, secondary can re-establish the most current metadata snapshot
ñ If not, create a new NameNode, use secondary to copy metadata to new primary, restart whole cluster ( L ) ñ Is there another way…?
Keeping the Cluster Up
ñ Problem: DataNodes “fix” the address of the NameNode in memory, can’t switch in flight
ñ Solution: Bring new NameNode up, but use DNS to make cluster believe it’s the original one
Further Reliability Measures
ñ Namenode can output multiple copies of metadata files to different directories
- Including an NFS mounted one
- May degrade performance; watch for NFS locks
Making Hadoop Work
ñ Basic configuration involves pointing nodes at master machines
- mapred.job.tracker - fs.default.name
- dfs.data.dir, dfs.name.dir - hadoop.tmp.dir
- mapred.system.dir
ñ See “Hadoop Quickstart” in online documentation
Configuring for Performance
ñ Configuring Hadoop performed in “base JobConf” in conf/hadoop-site.xml
ñ Contains 3 different categories of settings
- Settings that make Hadoop work - Settings for performance
Configuring for Performance
ñ Configuring Hadoop performed in “base JobConf” in conf/hadoop-site.xml
ñ Contains 3 different categories of settings
- Settings that make Hadoop work - Settings for performance
Number of Tasks
ñ Controlled by two parameters:
- mapred.tasktracker.map.tasks.maximum - mapred.tasktracker.reduce.tasks.maximum
ñ Two degrees of freedom in mapper run time: Number of tasks/node, and size of InputSplits
ñ Current conventional wisdom: 2 map tasks/core, less for reducers
ñ See http://wiki.apache.org/lucene-hadoop/ HowManyMapsAndReduces
Dead Tasks
ñ Student jobs would “run away”, admin restart needed
ñ Very often stuck in huge shuffle process
- Students did not know about Partitioner class, may have had non-uniform distribution
- Did not use many Reducer tasks
- Lesson: Design algorithms to use Combiners where possible
Working With the Scheduler
ñ Remember: Hadoop has a FIFO job scheduler
- No notion of fairness, round-robin
ñ Design your tasks to “play well” with one another
- Decompose long tasks into several smaller ones which can be interleaved at Job level
Additional Languages &
Components
Hadoop and C++
ñ Hadoop Pipes
- Library of bindings for native C++ code - Operates over local socket connection
ñ Straight computation performance may be faster
ñ Downside: Kernel involvement and context switches
Hadoop and Python
ñ Option 1: Use Jython
- Caveat: Jython is a subset of full Python
HadoopStreaming
ñ Effectively allows shell pipe ‘|’ operator to be used with Hadoop
ñ You specify two programs for map and
reduce
- (+) stdin and stdout do the rest
- (-) Requires serialization to text, context switches…
Eclipse Plugin
ñ Support for Hadoop in Eclipse IDE
- Allows MapReduce job dispatch - Panel tracks live and recent jobs
ñ http://www.alphaworks.ibm.com/tech/ mapreducetools
References
ñ http://hadoop.apache.org/
ñ Jeffrey Dean and Sanjay Ghemawat,
MapReduce: Simplified Data Processing on Large Clusters. Usenix SDI '04, 2004.
http://www.usenix.org/events/osdi04/tech/
full_papers/dean/dean.pdf
ñ David DeWitt, Michael Stonebraker,
"MapReduce: A major step backwards“, craig-henderson.blogspot.com
ñ http://scienceblogs.com/goodmath/2008/01/