Você está na página 1de 49

"BIG DATA ANALYTICS"

(15CS82 CBCS as per VTU Syllabus)

Module-1
Hadoop Distributed File System (HDFS) Basics
Hadoop Distributed File System (HDFS) is a distributed file system which is designed to run on
commodity hardware. Commodity hardware is cheaper in cost. Since Hadoop requires processing
power of multiple machines and since it is expensive to deploy costly hardware, we use commodity
hardware. When commodity hardware is used, failures are more common rather than an exception.
HDFS is highly fault-tolerant and is designed to run on commodity hardware.
HDFS provides high throughput access to the data stored. So it is extremely useful when you want
to build applications which require large data sets.
HDFS was originally built as infrastructure layer for Apache Nutch. It is now pretty much part of
Apache Hadoop project.

Fig 1.1 HDFS ARchitecture


HDFS has master/slave architecture. In this architecture one of the machines will be designated as
a master node (or name node). Every other machine would be acting as slave (or data node).
NameNode/DataNode are java processes that run on the machines when Hadoop software is
installed.
NameNode is responsible for managing the metadata about the HDFS Files. This metadata
includes various information about the HDFS File such as Name of the file, File Permissions,
FileSize, Blocks etc. It is also responsible for performing various namespace operations like
opening, closing, renaming the files or directories.
Whenever a file is to be stored in HDFS, it is divided into blocks. By default, blocksize is 64MB
(Configurable). These blocks are replicated (default is 3) and stored across various datanodes to
take care of hardware failures and for faster data transfers. NameNode maintains a mapping of
blocks to DataNodes.

1
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

DataNodes serves the read and write requests from HDFS file system clients. They are also
responsible for creation of block replicas and for checking if blocks are corrupted or not. It sends
the ping messages to the NameNode in the form of block mappings.

How communication happens?


1. HDFS exposes Java/C API using which user can write an application to interact with HDFS.
Application using this API Interacts with Client Library (present on the same client machine).
2. Client (Library) connects to the NameNode using RPC. The communication between them
happens using ClientProtocol. Major functionality in ClientProtocol includes Create (creates a file
in name space), Append (add to the end of already existing file), Complete (client has finished
writing to file), Read etc.
3. Client (Library) interacts with DataNode directly using DataTransferProtocol. The
DataTransferProtocol defines operations to read a block, write to block, get checksum of block,
copy the block etc.
4. Interaction between NameNode and DataNode. It‘s always DataNode which initiates the
communication first and NameNode just responds to the requests intiated. The communication
usually involves DataNode Registration, DataNode sending heart beat messages, DataNode
sending blockreport, DataNode notifying the receipt of Block from a client or another DataNode
during replication of blocks.
Assumptions and Goals
1. Hardware Failure Hardware Failure is the norm rather than the exception. The entire HDFS
file system may consist of hundreds or thousands of server machines that stores pieces of file
system data. The fact that there are a huge number of components and that each component has a
non-trivial probability of failure means that some component of HDFS is always non-functional.
Therefore, detection of faults and automatically recovering quickly from those faults are core
architectural goals of HDFS.
2. Streaming Data Access: Applications that run on HDFS need streaming access to their data
sets. They are not general purpose applications that typically run on a general purpose file system.
HDFS is designed more for batch processing rather than interactive use by users. The emphasis is
on throughput of data access rather than latency of data access. POSIX imposes many hard
requirements that are not needed for applications that are targeted for HDFS. POSIX semantics in a
few key areas have been traded off to further enhance data throughout rates.
3. Large Data Sets: Applications that run on HDFS have large data sets. This means that a typical
file in HDFS is gigabytes to terabytes in size. Thus, HDFS is tuned to support large files. It should
provide high aggregate data bandwidth and should scale to hundreds of nodes in a single cluster. It
should support tens of millions of files in a single cluster.
4. Simple Coherency Model: Most HDFS applications need write-once-read-many access model
for files. A file once created, written and closed need not be changed. This assumption simplifies
data coherency issues and enables high throughout data access. A Map-Reduce application or a
Web-Crawler application fits perfectly with this model. There is a plan to support appending-writes
to a file in future.

2
“BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

5. Moving computation is cheaper than moving data: A computation requested by an


application is most optimal if the computation can be done near where the data is located. This is
especially true when the size of the data set is huge. This eliminates network congestion and
increase overall throughput of the system. The assumption is that it is often better to migrate the
computation closer to where the data is located rather than moving the data to where the
application is running. HDFS provides interfaces for applications to move themselves closer to
where the data is located.
6. Portability across Heterogeneous Hardware and Software Platforms: HDFS should be
designed in such a way that it is easily portable from one platform to another. This facilitates
widespread adoption of HDFS as a platform of choice for a large set of applications.

Namenode and Datanode


HDFS has a master/slave architecture. An HDFS cluster consists of a single Namenode, a master
server that manages the filesystem namespace and regulates access to files by clients. In addition,
there are a number of Datanodes, one per node in the cluster, which manage storage attached to the
nodes that they run on. HDFS exposes a file system namespace and allows user data to be stored in
files. Internally, a file is split into one or more blocks and these blocks are stored in a set of
Datanodes. The Namenode makes filesystem namespace operations like opening, closing,
renaming etc. of files and directories. It also determines the mapping of blocks to Datanodes. The
Datanodes are responsible for serving read and write requests from filesystem clients. The
Datanodes also perform block creation, deletion, and replication upon instruction from the
Namenode. The Namenode and Datanode are pieces of software that run on commodity machines.
These machines are typically commodity Linux machines. HDFS is built using the Java language;
any machine that support Java can run the Namenode or the Datanode. Usage of the highly
portable Java language means that HDFS can be deployed on a wide range of machines. A typical
deployment could have a dedicated machine that runs only the Namenode software. Each of the
other machines in the cluster runs one instance of the Datanode software. The architecture does not
preclude running multiple Datanodes on the same machine but in a real-deployment that is never
the case. The existence of a single Namenode in a cluster greatly simplifies the architecture of the
system. The Namenode is the arbitrator and repository for all HDFS metadata. The system is
designed in such a way that user data never flows through the Namenode.

The File System Namespace


HDFS supports a traditional hierarchical file organization. A user or an application can create
directories and store files inside these directories. The file system namespace hierarchy is similar to
most other existing file systems. One can create and remove files, move a file from one directory to
another, or rename a file. HDFS does not yet implement user quotas and access permissions.
HDFS does not support hard links and soft links. However, the HDFS architecture does not
preclude implementing these features at a later time. The Namenode maintains the file system
namespace. Any change to the file system namespace and properties are recorded by the
Namenode. An application can specify the number of replicas of a file that should be maintained
by HDFS. The number of copies of a file is called the replication factor of that file. This
information is stored by the Namenode.

3
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

Data Replication
HDFS is designed to reliably store very large files across machines in a large cluster. It stores each
file as a sequence of blocks; all blocks in a file except the last block are the same size. Blocks
belonging to a file are replicated for fault tolerance. The block size and replication factor are
configurable per file. Files in HDFS are write-once and have strictly one writer at any time. An
application can specify the number of replicas of a file. The replication factor can be specified at
file creation time and can be changed later. The Namenode makes all decisions regarding
replication of blocks. It periodically receives Heartbeat and a Blockreport from each of the
Datanodes in the cluster. A receipt of a heartbeat implies that the Datanode is in good health and is
serving data as desired. A Blockreport contains a list of all blocks on that Datanode.

Replica Placement the First Baby Steps


The selection of placement of replicas is critical to HDFS reliability and performance. This feature
distinguishes HDFS from most other distributed file systems. This is a feature that needs lots of
tuning and experience. The purpose of a rack-aware replica placement is to improve data
reliability, availability, and network bandwidth utilization. The current implementation for the
replica placement policy is a first effort in this direction. The short-term goals of implementing this
policy are to validate it on production systems, learn more about its behavior and build a
foundation to test and research more sophisticated policies in the future. HDFS runs on a cluster of
computers that spread across many racks. Communication between two nodes on different racks
has to go through switches. In most cases, network bandwidth between two machines in the same
rack is greater than network bandwidth between two machines on different racks.
At startup time, each Datanode determines the rack it belongs to and notifies the Namenode of the
rack id upon registration. HDFS provides APIs to facilitate pluggable modules that can be used to
determine the rack identity of a machine. A simple but non-optimal policy is to place replicas
across racks. This prevents losing data when an entire rack fails and allows use of bandwidth from
multiple racks when reading data. This policy evenly distributes replicas in the cluster and thus
makes it easy to balance load on component failure. However, this policy increases the cost of
writes because a write needs to transfer blocks to multiple racks.
For the most common case when the replica factor is three, HDFS.s placement policy is to place
one replica on the local node, place another replica on a different node at the local rack, and place
the last replica on different node at a different rack. This policy cuts the inter-rack write traffic and
improves write performance. The chance of rack failure is far less than that of node failure; this
policy does not impact data reliability and availability guarantees. But it reduces the aggregate
network bandwidth when reading data since a block is placed in only two unique racks rather than
three. The replicas of a file do not evenly distribute across the racks. One third of replicas are on
one node, two thirds of the replicas are on one rack; the other one third of replicas is evenly
distributed across all the remaining racks. This policy improves write performance while not
impacting data reliability or read performance. The implementation of the above policy is work-in-
progress.
Replica Selection
HDFS tries to satisfy a read request from a replica that is closest to the reader. If there exists a
replica on the same rack as the reader node, then that replica is preferred to satisfy the read request.

4
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

If a HDFS cluster spans multiple data centers, then a replica that is resident in the local data center
is preferred over remote replicas.
SafeMode
On startup, the Namenode enters a special state called Safemode. Replication of data blocks does
not occur when the Namenode is in Safemode state. The Namenode receives Heartbeat and
Blockreport from the Datanodes. A Blockreport contains the list of data blocks that a Datanode
reports to the Namenode. Each block has a specified minimum number of replicas. A block is
considered safely-replicated when the minimum number of replicas of that data block has checked
in with the Namenode. When a configurable percentage of safely-replicated data blocks checks in
with the Namenode (plus an additional 30 seconds), the Namenode exits the Safemode state. It
then determines the list of data blocks (if any) that have fewer than the specified number of
replicas. The Namenode then replicates these blocks to other Datanodes.

The Persistence of File System Metadata


The HDFS namespace is stored by the Namenode. The Namenode uses a transaction log called the
EditLog to persistently record every change that occurs to file system metadata. For example,
creating a new file in HDFS causes the Namenode to insert a record into the EditLog indicating
this change. Similarly, changing the replication factor of a file causes a new record to be inserted
into the EditLog. The Namenode uses a file in its local file system to store the Edit Log. The entire
file system namespace, the mapping of blocks to files and filesystem properties are stored in a file
called the FsImage. The FsImage is a file in the Namenode‘s local file system too.
The Namenode has an image of the entire file system namespace and file Blockmap in memory.
This metadata is designed to be compact, so that a 4GB memory on the Namenode machine is
plenty to support a very large number of files and directories. When the Namenode starts up, it
reads the FsImage and EditLog from disk, applies all the transactions from the EditLog into the in-
memory representation of the FsImage and then flushes out this new metadata into a new FsImage
on disk. It can then truncate the old EditLog because its transactions have been applied to the
persistent FsImage. This process is called a checkpoint. In the current implementation, a
checkpoint occurs when the Namenode starts up. Work is in progress to support periodic
checkpointing in the near future.
The Datanode stores HDFS data into files in its local file system. The Datanode has no knowledge
about HDFS files. It stores each block of HDFS data in a separate file in its local file system. The
Datanode does not create all files in the same directory. Instead, it uses a heuristic to determine the
optimal number of files per directory. It creates subdirectories appropriately. It is not optimal to
create all local files in the same directory because the local file system might not be able to
efficiently support a huge number of files in a single directory. When a Datanode starts up, it scans
through its local file system, generates a list of all HDFS data blocks that correspond to each of
these local files and sends this report to the Namenode. This report is called the Blockreport.

The Communication Protocol


All communication protocols are layered on top of the TCP/IP protocol. A client establishes a
connection to a well-defined and configurable port on the Namenode machine. It talks the
ClientProtocol with the Namenode. The Datanodes talk to the Namenode using the
DatanodeProtocol. The details on these protocols will be explained later on. A Remote Procedure

5
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

Call (RPC) abstraction wraps the ClientProtocol and the DatanodeProtocol. By design, the
Namenode never initiates an RPC. It responds to RPC requests issued by a Datanode or a client.

Robustness
The primary objective of HDFS is to store data reliably even in the presence of failures. The three
types of common failures are Namenode failures, Datanode failures and network partitions.

Data Disk Failure, Heartbeats and Re-Replication


A Datanode sends a heartbeat message to the Namenode periodically. A network partition can
cause a subset of Datanodes to lose connectivity with the Namenode. The Namenode detects this
condition be a lack of heartbeat message. The Namenode marks these Datanodes as dead and does
not forward any new IO requests to these Datanodes. The data that was residing on those
Datanodes are not available to HDFS any more. This may cause the replication factor of some
blocks to fall below their specified value. The Namenode determines all the blocks that need to be
replicated and starts replicating them to other Datanodes. The necessity for re-replication may arise
due to many reasons: a Datanode becoming unavailable, a corrupt replica, a bad disk on the
Datanode or an increase of the replication factor of a file.

Cluster Rebalancing
The HDFS architecture is compatible with data rebalancing schemes. It is possible that data may
move automatically from one Datanode to another if the free space on a Datanode falls below a
certain threshold. Also, a sudden high demand for a particular file can dynamically cause creation
of additional replicas and rebalancing of other data in the cluster. These types of rebalancing
schemes are not yet implemented.

Data Correctness
It is possible that a block of data fetched from a Datanode is corrupted. This corruption can occur
because of faults in the storage device, a bad network or buggy software. The HDFS client
implements checksum checking on the contents of a HDFS file. When a client creates a HDFS file,
it computes a checksum of each block on the file and stores these checksums in a separate hidden
file in the same HDFS namespace. When a client retrieves file contents it verifies that the data it
received from a Datanode satisfies the checksum stored in the checksum file. If not, then the client
can opt to retrieve that block from another Datanode that has a replica of that block.

Metadata Disk Failure


The FsImage and the EditLog are central data structures of HDFS. A corruption of these files can
cause the entire cluster to be non-functional. For this reason, the Namenode can be configured to
support multiple copies of the FsImage and EditLog. Any update to either the FsImage or EditLog
causes each of the FsImages and EditLogs to get updated synchronously. This synchronous
updating of multiple EditLog may degrade the rate of namespace transactions per second that a
Namenode can support. But this degradation is acceptable because HDFS applications are very
data intensive in nature; they are not metadata intensive. A Namenode, when it restarts, selects the
latest consistent FsImage and EditLog to use. The Namenode machine is a single point of failure

6
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

for the HDFS cluster. If a Namenode machine fails, manual intervention is necessary. Currently,
automatic restart and failover of the Namenode software to another machine is not supported.

Snapshots
Snapshots support storing a copy of data at a particular instant of time. One usage of the snapshot-
feature may be to roll back a corrupted cluster to a previously known good point in time. HDFS
current does not support snapshots but it will be supported it in future release.

Data Blocks
HDFS is designed to support large files. Applications that are compatible with HDFS are those that
deal with large data sets. These applications write the data only once; they read the data one or
more times and require that reads are satisfied at streaming speeds. HDFS supports write-once-
read-many semantics on files. A typical block size used by HDFS is 64 MB. Thus, a HDFS file is
chopped up into 128MB chunks, and each chunk could reside in different Datanodes.

Staging
A client-request to create a file does not reach the Namenode immediately. In fact, the HDFS client
caches the file data into a temporary local file. An application-write is transparently redirected to
this temporary local file. When the local file accumulates data worth over a HDFS block size, the
client contacts the Namenode. The Namenode inserts the file name into the file system hierarchy
and allocates a data block for it. The Namenode responds to the client request with the identity of
the Datanode(s) and the destination data block. The client flushes the block of data from the local
temporary file to the specified Datanode. When a file is closed, the remaining un-flushed data in
the temporary local file is transferred to the Datanode. The client then instructs the Namenode that
the file is closed. At this point, the Namenode commits the file creation operation into a persistent
store. If the Namenode dies before the file is closed, the file is lost. The above approach has been
adopted after careful consideration of target applications that run on HDFS. Applications need
streaming writes to files. If a client writes to a remote file directly without any client side
buffering, the network speed and the congestion in the network impacts throughput considerably.
This approach is not without precedence either. Earlier distributed file system, e.g. AFS have used
client side caching to improve performance. A POSIX requirement has been relaxed to achieve
higher performance of data uploads.

Pipelining
When a client is writing data to a HDFS file, its data is first written to a local file as explained
above. Suppose the HDFS file has a replication factor of three. When the local file accumulates a
block of user data, the client retrieves a list of Datanodes from the Namenode. This list represents
the Datanodes that will host a replica of that block. The client then flushes the data block to the
first Datanode. The first Datanode starts receiving the data in small portions (4 KB), writes each
portion to its local repository and transfers that portion to the second Datanode in the list. The
second Datanode, in turn, starts receiving each portion of the data block, writes that portion to its
repository and then flushes that portion to the third Datanode. The third Datanode writes the data to

7
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

its local repository. A Datanode could be receiving data from the previous one in the pipeline and
at the same time it could be forwarding data to the next one in the pipeline. Thus, the data is
pipelined from one Datanode to the next.

Accessibility
HDFS can be accessed by application by many different ways. Natively, HDFS provides a Java
API for applications to use. A C language wrapper for this Java API is available. A HTTP browser
can also be used to browse the file in HDFS. Work is in progress to expose a HDFS content
repository through the WebDAV Protocol.

DFSShell
HDFS allows user data to be organized in the form of files and directories. It provides an interface
called DFSShell that lets a user interact with the data in HDFS. The syntax of this command set is
similar to other shells (e.g. bash, csh) that users are already familiar with.
Here are some sample commands:
Create a directory named /foodir : hadoop dfs -mkdir /foodir
View a file /foodir/myfile.txt : hadoop dfs -cat /foodir/myfile.txt
Delete a file /foodir/myfile.txt : hadoop dfs -rm /foodir myfile.txt
The command syntax for DFSShell is targeted for applications that need a scripting language to
interact with the stored data.

DFSAdmin
The DFSAdmin command set is used for administering a dfs cluster. These are commands that are
used only by a HDFS administrator. Here are some sample commands:
Put a cluster in Safe Mode : bin/hadoop dfsadmin -safemode enter
Generate a list of Datanodes : bin/hadoop dfsadmin -report
Decommission a Datanode : bin/hadoop dfsadmin -decommission datanodename

Browser Interface
A typical HDFS install configures a web-server to expose the HDFS namespace through a
configurable port. This allows a Web browser to navigate the HDFS namespace and view contents
of a HDFS file.

Space Reclamation
1. File Deletes and Undelete
When a file is deleted by a user or an application, it is not immediately removed from HDFS.
HDFS renames it to a file in the /trash directory. The file can be restored quickly as long as it
remains in /trash. A file remains in /trash for a configurable amount of time. After the expiry of its
life in /trash, the Namenode deletes the file from the HDFS namespace. The deletion of the file
causes the blocks associated with the file to be freed. There could be an appreciable time delay
between the time a file is deleted by a user and the time of the corresponding increase in free space
in HDFS.

8
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

A user can Undelete a file after deleting it as long as it remains in the /trash directory. If a user
wants to undelete a file that he/she has deleted, he/she can navigate the /trash directory and retrieve
the file. The /trash directory contains only the latest copy of the file that was deleted. The /trash
directory is just like any other directory with one special feature: HDFS applies specified policies
to automatically delete files from this directory. The current default policy is to delete files that are
older than 6 hours. In future, this policy will be configurable through a well-defined interface.

2. Decrease Replication Factor


When the replication factor of a file is reduced, the Namenode selects excess replicas that can be
deleted. The next Heartbeat transfers this information to the Datanode. The Datanode then removes
the corresponding blocks and the corresponding free space appears in the cluster. The point to note
here is that there might be a time delay between the completion of the setReplication API and the
appearance of free space in the cluster.

Running MapReduce Examples


Locate the example file using below command
$ find / -name "hadoop-mapreduce-examples*.jar" -print
Listing Available Examples
$ yarn jar $HADOOP_EXAMPLES/hadoop-mapreduce-examples.jar
Running the Pi Example
The pi example calculates the digits of p using a quasi-Monte Carlo method. To run the pi example
with 16 maps and 1,000,000 samples per map, enter the following command:
$ yarn jar $HADOOP_EXAMPLES/hadoop-mapreduce-examples.jar pi 16 1000000

Running Basic Hadoop Benchmarks


Many Hadoop benchmarks can provide insight into cluster performance. The best benchmarks are
always those that reflect real application performance. The terasort benchmarks is discussed in this
section.

Running the Terasort Test


The terasort benchmark sorts a specified amount of randomly generated data. This benchmark
provides combined testing of the HDFS and MapReduce layers of a Hadoop cluster. A full terasort
benchmark run consists of the following three steps:
1. Generating the input data via teragen program.
2. Running the actual terasort benchmark on the input data.
3. Validating the sorted output data via the teravalidate program.
In general, each row is 100 bytes long; thus the total amount of data written is 100 times the
number of rows specified as part of the benchmark (i.e., to write 100GB of data, use 1 billion
rows). The input and output directories need to be specified in HDFS. The following sequence of
commands will run the benchmark for 50GB of data as user hdfs.
1. Run teragen to generate rows of random data to sort.
$ yarn jar $HADOOP_EXAMPLES/hadoop-mapreduce-examples.jar teragen 500000000
➥/user/hdfs/TeraGen-50GB
2. Run terasort to sort the database.

9
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

$ yarn jar $HADOOP_EXAMPLES/hadoop-mapreduce-examples.jar terasort


➥/user/hdfs/TeraGen-50GB /user/hdfs/TeraSort-50GB
3. Run teravalidate to validate the sort.
$ yarn jar $HADOOP_EXAMPLES/hadoop-mapreduce-examples.jar teravalidate
➥/user/hdfs/TeraSort-50GB /user/hdfs/TeraValid-50GB
To report results, the time for the actual sort (terasort) is measured and the benchmark rate in
megabytes/second (MB/s) is calculated. For best performance, the actual terasort benchmark
should be run with a replication factor of 1. In addition, the default number of terasort reducer
tasks is set to 1. Increasing the number of reducers often helps with benchmark performance. For
example, the following command will instruct terasort to use four reducer tasks:
$ yarn jar $HADOOP_EXAMPLES/hadoop-mapreduce-examples.jar terasort
➥ -Dmapred.reduce.tasks=4 /user/hdfs/TeraGen-50GB /user/hdfs/TeraSort-50GB
The following command will perform the cleanup for the previous example:
$ hdfs dfs -rm -r -skipTrash Tera*

Hadoop MapReduce Framework

Hadoop MapReduce is a programming paradigm at the heart of Apache Hadoop for providing
massive scalability across hundreds or thousands of Hadoop clusters on commodity hardware. The
MapReduce model processes large unstructured data sets with a distributed algorithm on a Hadoop
cluster.
The term MapReduce represents two separate and distinct tasks Hadoop programs perform-Map
Job and Reduce Job. Map job scales takes data sets as input and processes them to produce key
value pairs. Reduce job takes the output of the Map job i.e. the key value pairs and aggregates
them to produce desired results. The input and output of the map and reduce jobs are stored in
HDFS.

Fig 1.2 MapReduce framework

Bear, Deer, River and Car Example

10
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

The following word count example explains MapReduce method. For simplicity, let's consider a
few words of a text document. We want to find the number of occurrence of each word. First the
input is split to distribute the work among all the map nodes as shown in the figure. Then each
word is identified and mapped to the number one. Thus the pairs also called as tuples are created.
In the first mapper node three words Deer, Bear and River are passed. Thus the output of the node
will be three key, value pairs with three distinct keys and value set to one. The mapping process
remains the same in all the nodes. These tuples are then passed to the reduce nodes. A partitioner
comes into action which carries out shuffling so that all the tuples with same key are sent to same
node.

Fig 1.3 Map reduce example


The Reducer node processes all the tuples such that all the pairs with same key are counted and the
count is updated as the value of that specific key. In the example there are two pairs with the key
‗Bear‘ which are then reduced to single tuple with the value equal to the count. All the output
tuples are then collected and written in the output file.

MapReduce Programming: Compiling and Running Hadoop wordcount example

Compiling the WordCount program


The WordCount program resides inside the WordCount folder. 2 The folder is composed of the
following files:
• WordCountMapper.java. Contains the map function implementation.
• WordCountReducer.java. Contains the reduce function implementation.
• WordCount.java. Contains the code coordinating the execution of the map and reduce functions.
Inside order to compile the WordCount program, execute the following commands in the
WordCount folder:
WordCount J$ javac -cp hadoop-core-1.0.4.jar *.java
WordCount J$ jar cvf WordCount.jar *.class

11
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

The first command compiles the program using the classes developed by Hadoop (i.e., hadoop-
core-1.0.4.jar). The second command creates a jar file called WordCount.jar that you will use for
running the WordCount program in Hadoop

Running the WordCount program in Hadoop


Assuming that you are in the folder containing your Hadoop installation, execute the following
commands
hadoop J$ bin/start-all.sh
hadoop J$ ssh localhost
hadoop J$ mkdir input

The first command starts the Hadoop services. The second command establishes a secure
connection with your machine. The third command creates the directory where you will put file
containing The Miserables.
Afterwards, copy the WordCount.jar and the TheMiserables.txt file into the folder containing your
Hadoop installation.
Then prepare the input for the WordCount program:
hadoop J$ bin/hadoop dfs -mkdir input
hadoop J$ bin/hadoop dfs -put LesMiserables.txt input
The former command creates a directory called input in the Hadoop Distributed File System
(HDFS). The second command will copy TheMiserables.txt into the input folder in HDFS.
Without this command Hadoop cannot find the input file. Finally execute the following
commands:
hadoop J$ bin/hadoop jar WordCount.jar WordCount input output
hadoop J$ bin/hadoop dfs -get output output
The first command run the WordCount program in Hadoop. Note that the command specifies the
names of:
• the class where the main method resides (cf. the WordCount.java file).
• the HDFS folder where the input files resides.
• the HDFS folder that will contain the output files.
The second command copies the output folder from HDFS to your machine. You will find the
result of the WordCount program in a file (probably) called part-00000.

12
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

Module-2
Essential Hadoop Tools
• The Pig scripting tool is introduced as a way to quickly examine data both locally and on a
Hadoop cluster.
• The Hive SQL-like query tool is explained using two examples.
• The Sqoop RDBMS tool is used to import and export data from MySQL to/from HDFS.
• The Flume streaming data transport utility is configured to capture weblog data into HDFS.
• The Oozie workflow manager is used to run basic and complex Hadoop workflows.
• The distributed HBase database is used to store and access data on a Hadoop cluster.

The Hadoop ecosystem offers many tools to help with data input, high-level processing, workflow
management, and creation of huge databases. Hadoop Ecosystem is neither a programming
language nor a service, it is a platform or framework which solves big data problems. You can
consider it as a suite which encompasses a number of services (ingesting, storing, analyzing and
maintaining) inside it.

Fig 2.1: Hadoop Ecosystem

USING APACHE PIG Tools

• Apache Pig is a high-level language that enables programmers to write complex


MapReduce transformations using a simple scripting language. PIG has two parts: Pig
Latin, the language and the pig runtime, for the execution environment. It supports pig
latin language, which has SQL like command structure.

13
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

10 line of pig latin = approx. 200 lines of Map-Reduce Java code

The compiler internally converts pig latin to MapReduce. It produces a sequential set of
MapReduce jobs, and that‘s an abstraction (which works like black box). PIG was initially
developed by Yahoo. It gives you a platform for building data flow for ETL (Extract, Transform
and Load), processing and analyzing huge data sets. In PIG, first the load command, loads the
data. Then we perform various functions on it like grouping, filtering, joining, sorting, etc. At last,
either you can dump the data on the screen or you can store the result back in HDFS

Apache Pig has several usage modes. The first is a local mode in which all processing is done on
the local machine. The non-local (cluster) modes are MapReduce and Tez. These modes execute
the job on the cluster using either the MapReduce engine or the optimized Tez engine. There are
also interactive and batch modes available; they enable Pig applications to be developed locally in
interactive modes, using small amounts of data, and then run at scale on the cluster in a production
mode.

USING APACHE HIVE

Facebook created HIVE for people who are fluent with SQL. Thus, HIVE makes them feel at home
while working in a Hadoop Ecosystem. Basically, HIVE is a data warehousing component which
performs reading, writing and managing large data sets in a distributed environment using SQL-
like interface.

HIVE + SQL = HQL

The query language of Hive is called Hive Query Language(HQL), which is very similar like SQL.
It has 2 basic components: Hive Command Line and JDBC/ODBC driver. The Hive Command
line interface is used to execute HQL commands. While, Java Database Connectivity (JDBC) and
Object Database Connectivity (ODBC) is used to establish connection from data storage.

Secondly, Hive is highly scalable. As, it can serve both the purposes, i.e. large data set processing
(i.e. Batch query processing) and real time processing (i.e. Interactive query processing). It
supports all primitive data types of SQL. You can use predefined functions, or write tailored user
defined functions (UDF) also to accomplish your specific needs.

USING APACHE SQOOP TO ACQUIRE RELATIONAL DATA

Sqoop is a tool designed to transfer data between Hadoop and relational databases. You can use
Sqoop to import data from a relational database management system (RDBMS) into the Hadoop
Distributed File System (HDFS), transform the data in Hadoop, and then export the data back into
an RDBMS.

14
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

Sqoop can be used with any Java Database Connectivity (JDBC)–compliant database and has been
tested on Microsoft SQL Server, PostgresSQL, MySQL, and Oracle

When we submit Sqoop command, our main task gets divided into sub tasks which is handled by
individual Map Task internally. Map Task is the sub task, which imports part of data to the Hadoop
Ecosystem. Collectively, all Map tasks imports the whole data

Fig 2.2: Sqoop WorkFlow

Export also works in a similar manner.

When we submit our Job, it is mapped into Map Tasks which brings the chunk of data from
HDFS. These chunks are exported to a structured data destination. Combining all these exported
chunks of data, we receive the whole data at the destination, which in most of the cases is an
RDBMS (MYSQL/Oracle/SQL Server).

APACHE SOLR & LUCENE

Apache Solr and Apache Lucene are the two services which are used for searching and indexing in
Hadoop Ecosystem.

• Apache Lucene is based on Java, which also helps in spell checking.


• If Apache Lucene is the engine, Apache Solr is the car built around it. Solr is a complete
application built around Lucene.
• It uses the Lucene Java search library as a core for search and full indexing.

15
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

APACHE AMBARI

Ambari is an Apache Software Foundation Project which aims at making Hadoop ecosystem more
manageable. It includes software for provisioning, managing and monitoringApache Hadoop
clusters.

The Ambari provides:


1. Hadoop cluster provisioning:
▪ It gives us step by step process for installing Hadoop services across a number of
hosts.
▪ It also handles configuration of Hadoop services over a cluster.
2. Hadoop cluster management:
▪ It provides a central management service for starting, stopping and re-configuring
Hadoop services across the cluster.
3. Hadoop cluster monitoring:
▪ For monitoring health and status, Ambari provides us a dashboard.
▪ The Amber Alert framework is an alerting service which notifies the user,
whenever the attention is needed. For example, if a node goes down or low disk
space on a node, etc.

USING APACHE FLUME TO ACQUIRE DATA STREAMS

Apache Flume is an independent agent designed to collect, transport, and store data into HDFS.
Often data transport involves a number of Flume agents that may traverse a series of machines and
locations. Flume is often used for log files, social media-generated data, email messages, and just
about any continuous data source.
As shown in Figure 2.3, a Flume agent is composed of three components.

Fig 2.3. Flume agent with source, channel, and sink

16
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

• Source. The source component receives data and sends it to a channel. It can send the data
to more than one channel. The input data can be from a real-time source (e.g., weblog) or
another Flume agent.
• Channel. A channel is a data queue that forwards the source data to the sink destination. It
can be thought of as a buffer that manages input (source) and output (sink) flow rates.
• Sink. The sink delivers data to destination such as HDFS, a local file, or another Flume
agent.
A Flume agent must have all three of these components defined. A Flume agent can have several
sources, channels, and sinks. Sources can write to multiple channels, but a sink can take data from
only a single channel. Data written to a channel remain in the channel until a sink removes the
data. By default, the data in a channel are kept in memory but may be optionally stored on disk to
prevent data loss in the event of a network failure.

MANAGE HADOOP WORKFLOWS WITH APACHE OOZIE


Oozie is a workflow director system designed to run and manage multiple related Apache Hadoop
jobs. For instance, complete data input and analysis may require several discrete Hadoop jobs to be
run as a workflow in which the output of one job serves as the input for a successive job. Oozie is
designed to construct and manage these workflows. Oozie is not a substitute for the YARN
scheduler. That is, YARN manages resources for individual Hadoop jobs, and Oozie provides a
way to connect and control Hadoop jobs on the cluster.
Oozie workflow jobs are represented as directed acyclic graphs (DAGs) of actions. (DAGs are
basically graphs that cannot have directed loops.) Three types of Oozie jobs are permitted:
• Workflow—a specified sequence of Hadoop jobs with outcome-based decision points and
control dependency. Progress from one action to another cannot happen until the first action
is complete.
• Coordinator—a scheduled workflow job that can run at various time intervals or when data
become available.
• Bundle—a higher-level Oozie abstraction that will batch a set of coordinator jobs.
Oozie is integrated with the rest of the Hadoop stack, supporting several types of Hadoop jobs out
of the box (e.g., Java MapReduce, Streaming MapReduce, Pig, Hive, and Sqoop) as well as
system-specific jobs (e.g., Java programs and shell scripts). Oozie also provides a CLI and a web
UI for monitoring jobs.
Figure 2.4 depicts a simple Oozie workflow. In this case, Oozie runs a basic MapReduce operation.
If the application was successful, the job ends; if an error occurred, the job is killed.

17
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

Fig 2.4. A simple Oozie DAG workflow


Oozie workflow definitions are written in hPDL (an XML Process Definition Language). Such
workflows contain several types of nodes:
• Control flow nodes define the beginning and the end of a workflow. They include start,
end, and optional fail nodes.
• Action nodes are where the actual processing tasks are defined. When an action node
finishes, the remote systems notify Oozie and the next node in the workflow is executed.
Action nodes can also include HDFS commands.
• Fork/join nodes enable parallel execution of tasks in the workflow. The fork node enables
two or more tasks to run at the same time. A join node represents a rendezvous point that
must wait until all forked tasks complete.
• Control flow nodes enable decisions to be made about the previous task. Control decisions
are based on the results of the previous action (e.g., file size or file existence). Decision
nodes are essentially switch-case statements that use JSP EL (Java Server Pages—
Expression Language) that evaluate to either true or false.
Figure 2.5 depicts a more complex workflow that uses all of these node types.

Fig 2.5. A more complex Oozie DAG workflow

18
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

USING APACHE HBASE


• HBase is an open source, non-relational distributed database. In other words, it is a NoSQL
database.
• It supports all types of data and that is why, it‘s capable of handling anything and
everything inside a Hadoop ecosystem.
• It is modelled after Google‘s BigTable, which is a distributed storage system designed to
cope up with large data sets.
• The HBase was designed to run on top of HDFS and provides BigTable like capabilities.
• It gives us a fault tolerant way of storing sparse data, which is common in most Big Data
use cases.
• The HBase is written in Java, whereas HBase applications can be written in REST, Avro
and Thrift APIs.

Specific HBase cell values are identified by a row key, column (column family and column), and
version (timestamp). It is possible to have many versions of data within an HBase cell. A version is
specified as a timestamp and is created each time data are written to a cell. Almost anything can
serve as a row key, from strings to binary representations of longs to serialized data structures.
Rows are lexicographically sorted with the lowest order appearing first in a table. The empty byte
array denotes both the start and the end of a table‘s namespace. All table accesses are via the table
row key, which is considered its primary key.

Hadoop YARN Applications

YARN DISTRIBUTED-SHELL
The Hadoop YARN project includes the Distributed-Shell application, which is an example
of a Hadoop non-MapReduce application built on top of YARN. Distributed-Shell is a simple
mechanism for running shell commands and scripts in containers on multiple nodes in a Hadoop
cluster.
The central YARN ResourceManager runs as a scheduling daemon on a dedicated machine
and acts as the central authority for allocating resources to the various competing applications in
the cluster. The ResourceManager has a central and global view of all cluster resources and,
therefore, can ensure fairness, capacity, and locality are shared across all users. Depending on the
application demand, scheduling priorities, and resource availability, the ResourceManager
dynamically allocates resource containers to applications to run on particular nodes. A container is
a logical bundle of resources (e.g., memory, cores) bound to a particular cluster node. To enforce
and track such assignments, the ResourceManager interacts with a special system daemon running
on each node called the NodeManager. Communications between the ResourceManager and
NodeManagers are heartbeat based for scalability. NodeManagers are responsible for local
monitoring of resource availability, fault reporting, and container life-cycle management (e.g.,

19
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

starting and killing jobs). The ResourceManager depends on the NodeManagers for its ―global
view‖ of the cluster.
User applications are submitted to the ResourceManager via a public protocol and go
through anadmission control phase during which security credentials are validated and various
operational and administrative checks are performed. Those applications that are accepted pass to
the scheduler and are allowed to run. Once the scheduler has enough resources to satisfy the
request, the application is moved from an accepted state to a running state. Aside from internal
bookkeeping, this process involves allocating a container for the single ApplicationMaster and
spawning it on a node in the cluster. Often called container 0, the ApplicationMaster does not have
any additional resources at this point, but rather must request additional resources from the
ResourceManager.
The ApplicationMaster is the ―master‖ user job that manages all application life-cycle
aspects, including dynamically increasing and decreasing resource consumption (i.e., containers),
managing the flow of execution (e.g., in case of MapReduce jobs, running reducers against the
output of maps), handling faults and computation skew, and performing other local optimizations.
The ApplicationMaster is designed to run arbitrary user code that can be written in any
programming language, as all communication with the ResourceManager and NodeManager is
encoded using extensible network protocols
The ApplicationMaster will need to harness the processing power of multiple servers to
complete a job. To achieve this, the ApplicationMaster issues resource requests to the
ResourceManager. The form of these requests includes specification of locality preferences (e.g.,
to accommodate HDFS use) and properties of the containers. The ResourceManager will attempt to
satisfy the resource requests coming from each application according to availability and scheduling
policies. When a resource is scheduled on behalf of an ApplicationMaster, the ResourceManager
generates a lease for the resource, which is acquired by a subsequent ApplicationMaster heartbeat.
The ApplicationMaster then works with the NodeManagers to start the resource. A token-based
security mechanism guarantees its authenticity when the ApplicationMaster presents the container
lease to the NodeManager. In a typical situation, running containers will communicate with the
ApplicationMaster through an application-specific protocol to report status and health information
and to receive framework-specific commands. In this way, YARN provides a basic infrastructure
for monitoring and life-cycle management of containers, while each framework manages
application-specific semantics independently.
The YARN components appear as the large outer boxes (ResourceManager and
NodeManagers), and the two applications appear as smaller boxes (containers), one dark and one
light. Each application uses a different ApplicationMaster; the darker client is running a Message
Passing Interface (MPI) application and the lighter client is running a traditional MapReduce
application.

20
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

Fig 2.6 YARN architecture with two clients (MapReduce and MPI).

YARN APPLICATION FRAMEWORKS


YARN presents a resource management platform, which provides services such as scheduling,
fault monitoring, data locality, and more to MapReduce and other frameworks. Figure 7 illustrates
some of the various frameworks that will run under YARN. Note that the Hadoop version 1
applications (e.g., Pig and Hive) run under the MapReduce framework.

Fig 2.7 Example of the Hadoop version 2 ecosystem.

21
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

Distributed-Shell
As described earlier in this chapter, Distributed-Shell is an example application included with the
Hadoop core components that demonstrates how to write applications on top of YARN. It provides
a simple method for running shell commands and scripts in containers in parallel on a Hadoop
YARN cluster.

Hadoop MapReduce
MapReduce was the first YARN framework and drove many of YARN‘s requirements. It is
integrated tightly with the rest of the Hadoop ecosystem projects, such as Apache Pig, Apache
Hive, and Apache Oozie.

Apache Tez
One great example of a new YARN framework is Apache Tez. Many Hadoop jobs involve the
execution of a complex directed acyclic graph (DAG) of tasks using separate MapReduce stages.
Apache Tez generalizes this process and enables these tasks to be spread across stages so that they
can be run as a single, all-encompassing job. Tez can be used as a MapReduce replacement for
projects such as Apache Hive and Apache Pig. No changes are needed to the Hive or Pig
applications.

Apache Giraph
Apache Giraph is an iterative graph processing system built for high scalability. Facebook, Twitter,
and LinkedIn use it to create social graphs of users. Giraph was originally written to run on
standard Hadoop V1 using the MapReduce framework, but that approach proved inefficient and
totally unnatural for various reasons.. In addition, using the flexibility of YARN, the Giraph
developers plan on implementing their own web interface to monitor job progress.

Hoya: HBase on YARN


The Hoya project creates dynamic and elastic Apache HBase clusters on top of YARN. A client
application creates the persistent configuration files, sets up the HBase cluster XML files, and then
asks YARN to create an ApplicationMaster. YARN copies all files listed in the client‘s
application-launch request from HDFS into the local file system of the chosen server, and then
executes the command to start the Hoya ApplicationMaster. Hoya also asks YARN for the number
of containers matching the number of HBase region servers it needs.

Apache Spark
Spark was initially developed for applications in which keeping data in memory improves
performance, such as iterative algorithms, which are common in machine learning, and interactive
data mining. Spark differs from classic MapReduce in two important ways. First, Spark holds

22
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

intermediate results in memory, rather than writing them to disk. Second, Spark supports more than
just MapReduce functions; that is, it greatly expands the set of possible analyses that can be
executed over HDFS data stores. It also provides APIs in Scala, Java, and Python.
Since 2013, Spark has been running on production YARN clusters at Yahoo!. The advantage of
porting and running Spark on top of YARN is the common resource management and a single
underlying file system

Apache Storm
Traditional MapReduce jobs are expected to eventually finish, but Apache Storm continuously
processes messages until it is stopped. This framework is designed to process unbounded streams
of data in real time. It can be used in any programming language. The basic Storm use-cases
include real-time analytics, online machine learning, continuous computation, distributed RPC
(remote procedure calls), ETL (extract, transform, and load), and more. Storm provides fast
performance, is scalable, is fault tolerant, and provides processing guarantees. It works directly
under YARN and takes advantage of the common data and resource management substrate.

Apache REEF: Retainable Evaluator Execution Framework


YARN‘s flexibility sometimes requires significant effort on the part of application implementers.
The steps involved in writing a custom application on YARN include building your own
ApplicationMaster, performing client and container management, and handling aspects of fault
tolerance, execution flow, coordination, and other concerns. The REEF project by Microsoft
recognizes this challenge and factors out several components that are common to many
applications, such as storage management, data caching, fault detection, and checkpoints.
Framework designers can build their applications on top of REEF more easily than they can build
those same applications directly on YARN, and can reuse these common services/libraries. REEF‘s
design makes it suitable for both MapReduce and DAG-like executions as well as iterative and
interactive computations.

Hamster: Hadoop and MPI on the Same Cluster


The Message Passing Interface (MPI) is widely used in high-performance computing (HPC). MPI
is primarily a set of optimized message-passing library calls for C, C++, and Fortran that operate
over popular server interconnects such as Ethernet and InfiniBand. Because users have full control
over their YARN containers, there is no reason why MPI applications cannot run within a Hadoop
cluster. The Hamster effort is a work-in-progress that provides a good discussion of the issues
involved in mapping MPI to a YARN cluster.

Apache Flink: Scalable Batch and Stream Data Processing


Apache Flink is a platform for efficient, distributed, general-purpose data processing. It features
powerful programming abstractions in Java and Scala, a high-performance run time, and automatic

23
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

program optimization. It also offers native support for iterations, incremental iterations, and
programs consisting of large DAGs of operations.
Flink is primarily a stream-processing framework that can look like a batch-processing
environment. The immediate benefit from this approach is the ability to use the same algorithms
for both streaming and batch modes (exactly as is done in Apache Spark). However, Flink can
provide low-latency similar to that found in Apache Storm, but which is not available in Apache
Spark. In addition, Flink has its own memory management system, separate from Java‘s garbage
collector. By managing memory explicitly, Flink almost eliminates the memory spikes often seen
on Spark clusters.

Apache Slider: Dynamic Application Management


Apache Slider (incubating) is a YARN application to deploy existing distributed applications on
YARN, monitor them, and make them larger or smaller as desired in real time.
Applications can be stopped and then started; the distribution of the deployed application across
the YARN cluster is persistent and allows for best-effort placement close to the previous locations.
Applications that remember the previous placement of data (such as HBase) can exhibit fast startup
times by capitalizing on this feature.
YARN monitors the health of ―YARN containers‖ that are hosting parts of the deployed
applications. If a container fails, the Slider manager is notified. Slider then requests a new
replacement container from the YARN ResourceManager. Some of Slider‘s other features include
user creation of on-demand applications, the ability to stop and restart applications as needed
(preemption), and the ability to expand or reduce the number of application containers as needed.
The Slider tool is a Java command-line application.

Basic Hadoop Administration Procedures

Hadoop has two main areas of administration: the YARN resource manager and the HDFS file
system. Other application frameworks (e.g., the MapReduce framework) and tools have their own
management files. Hadoop configuration is accomplished through the use of XML configuration
files. The basic files and their function are as follows:
core-default.xml: System-wide properties
hdfs-default.xml: Hadoop Distributed File System properties
mapred-default.xml: Properties for the YARN MapReduce framework
yarn-default.xml: YARN properties

BASIC HADOOP YARN ADMINISTRATION

24
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

YARN has several built-in administrative features and commands. The main administration
command is yarn rmadmin (resource manager administration). Enter yarn rmadmin -help to learn
more about the various options.

Decommissioning YARN Nodes


If a NodeManager host/node needs to be removed from the cluster, it should be decommissioned
first. Assuming the node is responding, you can easily decommission it from the Ambari web UI.
Simply go to the Hosts view, click on the host, and select Decommission from the pull-down menu
next to the NodeManager component. Note that the host may also be acting as a HDFS DataNode.
Use the Ambari Hosts view to decommission the HDFS host in a similar fashion.

YARN WebProxy
The Web Application Proxy is a separate proxy server in YARN that addresses security issues with
the cluster web interface on ApplicationMasters. By default, the proxy runs as part of the Resource
Manager itself, but it can be configured to run in a stand-alone mode by adding the configuration
property yarn.web-proxy.address to yarn-site.xml. (Using Ambari, go to the YARN Configs view,
scroll to the bottom, and select Custom yarn-site.xml/Add property.) In stand-alone
mode, yarn.web-proxy.principal and yarn.web-proxy.keytab control the Kerberos principal name
and the corresponding keytab, respectively, for use in secure mode. These elements can be added
to the yarn-site.xml if required.

Using the JobHistoryServer


The removal of the JobTracker and migration of MapReduce from a system to an application-level
framework necessitated creation of a place to store MapReduce job history. The JobHistoryServer
provides all YARN MapReduce applications with a central location in which to aggregate
completed jobs for historical reference and debugging. The settings for the JobHistoryServer can
be found in the mapred-site.xml file.

Managing YARN Jobs


YARN jobs can be managed using the yarn application command. The following options,
including -kill, -list, and -status, are available to the administrator with this command. MapReduce
jobs can also be controlled with the mapred job command.

Setting Container Memory


YARN manages application resource containers over the entire cluster. Controlling the amount of
container memory takes place through three important values in the yarn-site.xml file:
yarn.nodemanager.resource.memory-mb is the amount of memory the NodeManager can use for
containers.

25
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

scheduler.minimum-allocation-mb is the smallest container allowed by the ResourceManager. A


requested container smaller than this value will result in an allocated container of this size (default
1024MB).
yarn.scheduler.maximum-allocation-mb is the largest container allowed by the ResourceManager
(default 8192MB).

Setting Container Cores


You can set the number of cores for containers using the following properties in the yarn-stie.xml:
yarn.scheduler.minimum-allocation-vcores: The minimum allocation for every container request
at the ResourceManager, in terms of virtual CPU cores. Requests smaller than this allocation will
not take effect, and the specified value will be allocated the minimum number of cores. The default
is 1 core.
yarn.scheduler.maximum-allocation-vcores: The maximum allocation for every container request
at the ResourceManager, in terms of virtual CPU cores. Requests larger than this allocation will
not take effect, and the number of cores will be capped at this value. The default is 32.
yarn.nodemanager.resource.cpu-vcores: The number of CPU cores that can be allocated for
containers. The default is 8.

Setting MapReduce Properties


As noted throughout this book, MapReduce now runs as a YARN application. Consequently, it
may be necessary to adjust some of the mapred-site.xml properties as they relate to the map and
reduce containers. The following properties are used to set some Java arguments and memory size
for both the map and reduce containers:
mapred.child.java.opts provides a larger or smaller heap size for child JVMs of maps (e.g., --
Xmx2048m).
mapreduce.map.memory.mb provides a larger or smaller resource limit for maps (default =
1536MB).
mapreduce.reduce.memory.mb provides a larger heap size for child JVMs of maps (default =
3072MB).
mapreduce.reduce.java.opts provides a larger or smaller heap size for child reducers.

BASIC HDFS ADMINISTRATION


The following section covers some basic administration aspects of HDFS.

The NameNode User Interface


Monitoring HDFS can be done in several ways. One of the more convenient ways to get a quick
view of HDFS status is through the NameNode user interface. This web-based tool provides

26
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

essential information about HDFS and offers the capability to browse the HDFS namespace and
logs.
The web-based UI can be started from within Ambari or from a web browser connected to the
NameNode. In Ambari, simply select the HDFS service window and click on the Quick Links pull-
down menu in the top middle of the page. Select NameNode UI. A new browser tab will open with
the UI shown. You can also start the UI directly by entering the following command
$ firefox http://localhost:50070
There are five tabs on the UI: Overview, Datanodes, Snapshot, Startup Progress, and Utilities.
The Overview page provides much of the essential information that the command-line tools also
offer, but in a much easier-to-read format. The Datanodes tab displays node information. The
Snapshot window lists the ―snapshottable‖ directories and the snapshots.
In NameNode startup progress view, when the NameNode starts, it reads the previous file system
image file (fsimage); applies any new edits to the file system image, thereby creating a new file
system image; and drops into safe mode until enough DataNodes come online. This progress is
shown in real time in the UI as the NameNode starts. Completed phases are displayed in bold text.
The currently running phase is displayed in italics. Phases that have not yet begun are displayed in
gray text.
The Utilities menu offers two options. The first, is a file system browser. From this window, you
can easily explore the HDFS namespace. The second option, links to the various NameNode logs.

Adding Users to HDFS


1. Add the user to the group for your operating system on the HDFS client system. In most cases,
the groupname should be that of the HDFS superuser, which is often hadoop or hdfs.
useradd -G <groupname> <username>
2. Create the username directory in HDFS.
hdfs dfs -mkdir /user/<username>
3. Give that account ownership over its directory in HDFS.
hdfs dfs -chown <username>:<groupname> /user/<username>
Balancing HDFS
Based on usage patterns and DataNode availability, the number of data blocks across the
DataNodes may become unbalanced. To avoid over-utilized DataNodes, the HDFS balancer tool
rebalances data blocks across the available DataNodes. Data blocks are moved from over-utilized
to under-utilized nodes to within a certain percent threshold. Rebalancing can be done when new
DataNodes are added or when a DataNode is removed from service. This step does not create more
space in HDFS, but rather improves efficiency.
The HDFS superuser must run the balancer. The simplest way to run the balancer is to enter the
following command:
$ hdfs balancer

27
"BIG DATA ANALYTICS"
(15CS82 CBCS as per VTU Syllabus)

By default, the balancer will continue to rebalance the nodes until the number of data blocks on all
DataNodes are within 10% of each other. The balancer can be stopped, without harming HDFS, at
any time by entering a Ctrl-C. Lower or higher thresholds can be set using the -threshold argument.
For example, giving the following command sets a 5% threshold:
$ hdfs balancer -threshold 5

HDFS Safe Mode


When the NameNode starts, it loads the file system state from the fsimage and then applies the
edits log file. It then waits for DataNodes to report their blocks. During this time, the NameNode
stays in a read-only Safe Mode. The NameNode leaves Safe Mode automatically after the
DataNodes have reported that most file system blocks are available.
The administrator can place HDFS in Safe Mode by giving the following command:
$ hdfs dfsadmin -safemode enter
Entering the following command turns off Safe Mode:
$ hdfs dfsadmin -safemode leave
HDFS may drop into Safe Mode if a major issue arises within the file system (e.g., a full
DataNode). The file system will not leave Safe Mode until the situation is resolved. To check
whether HDFS is in Safe Mode, enter the following command:
$ hdfs dfsadmin -safemode get

SecondaryNameNode
To avoid long NameNode restarts and other issues, the performance of the SecondaryNameNode
should be verified. The hdfs-site.xml defines a property called fs.checkpoint.period (called HDFS
Maximum Checkpoint Delay in Ambari). This property provides the time in seconds between the
SecondaryNameNode checkpoints.
When a checkpoint occurs, a new fsimage* file is created in the directory corresponding to the
value of dfs.namenode.checkpoint.dir in the hdfs-site.xml file. This file is also placed in the
NameNode directory corresponding to the dfs.namenode.name.dir path designated in the hdfs-
site.xml file. To test the checkpoint process, a short time period (e.g., 300 seconds) can be used
for fs.checkpoint.period and HDFS restarted. After five minutes, two identical fsimage* files
should be present in each of the two previously mentioned directories. If these files are not recent
or are missing, consult the NameNode and SecondaryNameNode logs.
Once the SecondaryNameNode process is confirmed to be working correctly, reset
the fs.checkpoint.period to the previous value and restart HDFS. (Ambari versioning is helpful
with this type or procedure.) If the SecondaryNameNode is not running, a checkpoint can be forced
by running the following command:
$ hdfs secondarynamenode -checkpoint force

28
29
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner

Você também pode gostar