Job的数据输入格式化器—InputFormat

 Hadoop被设计用来处理海量数据,这种数据可以是结构化的,半结构化的,甚至是一些无结构化的文本数据(这些数据可能存储在HDFS文件中,也可能存放在DB中)。它处理数据的核心就是map-reduce模型,但是,无论是map还是reduce,它们的输入输出数据都是key-value对的形式,这种key-value对的形式我们可以看做是结构化的数据。同时,对于reduce的输入,当然就是map的输出,而reduce、map的输出又直接可以在map和reduce处理函数中定义,那么这就只剩下map的输出了,也就是说,Hadoop如何把输入文件包装成key-value对的形式交给map来处理,同时hadoop又是如何切割作业的输入文件来结果不同的TaskTracker同时来处理的呢?这两个问题就是本文将要重点讲述的内容——作业的输入文件格式化器(InputFormat)。

           在Hadoop对Map-Reduce实现设计中,作业的输入文件格式化器包括两个组件:文件读取器(RecordReader)和文件切割器(Spliter)。其中,文件切割器用来对作业的所有输入数据进行分片切割,最后有多少个切片就有多少个map任务,文件读取器用来读取切片中的数据,并按照一定的格式把读取的数据包装成一个个key-value对。而在具体的对应实现中这个输入文件格式化器被定义了一个抽先类,这样它把如何切割输入数据以及如何读取数据并把数据包装成key-value对交给了用户来实现,因为只有用户才知道输入的数据是如何组织的,map函数需要什么样的key-value值作为输入值。这个输入文件格式化器对应的是org.apache.hadoop.mapreduce.InputFormat类:

[java] view plaincopy
  1. public abstract class InputFormat<K, V> {  
  2.   
  3.   /**  
  4.    * Logically split the set of input files for the job.   
  5.    */  
  6.   public abstract List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException;  
  7.     
  8.   /** 
  9.    * Create a record reader for a given split. The framework will call 
  10.    */  
  11.   public abstract RecordReader<K,V> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException;  
  12.   
  13. }  
       显然,在InputSplit类中,getSplit()方法是让用户定义如何对作业的输入数据进行切割分的,createRecordReader方法是定义如何读取输入数据,并包装成一个若干个key-value对的,即定义一个记录读取器。另外,对于一个输入数据切片信息(数据的长度、数据保存在哪些DataNode节点上)被保存在一个对应的InputSplit对象中。顺带需要提一下的是,JobClient在调用InputFormat的getSplit()方法时,对返回的InputSplit数组又使用JobClient.RawSplit进行了一次封装,并将其序列化到文件中。下面就来看看hadoop在其内部有哪些相关的默认实现的。



       

      从上面的类图可以看出,Hadoop在抽象类FileInputFormat中实现了一个基于文件的数据分片切割器,所以在这里我先主要谈谈它是如何实现的。先来看源码:

[java] view plaincopy
  1. protected long getFormatMinSplitSize() {  
  2.     return 1;  
  3. }  
  4.   
  5. public static long getMinSplitSize(JobContext job) {  
  6.     return job.getConfiguration().getLong("mapred.min.split.size", 1L);  
  7. }  
  8.   
  9. public static long getMaxSplitSize(JobContext context) {  
  10.     return context.getConfiguration().getLong("mapred.max.split.size", Long.MAX_VALUE);  
  11. }  
  12.   
  13. protected long computeSplitSize(long blockSize, long minSize,long maxSize) {  
  14.     return Math.max(minSize, Math.min(maxSize, blockSize));  
  15. }  
  16.   
  17. public List<InputSplit> getSplits(JobContext job) throws IOException {  
  18.     long minSize = Math.max(getFormatMinSplitSize(), getMinSplitSize(job));//计算允许的最小切片大小  
  19.     long maxSize = getMaxSplitSize(job);//计算允许的最大切片大小  
  20.   
  21.  // generate splits  
  22.     LOG.debug("start to split all input files for Job["+job.getJobName()+"]");  
  23.     List<InputSplit> splits = new ArrayList<InputSplit>();  
  24.     for (FileStatus file: listStatus(job)) {  
  25.       Path path = file.getPath();  
  26.       FileSystem fs = path.getFileSystem(job.getConfiguration());  
  27.       long length = file.getLen();  
  28.   
  29.       BlockLocation[] blkLocations = fs.getFileBlockLocations(file, 0, length);  
  30.       if ((length != 0) && isSplitable(job, path)) {   
  31.         long blockSize = file.getBlockSize();  
  32.         long splitSize = computeSplitSize(blockSize, minSize, maxSize);//计算该输入文件一个切片最终大小  
  33.         long bytesRemaining = length;  
  34.         while (((double) bytesRemaining)/splitSize > SPLIT_SLOP) {  
  35.           int blkIndex = getBlockIndex(blkLocations, length-bytesRemaining);  
  36.           splits.add(new FileSplit(path, length-bytesRemaining, splitSize, blkLocations[blkIndex].getHosts()));  
  37.           bytesRemaining -= splitSize;  
  38.         }  
  39.           
  40.         if (bytesRemaining != 0) {  
  41.           splits.add(new FileSplit(path, length-bytesRemaining, bytesRemaining,blkLocations[blkLocations.length-1].getHosts()));  
  42.         }  
  43.       } else if (length != 0) {  
  44.         splits.add(new FileSplit(path, 0, length, blkLocations[0].getHosts()));  
  45.       } else {   
  46.         //Create empty hosts array for zero length files  
  47.         splits.add(new FileSplit(path, 0, length, new String[0]));  
  48.       }  
  49.     }  
  50.       
  51.     LOG.debug("Total # of splits in Job["+job.getJobName()+"]'s input files: " + splits.size());  
  52.       
  53.     return splits;  
  54.   }  
  55.   
  56. /*是否允许对一个文件进行切片*/  
  57. protected boolean isSplitable(JobContext context, Path filename) {  
  58.     return true;  
  59. }  
    上面的输入数据切割器是支持多输入文件的,而且还要着重注意的是这个输入数据切割器是如何计算一个数据切片大小的,因为在很多情况下,切片的大小对一个作业的执行性能有着至关重要的影响,应为至少切片的数量决定了map任务的数量。试想一下,如果3个数据块被切成两个数据片和被切成三个数据块,哪一种情况下耗费的网络I/O时间要多一些呢?在作业没有配置数据切割器的情况下,默认的是TextInputFormat,对应的配置文件的设置项为:mapreduce.inputformat.class

        最后,以LineRecordReader为例来简单的讲解一下记录读取器的实现,这个记录读取器是按文本文件中的行来读取数据的,它的key-value中为:行号一行文本。    

[java] view plaincopy
  1. public class LineRecordReader extends RecordReader<LongWritable, Text> {  
  2.       
  3.   private static final Log LOG = LogFactory.getLog(LineRecordReader.class);  
  4.   
  5.   private CompressionCodecFactory compressionCodecs = null;  
  6.   private long start;  
  7.   private long pos;  
  8.   private long end;  
  9.   private LineReader in;  
  10.   private int maxLineLength;  
  11.   private LongWritable key = null;  
  12.   private Text value = null;  
  13.   
  14.   public void initialize(InputSplit genericSplit, TaskAttemptContext context) throws IOException {  
  15.            
  16.     FileSplit split = (FileSplit) genericSplit;  
  17.     Configuration job = context.getConfiguration();  
  18.     this.maxLineLength = job.getInt("mapred.linerecordreader.maxlength", Integer.MAX_VALUE);  
  19.       
  20.     start = split.getStart();  
  21.     end = start + split.getLength();  
  22.       
  23.     final Path file = split.getPath();  
  24.     compressionCodecs = new CompressionCodecFactory(job);  
  25.     final CompressionCodec codec = compressionCodecs.getCodec(file);  
  26.   
  27.     // open the file and seek to the start of the split  
  28.     FileSystem fs = file.getFileSystem(job);  
  29.     Path _inputFile = split.getPath();  
  30.   
  31.     FSDataInputStream fileIn = fs.open(_inputFile);  
  32.     boolean skipFirstLine = false;  
  33.     if (codec != null) {  
  34.       in = new LineReader(codec.createInputStream(fileIn), job);  
  35.       end = Long.MAX_VALUE;  
  36.     } else {  
  37.       if (start != 0) {  
  38.         skipFirstLine = true;  
  39.         --start;  
  40.         fileIn.seek(start);  
  41.       }  
  42.       in = new LineReader(fileIn, job);  
  43.     }  
  44.       
  45.     if (skipFirstLine) {  // skip first line and re-establish "start".  
  46.       start += in.readLine(new Text(), 0,(int)Math.min((long)Integer.MAX_VALUE, end - start));  
  47.     }  
  48.       
  49.     this.pos = start;  
  50.   }  
  51.     
  52.   public boolean nextKeyValue() throws IOException {  
  53.         
  54.     if (key == null) {  
  55.       key = new LongWritable();  
  56.     }  
  57.     key.set(pos);  
  58.       
  59.     if (value == null) {  
  60.       value = new Text();  
  61.     }   
  62.     int newSize = 0;  
  63.     while (pos < end) {  
  64.       newSize = in.readLine(value, maxLineLength,Math.max((int)Math.min(Integer.MAX_VALUE, end-pos), maxLineLength));  
  65.       if (newSize == 0) {  
  66.         break;  
  67.       }  
  68.       pos += newSize;  
  69.       if (newSize < maxLineLength) {  
  70.         break;  
  71.       }  
  72.   
  73.       // line too long. try again  
  74.       LOG.debug("Skipped this line because the line is too long: lineLength["+newSize+"]>maxLineLength["+maxLineLength+"] at position[" + (pos - newSize)+"].");  
  75.     }  
  76.       
  77.     if (newSize == 0) {  
  78.       key = null;  
  79.       value = null;  
  80.       return false;  
  81.         
  82.     }   
  83.     else {  
  84.       return true;  
  85.     }  
  86.   }  
  87.   
  88.   @Override  
  89.   public LongWritable getCurrentKey() {  
  90.     return key;  
  91.   }  
  92.   
  93.   @Override  
  94.   public Text getCurrentValue() {  
  95.     return value;  
  96.   }  
  97.   
  98.   /** 
  99.    * Get the progress within the split 
  100.    */  
  101.   public float getProgress() {  
  102.     if (start == end) {  
  103.       return 0.0f;  
  104.     } else {  
  105.       return Math.min(1.0f, (pos - start) / (float)(end - start));  
  106.     }  
  107.   }  
  108.     
  109.   public synchronized void close() throws IOException {  
  110.     if (in != null) {  
  111.       in.close();   
  112.     }  
  113.   }  
  114. }  
    在记录读取器中,getProgress()被用来报告当前读取输入文件的进度,因为Hadoop为客户端查看当前作业执行进度的API。另外,由于LineRecordReader是按照行来读取的,由于切割器的分割,可能使得某一行在两个数据片中,所以在初始化的时候有一个是否跳过第一行的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值