如何在Spark中读取无扩展名的压缩(gzip)文件

时间:2018-08-24 21:03:00

标签: apache-spark gzip

我是Spark的新手,有一个有趣的任务,我必须从S3中读取一堆文件,其中包含一些xml内容。

这些文件已压缩(Gzip),但没有该扩展名。

我在此处阅读了一些问题,人们建议在Spark中扩展默认编解码器并强制进行其他扩展。

但是对于我来说,没有扩展名,文件以大约16位UUID格式命名,例如2c7358ca472ad91057da84adfba

2 个答案:

答案 0 :(得分:1)

您可以将newAPIHadoopFile(而不是textFile)与经过定制/修改的TextInputFormat配合使用,从而强制使用GzipCodec

代替调用sparkContext.textFile

// gzip compressed but no .gz extension:
sparkContext.textFile("s3://mybucket/uuid")

我们可以使用基础的sparkContext.newAPIHadoopFile,它允许我们指定如何读取输入:

import org.apache.hadoop.mapreduce.lib.input.GzipInputFormatWithoutExtention
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.io.{LongWritable, Text}

sparkContext
  .newAPIHadoopFile(
    "s3://mybucket/uuid",
    classOf[GzipInputFormatWithoutExtention], // This is our custom reader
    classOf[LongWritable],
    classOf[Text],
    new Configuration(sparkContext.hadoopConfiguration)
  )
  .map { case (_, text) => text.toString }

调用newAPIHadoopFile的通常方法是使用TextInputFormat。这是包装如何读取文件以及根据文件扩展名选择压缩编解码器的部分。

我们称它为GzipInputFormatWithoutExtention并以TextInputFormat的扩展名的形式实现(这是一个Java文件,我们将其放在src / main / java / org / apache / hadoop / mapreduce包中) / lib / input):

package org.apache.hadoop.mapreduce.lib.input;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import com.google.common.base.Charsets;

public class GzipInputFormatWithoutExtention extends TextInputFormat {

    public RecordReader<LongWritable, Text> createRecordReader(
        InputSplit split,
        TaskAttemptContext context
    ) {

        String delimiter =
            context.getConfiguration().get("textinputformat.record.delimiter");

        byte[] recordDelimiterBytes = null;
        if (null != delimiter)
            recordDelimiterBytes = delimiter.getBytes(Charsets.UTF_8);

        // Here we use our custom `GzipWithoutExtentionLineRecordReader`
        // instead of `LineRecordReader`:
        return new GzipWithoutExtentionLineRecordReader(recordDelimiterBytes);
    }

    @Override
    protected boolean isSplitable(JobContext context, Path file) {
        return false; // gzip isn't a splittable codec (as opposed to bzip2)
    }
}

实际上,我们必须更深入一点,并且还要用我们自己的默认LineRecordReader(Java)(我们将其称为GzipWithoutExtentionLineRecordReader)代替。

由于很难从LineRecordReader继承,我们可以复制LineRecordReader(在src / main / java / org / apache / hadoop / mapreduce / lib / input中)并稍加修改(并简化)initialize(InputSplit genericSplit, TaskAttemptContext context)方法,通过强制使用Gzip编解码器:

(与原始LineRecordReader相比,仅有的更改已获得注释以说明正在发生的事情)

package org.apache.hadoop.mapreduce.lib.input;

import java.io.IOException;

import org.apache.hadoop.io.compress.*;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.Seekable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@InterfaceAudience.LimitedPrivate({"MapReduce", "Pig"})
@InterfaceStability.Evolving
public class GzipWithoutExtentionLineRecordReader extends RecordReader<LongWritable, Text> {
    private static final Logger LOG =
            LoggerFactory.getLogger(GzipWithoutExtentionLineRecordReader.class);
    public static final String MAX_LINE_LENGTH =
            "mapreduce.input.linerecordreader.line.maxlength";

    private long start;
    private long pos;
    private long end;
    private SplitLineReader in;
    private FSDataInputStream fileIn;
    private Seekable filePosition;
    private int maxLineLength;
    private LongWritable key;
    private Text value;
    private boolean isCompressedInput;
    private Decompressor decompressor;
    private byte[] recordDelimiterBytes;

    public GzipWithoutExtentionLineRecordReader(byte[] recordDelimiter) {
        this.recordDelimiterBytes = recordDelimiter;
    }

    public void initialize(
        InputSplit genericSplit,
        TaskAttemptContext context
    ) throws IOException {

        FileSplit split = (FileSplit) genericSplit;
        Configuration job = context.getConfiguration();
        this.maxLineLength = job.getInt(MAX_LINE_LENGTH, Integer.MAX_VALUE);
        start = split.getStart();
        end = start + split.getLength();
        final Path file = split.getPath();

        // open the file and seek to the start of the split
        final FileSystem fs = file.getFileSystem(job);
        fileIn = fs.open(file);

        // This line is modified to force the use of the GzipCodec:
        // CompressionCodec codec = new CompressionCodecFactory(job).getCodec(file);
        CompressionCodecFactory ccf = new CompressionCodecFactory(job);
        CompressionCodec codec = ccf.getCodecByClassName(GzipCodec.class.getName());

        // This part has been extremely simplified as we don't have to handle
        // all the different codecs:
        isCompressedInput = true;
        decompressor = CodecPool.getDecompressor(codec);
        if (start != 0) {
            throw new IOException(
                "Cannot seek in " + codec.getClass().getSimpleName() + " compressed stream"
            );
        }

        in = new SplitLineReader(
            codec.createInputStream(fileIn, decompressor), job, this.recordDelimiterBytes
        );
        filePosition = fileIn;
        if (start != 0) {
            start += in.readLine(new Text(), 0, maxBytesToConsume(start));
        }
        this.pos = start;
    }

    private int maxBytesToConsume(long pos) {
        return isCompressedInput
                ? Integer.MAX_VALUE
                : (int) Math.max(Math.min(Integer.MAX_VALUE, end - pos), maxLineLength);
    }

    private long getFilePosition() throws IOException {
        long retVal;
        if (isCompressedInput && null != filePosition) {
            retVal = filePosition.getPos();
        } else {
            retVal = pos;
        }
        return retVal;
    }

    private int skipUtfByteOrderMark() throws IOException {
        int newMaxLineLength = (int) Math.min(3L + (long) maxLineLength,
                Integer.MAX_VALUE);
        int newSize = in.readLine(value, newMaxLineLength, maxBytesToConsume(pos));
        pos += newSize;
        int textLength = value.getLength();
        byte[] textBytes = value.getBytes();
        if ((textLength >= 3) && (textBytes[0] == (byte)0xEF) &&
                (textBytes[1] == (byte)0xBB) && (textBytes[2] == (byte)0xBF)) {
            LOG.info("Found UTF-8 BOM and skipped it");
            textLength -= 3;
            newSize -= 3;
            if (textLength > 0) {
                textBytes = value.copyBytes();
                value.set(textBytes, 3, textLength);
            } else {
                value.clear();
            }
        }
        return newSize;
    }

    public boolean nextKeyValue() throws IOException {
        if (key == null) {
            key = new LongWritable();
        }
        key.set(pos);
        if (value == null) {
            value = new Text();
        }
        int newSize = 0;
        while (getFilePosition() <= end || in.needAdditionalRecordAfterSplit()) {
            if (pos == 0) {
                newSize = skipUtfByteOrderMark();
            } else {
                newSize = in.readLine(value, maxLineLength, maxBytesToConsume(pos));
                pos += newSize;
            }

            if ((newSize == 0) || (newSize < maxLineLength)) {
                break;
            }

            LOG.info("Skipped line of size " + newSize + " at pos " +
                    (pos - newSize));
        }
        if (newSize == 0) {
            key = null;
            value = null;
            return false;
        } else {
            return true;
        }
    }

    @Override
    public LongWritable getCurrentKey() {
        return key;
    }

    @Override
    public Text getCurrentValue() {
        return value;
    }

    public float getProgress() throws IOException {
        if (start == end) {
            return 0.0f;
        } else {
            return Math.min(1.0f, (getFilePosition() - start) / (float)(end - start));
        }
    }

    public synchronized void close() throws IOException {
        try {
            if (in != null) {
                in.close();
            }
        } finally {
            if (decompressor != null) {
                CodecPool.returnDecompressor(decompressor);
                decompressor = null;
            }
        }
    }
}

答案 1 :(得分:0)

已提交https://issues.apache.org/jira/browse/HADOOP-17231

从Hadoop方面轻松解决问题。