Module 2 HDFS Notes
Module 2 HDFS Notes
CO2: Apply appropriate tools and frameworks (Hadoop, Spark, NoSQL) for storing, processing,
and managing large-scale datasets
3. The Hadoop Distributed Filesystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4. Hadoop I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
vi | Table of Contents
CHAPTER 3
The Hadoop Distributed Filesystem
41
HDFS Concepts
Blocks
HDFS Concepts | 43
fsck
[Link]
hdfs
localhost
[Link]
hadoop fs -help
hdfs://localhost
% hadoop fs -copyFromLocal input/docs/[Link] /user/tom/[Link]
ls -l
r w
x
[Link]
Hadoop Filesystems
[Link]
Hadoop Filesystems | 47
Filesystem URI scheme Java implementation (all under [Link]) Description
Local file [Link] A filesystem for a locally connec-
ted disk with client-side check-
sums. Use RawLocalFileSys
tem for a local filesystem with no
checksums. See “LocalFileSys-
tem” on page 76.
HDFS hdfs [Link] Hadoop’s distributed filesystem.
HDFS is designed to work effi-
ciently in conjunction with Map-
Reduce.
HFTP hftp [Link] A filesystem providing read-only
access to HDFS over HTTP. (Despite
its name, HFTP has no connection
with FTP.) Often used with distcp
(“Parallel Copying with
distcp” on page 70) to copy data
between HDFS clusters running
different versions.
HSFTP hsftp [Link] A filesystem providing read-only
access to HDFS over HTTPS. (Again,
this has no connection with FTP.)
HAR har [Link] A filesystem layered on another
filesystem for archiving files. Ha-
doop Archives are typically used
for archiving files in HDFS to reduce
the namenode’s memory usage.
See “Hadoop Ar-
chives” on page 71.
KFS (Cloud- kfs [Link] CloudStore (formerly Kosmos fil-
Store) esystem) is a distributed filesys-
tem like HDFS or Google’s GFS,
written in C++. Find more infor-
mation about it at [Link]
.[Link]/.
FTP ftp [Link] A filesystem backed by an FTP
server.
S3 (native) s3n fs.s3native.NativeS3FileSystem A filesystem backed by Amazon
S3. See [Link]
doop/AmazonS3.
S3 (block- s3 fs.s3.S3FileSystem A filesystem backed by Amazon
based) S3, which stores files in blocks
(much like HDFS) to overcome S3’s
5 GB file size limit.
Interfaces
FileSystem
Thrift
Writable
Hadoop Filesystems | 49
C
FileSystem
FUSE
ls cat
WebDAV
FTPFileSystem
DistributedFileSystem
FileSystem
hdfs
setURLStreamHandlerFactory URL
FsUrlStreamHandlerFactory
URLStreamHandlerFactory
FileSystem
static {
[Link](new FsUrlStreamHandlerFactory());
}
IOUtils
finally
[Link] copyBytes
[Link]
Path
[Link]
Path
FileSystem
public static FileSystem get(Configuration conf) throws IOException
public static FileSystem get(URI uri, Configuration conf) throws IOException
Configuration
URI
URI
FileSystem open()
package [Link];
Seekable
getPos()
public interface Seekable {
void seek(long pos) throws IOException;
long getPos() throws IOException;
boolean seekToNewSource(long targetPos) throws IOException;
}
seek()
IOException skip() [Link]
seek()
seekToNewSource()
targetPos
FSDataInputStream PositionedReadable
public int read(long position, byte[] buffer, int offset, int length)
throws IOException;
public void readFully(long position, byte[] buffer, int offset, int length)
throws IOException;
Seekable
long oldPos = getPos();
try {
seek(position);
// read data
} finally {
seek(oldPos);
}
seek()
create()
exists()
Progressable
package [Link];
append()
public FSDataOutputStream append(Path f) throws IOException
progress()
progress()
FSDataOutputStream
create() FileSystem FSDataOutputStream
FSDataInputStream
package [Link];
// implementation elided
FSDataInputStream FSDataOutputStream
Directories
FileSystem
public boolean mkdirs(Path f) throws IOException
FileStatus
@Before
public void setUp() throws IOException {
Configuration conf = new Configuration();
if ([Link]("[Link]") == null) {
[Link]("[Link]", "/tmp");
}
cluster = new MiniDFSCluster(conf, 1, true, null);
fs = [Link]();
OutputStream out = [Link](new Path("/dir/file"));
[Link]("content".getBytes("UTF-8"));
[Link]();
}
@After
public void tearDown() throws IOException {
if (fs != null) { [Link](); }
if (cluster != null) { [Link](); }
}
@Test(expected = [Link])
public void throwsFileNotFoundForNonExistentFile() throws IOException {
[Link](new Path("no-such-file"));
}
@Test
public void fileStatusForFile() throws IOException {
Path file = new Path("/dir/file");
FileStatus stat = [Link](file);
assertThat([Link]().toUri().getPath(), is("/dir/file"));
assertThat([Link](), is(false));
assertThat([Link](), is(7L));
@Test
public void fileStatusForDirectory() throws IOException {
Path dir = new Path("/dir");
FileStatus stat = [Link](dir);
assertThat([Link]().toUri().getPath(), is("/dir"));
assertThat([Link](), is(true));
assertThat([Link](), is(0L));
assertThat([Link](),
is(lessThanOrEqualTo([Link]())));
assertThat([Link](), is((short) 0));
assertThat([Link](), is(0L));
assertThat([Link](), is("tom"));
assertThat([Link](), is("supergroup"));
assertThat([Link]().toString(), is("rwxr-xr-x"));
}
FileNotFoundException
exists()
FileSystem
public boolean exists(Path f) throws IOException
Listing files
FileSystem listStatus()
FileStatus
FileStatus
PathFilter
listStatus FileStatus
File patterns
FileSystem
public FileStatus[] globStatus(Path pathPattern) throws IOException
public FileStatus[] globStatus(Path pathPattern, PathFilter filter) throws IOException
globStatus() FileStatus
PathFilter
Glob Expansion
/* /2007 /2008
/*/* /2007/12 /2008/01
/*/12/* /2007/12/30 /2007/12/31
/200? /2007 /2008
/200[78] /2007 /2008
/200[7-8] /2007 /2008
/200[^01234569] /2007 /2008
/*/*/{31,01} /2007/12/31 /2008/01/01
/*/*/3{0,1} /2007/12/30 /2007/12/31
/*/{12/31,01/01} /2007/12/31 /2008/01/01
PathFilter
PathFilter
Path
PathFilter
Deleting Data
delete() FileSystem
public boolean delete(Path f, boolean recursive) throws IOException
f recursive
recursive true
IOException
open() FileSystem
DistributedFileSystem
DistributedFileSystem
DistributedFileSystem FSDataInputStream
FSDataInputStream
DFSInputStream
Data Flow | 63
read() DFSInputStream
read()
DFSInputStream
DFSInputStream
close() FSDataInputStream
create() DistributedFileSystem
DistributedFileSystem
DataStreamer
[Link]
[Link]
close()
Data
Streamer
Replica Placement
Data Flow | 67
Coherency Model
fsync
sync()
Path p = new Path("p");
OutputStream out = [Link](p);
[Link]("content".getBytes("UTF-8"));
[Link]();
assertThat([Link](p).getLen(), is(((long) "content".length())));
sync()
sync()
sync()
sync()
Data Flow | 69
Parallel Copying with distcp
-overwrite
-update
-overwrite -update
-overwrite -update
[Link]
-m
1
Hadoop Archives
Hadoop Archives | 71
Using Hadoop Archives
archive
% hadoop archive -archiveName [Link] /my/files /my
Limitations
InputFormat
Hadoop Archives | 73
CHAPTER 4
Hadoop I/O
Data Integrity
75
ChecksumException IOException
DataBlockScanner
ChecksumException
false setVerify
Checksum() FileSystem open()
-ignoreCrc -get
-copyToLocal
LocalFileSystem
LocalFileSystem
[Link]
LocalFileSystem ChecksumException
ChecksumFileSystem
LocalFileSystem ChecksumFileSystem
ChecksumFileSys
tem FileSystem
FileSystem rawFs = ...
FileSystem checksummedFs = new ChecksumFileSystem(rawFs);
ChecksumFileSystem
reportChecksumFailure()
LocalFileSystem
Compression
Compression | 77
Compression format Tool Algorithm Filename extension Multiple files Splittable
DEFLATEa N/A DEFLATE .deflate No No
gzip gzip DEFLATE .gz No No
ZIP zip DEFLATE .zip Yes Yes, at file boundaries
bzip2 bzip2 bzip2 .bz2 No Yes
LZO lzop LZO .lzo No No
–1 -9
gzip -1 file
LzopCodec lzop
LzoCodec
CompressionOutputStream CompressionInputStream
[Link] [Link]
SequenceFile
Compression | 79
String codecClassname = args[0];
Class<?> codecClass = [Link](codecClassname);
Configuration conf = new Configuration();
CompressionCodec codec = (CompressionCodec)
[Link](codecClass, conf);
CompressionCodec
ReflectionUtils
[Link]
copyBytes() IOUtils
CompressionOutputStream finish()
CompressionOutputStream
StreamCompressor
GzipCodec
% echo "Text" | hadoop StreamCompressor [Link] \
| gunzip -
Text
GzipCodec
CompressionCodecFactory
CompressionCodec getCodec() Path
String outputUri =
[Link](uri, [Link]());
InputStream in = null;
OutputStream out = null;
try {
in = [Link]([Link](inputPath));
out = [Link](new Path(outputUri));
[Link](in, out, conf);
} finally {
[Link](in);
[Link](out);
}
}
}
removeSuffix() CompressionCodecFactory
CompressionCodecFactory
[Link]
CompressionCodecFactory
Native libraries
Compression | 81
Compression format Java implementation Native implementation
DEFLATE Yes Yes
gzip Yes Yes
bzip2 Yes No
LZO No Yes
[Link]
[Link]
false
CodecPool.
CodecPool
Compressor
Compressor CompressionCodec
createOutputStream() finally
IOException
Compression | 83
Which Compression Format Should I Use?
[Link]([Link]);
[Link]([Link]);
[Link]("[Link]", true);
[Link]("[Link]", [Link],
[Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link](conf);
}
}
% gunzip -c output/[Link]
1949 111
1950 22
[Link]
[Link]
RECORD BLOCK
Compression | 85
Property name Type Default value Description
[Link] boolean false Compress map outputs.
[Link]. Class [Link]. The compression codec to use for
[Link] [Link] map outputs.
[Link](true);
[Link]([Link]);
Serialization
import [Link];
import [Link];
import [Link];
Writable
IntWritable int
set()
IntWritable writable = new IntWritable();
[Link](163);
IntWritable
[Link] [Link]
[Link]
public static byte[] serialize(Writable writable) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(out);
[Link](dataOut);
[Link]();
Serialization | 87
return [Link]();
}
[Link]
StringUtils
assertThat([Link](bytes), is("000000a3"));
Writable
IntWritable deserialize()
get()
IntWritable newWritable = new IntWritable();
deserialize(newWritable, bytes);
assertThat([Link](), is(163));
RawComparator Comparator
package [Link];
import [Link];
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2);
IntWritable compare()
b1 b2
s1 s2 l1 l2
WritableComparator RawComparator
WritableComparable
compare()
compare()
RawComparator Writable
IntWritable
RawComparator<IntWritable> comparator = [Link]([Link]);
IntWritable
IntWritable w1 = new IntWritable(163);
IntWritable w2 = new IntWritable(67);
assertThat([Link](w1, w2), greaterThan(0));
byte[] b1 = serialize(w1);
byte[] b2 = serialize(w2);
assertThat([Link](b1, 0, [Link], b2, 0, [Link]),
greaterThan(0));
Writable Classes
Writable [Link]
Serialization | 89
Java primitive Writable implementation Serialized size (bytes)
long LongWritable 8
VLongWritable 1–9
double DoubleWritable 8
VIntWritable VLongWritable
long
Text
Text Writable Writable
[Link] Text UTF8
Text int
Text
Indexing.
Text String Text
char String
charAt()
Text t = new Text("hadoop");
assertThat([Link](), is(6));
assertThat([Link]().length, is(6));
charAt() int
String char Text find()
String indexOf()
Text t = new Text("hadoop");
assertThat("Find a substring", [Link]("do"), is(2));
assertThat("Finds first 'o'", [Link]("o"), is(3));
assertThat("Finds 'o' from position 4 or later", [Link]("o", 4), is(4));
assertThat("No match", [Link]("pig"), is(-1));
Serialization | 91
Unicode.
Text String
char char
String Text
@Test
public void string() throws UnsupportedEncodingException {
String s = "\u0041\u00DF\u6771\uD801\uDC00";
assertThat([Link](), is(5));
assertThat([Link]("UTF-8").length, is(10));
assertThat([Link]("\u0041"), is(0));
assertThat([Link]("\u00DF"), is(1));
assertThat([Link]("\u6771"), is(2));
assertThat([Link]("\uD801\uDC00"), is(3));
assertThat([Link](0), is('\u0041'));
assertThat([Link](1), is('\u00DF'));
assertThat([Link](2), is('\u6771'));
assertThat([Link](3), is('\uD801'));
assertThat([Link](4), is('\uDC00'));
assertThat([Link](0), is(0x0041));
assertThat([Link](1), is(0x00DF));
assertThat([Link](2), is(0x6771));
assertThat([Link](3), is(0x10400));
}
@Test
public void text() {
assertThat([Link]("\u0041"), is(0));
assertThat([Link]("\u00DF"), is(1));
assertThat([Link]("\u6771"), is(3));
assertThat([Link]("\uD801\uDC00"), is(6));
assertThat([Link](0), is(0x0041));
assertThat([Link](1), is(0x00DF));
assertThat([Link](3), is(0x6771));
assertThat([Link](6), is(0x10400));
}
}
String char
Text
indexOf() String char
find() Text
charAt() String char
code
PointAt() char
int charAt() Text
codePointAt() String
Iteration. Text
Text [Link]
bytesToCodePoint() Text
int
bytesToCodePoint()
Serialization | 93
% hadoop TextIterator
41
df
6771
10400
getBytes()
getLength()
Text t = new Text("hadoop");
[Link](new Text("pig"));
assertThat([Link](), is(3));
assertThat("Byte length not shortened", [Link]().length, is(6));
getLength()
getBytes()
BytesWritable
BytesWritable
00000002 03 05
BytesWritable b = new BytesWritable(new byte[] { 3, 5 });
byte[] bytes = serialize(b);
assertThat([Link](bytes), is("000000020305"));
BytesWritable set()
Text getBytes() Byte
sWritable
BytesWritable BytesWritable get
Length()
[Link](11);
assertThat([Link](), is(2));
assertThat([Link]().length, is(11));
NullWritable
NullWritable
SequenceFile
[Link]()
ObjectWritable
SequenceFile
ObjectWritable ObjectWritable
GenericWritable
Writable collections
Writable [Link] Array
Writable TwoDArrayWritable MapWritable SortedMapWritable
ArrayWritable TwoDArrayWritable Writable
Writable
ArrayWritable TwoDArrayWritable
Writable SequenceFile
ArrayWritable
TwoDArrayWritable
public class TextArrayWritable extends ArrayWritable {
public TextArrayWritable() {
super([Link]);
}
}
Serialization | 95
MapWritable SortedMapWritable [Link]<Writable,
Writable> [Link]<WritableComparable, Writable>
[Link]
Writable
MapWritable SortedMapWritable
byte
Writable MapWritable SortedMapWritable
MapWritable
Writable
MapWritable SortedMapWritable
NullWritable Writable ArrayWritable
Writable
GenericWritable ArrayWritable
ListWritable MapWritable
Writable
Writable
Writable
Writable
Writable
TextPair
import [Link].*;
import [Link].*;
public TextPair() {
set(new Text(), new Text());
}
@Override
public void write(DataOutput out) throws IOException {
[Link](out);
[Link](out);
}
@Override
public void readFields(DataInput in) throws IOException {
[Link](in);
[Link](in);
}
@Override
public int hashCode() {
return [Link]() * 163 + [Link]();
}
@Override
public boolean equals(Object o) {
if (o instanceof TextPair) {
TextPair tp = (TextPair) o;
return [Link]([Link]) && [Link]([Link]);
}
return false;
}
Serialization | 97
@Override
public String toString() {
return first + "\t" + second;
}
@Override
public int compareTo(TextPair tp) {
int cmp = [Link]([Link]);
if (cmp != 0) {
return cmp;
}
return [Link]([Link]);
}
}
Text
first second
Writable
readFields()
write() readFields()
TextPair write() Text
Text readFields()
Text DataOutput
DataInput
Writable
Writable TextOutputFormat
toString() TextOutputFormat
toString() Text
Pair Text
TextPair WritableComparable
compareTo()
TextPair TextArrayWrita
ble Text
TextArrayWritable Writable WritableComparable
TextPair
compareTo()
TextPair
TextPair Text
Text
TextPair
public Comparator() {
super([Link]);
}
@Override
public int compare(byte[] b1, int s1, int l1,
byte[] b2, int s2, int l2) {
try {
int firstL1 = [Link](b1[s1]) + readVInt(b1, s1);
int firstL2 = [Link](b2[s2]) + readVInt(b2, s2);
int cmp = TEXT_COMPARATOR.compare(b1, s1, firstL1, b2, s2, firstL2);
if (cmp != 0) {
return cmp;
}
return TEXT_COMPARATOR.compare(b1, s1 + firstL1, l1 - firstL1,
b2, s2 + firstL2, l2 - firstL2);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
static {
[Link]([Link], new Comparator());
}
WritableComparator RawComparator
Serialization | 99
firstL1 firstL2
Text
decodeVIntSize() WritableUtils
readVInt()
TextPair
Custom comparators
TextPair
Writable [Link]
WritableUtils
RawComparator
TextPair First
Comparator
compare() compare()
public FirstComparator() {
super([Link]);
}
@Override
public int compare(byte[] b1, int s1, int l1,
byte[] b2, int s2, int l2) {
try {
int firstL1 = [Link](b1[s1]) + readVInt(b1, s1);
int firstL2 = [Link](b2[s2]) + readVInt(b2, s2);
return TEXT_COMPARATOR.compare(b1, s1, firstL1, b2, s2, firstL2);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
if (a instanceof TextPair && b instanceof TextPair) {
return ((TextPair) a).[Link](((TextPair) b).first);
Serialization Frameworks
Writable
Serialization
[Link] WritableSerialization
Serialization Writable
Serialization Serializer
Deserializer
[Link]
Serialization [Link]
[Link] Writable
JavaSerialization
Integer String
Serialization | 101
[Link]
[Link]
Serialization IDL
[Link]
SequenceFile
SequenceFile
LongWrit
able Writable
SequenceFile
SequenceFile
SequenceFile
Writing a SequenceFile
SequenceFile createWriter()
[Link]
FSDataOutputStream FileSys
tem Path Configuration
Progressable
Metadata SequenceFile
SequenceFile Writable
Serialization
Serialization
Serialization
SequenceFile
IntWritable Text
[Link] getLength()
Reading a SequenceFile
[Link]
next()
Writable next()
true false
Writable
[Link]
next() null
getCurrentValue()
next() null
Writable Sequence
[Link] getKeyClass() getValueClass() ReflectionUtils
Writable
[Link]
seek()
[Link](359);
assertThat([Link](key, value), is(true));
assertThat(((IntWritable) key).get(), is(95));
next()
[Link](360);
[Link](key, value); // fails with IOException
sync(long
position) [Link]
position
sync()
[Link](360);
assertThat([Link](), is(2021L));
assertThat([Link](key, value), is(true));
assertThat(((IntWritable) key).get(), is(59));
[Link] sync()
sync()
Syncable
SEQ
SequenceFile
[Link]
[Link]
MapFile
MapFile SequenceFile MapFile
[Link]
Map
Writing a MapFile
MapFile SequenceFile
[Link] append()
IOException
WritableComparable Writable SequenceFile
MapFile
% hadoop MapFileWriteDemo [Link]
MapFile
% ls -l [Link]
total 104
-rw-r--r-- 1 tom tom 47898 Jul 29 22:06 data
-rw-r--r-- 1 tom tom 251 Jul 29 22:06 index
SequenceFile
% hadoop fs -text [Link]/data | head
1 One, two, buckle my shoe
2 Three, four, shut the door
3 Five, six, pick up sticks
[Link]
setIndexInterval() [Link]
MapFile
MapFile
Reading a MapFile
MapFile
SequenceFile [Link] next()
false
public boolean next(WritableComparable key, Writable val) throws IOException
get()
public Writable get(WritableComparable key, Writable val) throws IOException
MapFile null
key key
val
MapFile
[Link]
getClosest() get()
null MapFile
MapFile boolean
MapFile
MapFile [Link]
0 1
2
fix()
MapFile
MapFile