Monday, 12 May 2014

SQOOP the RDBMS recently Inserted/Updated records(Incremental Import) into HBASE and schedule it with OOZIE coordinator



We come to know how to flume the user activities in to the hadoop cluster in the first part here.

On top of this activities we will do some analysis and found the result. For example if a user wants to buy a mobile in the shopping site and he ended up with null for the day, we got all his activities in to Hadoop cluster and do analysis to find which mobile he looked for more times. And the result in Hadoop cluster has only mobile name and you don’t have more information about that mobile in your cluster. 

This information is standard and transactional which was maintained  in the RDBMS.We need to do join the RDBMS data with our hadoop cluster analysis result to send the information to the Recommendations tables of RDBMS in order to  recommend the user. Here we have two options to perform Joins.

1)      You have to send the result of your cluster to RDBMS and do Joins there.
2)      Get the RDBMS data into Hadoop cluster to perform join in parallel distributed passion.

Both can be done by a Map-Only Jobs tool called SQOOP (SQl to hadOOP).
In this article we will see how to sqoop the RDBMS table in to the Hadoop Real time Database HBASE in incremental passion.

Many of them have a question like as Hadoop is batch oriented, then how would hadoop can get the most recently updated data in to the cluster (like real-time).For example, If the Mobile Vendor has increased the price of the mobile in RDBMS it has to get in to hadoop cluster within 10 Minutes to make my recommendations more real. We will answer the question in this blog.

Step1) Make ready your RDBMS and NOSQL databases.

Open RDBMS database (Mysql) and see the table ITEMS which is tied to the web application where product team has authority over this table. Below is the table.
Create database dbsit and in this database create table ITEMS.
use dbsit;
create table ITEMS(id  int  not  null primary  key auto_increment,phone_name  varchar(64)  not null,model_name  varchar(10)  not  null,price  decimal(10,2),memory_card_size  varchar(8),mega_pixel varchar(10),color   varchar(10),Date_Item  DATE);




Open HBASE shell and create a table PRODUCT with column family as PHONE. Issue count to find the number of records.


Step 2) Run a Normal Sqoop import to get the ITEMS data of RDBMS into HBASE Product table.

bin/sqoop import --connect jdbc:mysql://localhost/dbsit --table ITEMS --hbase-table PRODUCT --column-family PHONE
Now go to your hbase shell and see the records of HBASE how it was distributed into column family. Your output looks like as below screen.



Step 3) Get a newly inserted record into HBASE from RDBMS.

Now your data is in HBASE table. Your sales are increasing and getting good response. As a result your got another phone vendor to your company. Then your product team has added another record in to ITEMS table of RDBMS.
Below insert will happen from web screen of your project. For convenient purpose I am doing from database.

Go to mysql >

insert into ITEMS values (9,'NOKIA','LUMIA_920',278,'32GB','8MP','BLACK','2014-05-11');



So, new record got inserted into your RDBMS.Then here is a question how do we get the newly added records into your HBASE table? Running the step2 Sqoop command again will get the new record but it will be a performance issue. You need only the newly created record of RDBMS, but the step2 command won’t give good performance, it will import again the 9 records which eats performance of your cluster.

So, inorder to handle the above type of situation, SQOOP gave a concept called Incremental Import. Incremental Import comes in two flavor
1) append (inserted one) 2) Last modified (updated one).
Incremental import in append mode will allow you to transfer only the newly created rows. This saves a considerable amount of resources compared with doing a full import every time you need the data to be in sync.

One disadvantage is the need to know the value of the last imported row so that next time Sqoop can start off where it ended. Sqoop, when running in incremental mode, always prints out the value of the last imported row. This allows you to easily pick up where you left off.

Before issue incremental append command we have to see what is the last value of your HBASE table and value of last id is ‘8’.We will see how to overcome the disadvantage of keeping the last imported row by using metastore.

Go to your sqoop.
bin/sqoop import --connect jdbc:mysql://localhost/dbsit --table ITEMS --hbase-table PRODUCT --column-family PHONE --incremental append --check-column id --last-value 8

Go to your HBASE shell and scan the PRODUCT table. You will see an extra record as 9th record as below. Here we have to tell to the sqoop import the record whose id > 8.We need to see the last record of your table before running the incremental append.




Step 4) Get a recently updated record in to HBASE from your RDBMS.

HTC-ONE mobiles are successfully saled out in the market and that vendor wants to increase the price of the mobile from 450 $ to 480$.HTC-ONE vendor will intimate to update the PRICE of that mobile in our Shopping site.So, our Product team will update the table ITEMS on 12th May 12, 2014 as below.


Now you got update in your RDBMS data. Then in order to make in sync with your analysis data you have to dump the only updated record into your HBASE. This will be done by using Incremental import last modified.

To get the updated record into your Hadoop, there is one necessary condition.It is like the updated record should contain date or time column which got updated by the application.

Go to your HBASE and get the record of HTC_ONE before update.


Go to your sqoop
bin/sqoop import --connect jdbc:mysql://localhost/dbsit  --table ITEMS --hbase-table PRODUCT --column-family PHONE --incremental lastmodified --check-column Date_Item --last-value "2014-05-11"

After finishing the above job go to your HBASE shell and get the updated one as below.



Step 5) How to overcome the remembering of the last value in the incremental import.

From step 3 and step 4, you got recently inserted/updated data in to your hadoop cluster. But the issue with the step3 and step 4 is we have to remember the last value or last modified value. It’s very hard if the data is huge and in production we will have many tables.so, to overcome this, we have a concept called metastore in sqoop which will automatically store the last inserted/updated value in its meta data.

So, we will create a metastore for the step 3.

Before creating a metastore, insert a new record into your RDBMS and get the latest one without the last value by not remembering.
Like, your shopping site got new orders NOKIA LUMIA_820 mobile and added to your list of RDBMS.


We will try to get the recently added record without remembering the last value by creating metastore.

bin/sqoop job --create product_ms -- \
 import --connect jdbc:mysql://localhost/dbsit --table ITEMS --hbase-table PRODUCT --column-family PHONE --incremental append --check-column id --last-value 0

After creating a metastore we have to execute it like as below

bin/sqoop job --exec product_ms

While executing you can see the logs generated by the metastore on the screen and you will find this query  SELECT MIN(`id`), MAX(`id`) FROM `ITEMS` WHERE ( `id` > 0 AND `id` <= 9 ) which automatically got the 10th record.

After job completed successfully go to hbase shell and see the count which you got an extra record whose count shows to 10 from 9.


Now, we will see how our metastore conserve the last –value by using the below command.

bin/sqoop job --show product_ms

Then you will get a screen as below and you found the incremental.last.value =10.By,this way we can avoid remembering the last value concept in our incremental import.




Step 6) Schedule your Metastore job with help of OOZIE coordinator.

You finally come to know how to import the recently inserted/updated records in to HBASE. With this concept you made your cluster data as online data instead of batch.But,here a question like will you going to run the above metastore job every time manually?.

That’s not wise, so we use OOZIE coordinator as a scheduler to execute your sqoop metastore  for every 10 minutes which will import your real-time data (RDBMS) into your Hadoop cluster in incremental way.

bin/oozie job -oozie http://localhost:11000/oozie -config /home/vm4learning/Code/oozie-clickstream-examples/apps/PRODUCT_SQOOP_CO/coordinator.properties –run

Your coordinator.propeties looks like as below.

nameNode=hdfs://localhost:9000
jobTracker=localhost:9001
queueName=default
examplesRoot=oozie-clickstream-examples
examplesRootDir=/user/${user.name}/${examplesRoot}
oozie.use.system.libpath=true
oozie.coord.application.path=${nameNode}/user/${user.name}/${examplesRoot}/apps/PRODUCT_SQOOP_CO

Your coordinator.xml Workflow looks like as below

<coordinator-app name="wf_scheduler" frequency="10" start="2013-10-25T07:40Z" end="2013-10-25T07:45Z" timezone="UTC" xmlns="uri:oozie:coordinator:0.1">
   <action>
      <workflow>
         <app-path>${nameNode}${examplesRootDir}/apps/PRODUCT_SQOOP</app-path>
      </workflow>
   </action>
</coordinator-app>

 The above coordinator will invoke below job.properties.

nameNode=hdfs://localhost:9000
jobTracker=localhost:9001
queueName=default

examplesRoot=oozie-clickstream-examples
examplesRootDir=/user/${user.name}/${examplesRoot}

oozie.use.system.libpath=true

oozie.wf.application.path=${nameNode}/user/${user.name}/${examplesRoot}/apps/PRODUCT_SQOOP


The above job.properties will call below workflow.xml.


<?xml version="1.0" encoding="UTF-8"?>
<workflow-app xmlns="uri:oozie:workflow:0.2" name="sqoop-wf">
    <start to="sqoop-node"/>
    <action name="sqoop-node">
        <sqoop xmlns="uri:oozie:sqoop-action:0.2">
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <prepare>
                <delete path="${nameNode}/${examplesRootDir}/input-data/user"/>
            </prepare>
            <configuration>
                <property>
                    <name>mapred.job.queue.name</name>
                    <value>${queueName}</value>
                </property>
            </configuration>
            <command>job --exec product_ms</command>
        </sqoop>
        <ok to="end"/>
        <error to="fail"/>
    </action>

    <kill name="fail">
        <message>Sqoop failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>
    <end name="end"/>
</workflow-app>


Incremental Import to HDFS is very easy when compared with HBASE.
This is the end of blog and will see more interesting things in our next blogs.










Monday, 5 May 2014

Fluming the User activities in to HBASE/HDFS using AVRO Client.




          Fluming the User activities in to HBASE/HDFS using AVRO Client.



This article is writing with the assumption that you already installed Flume, base and Log4J in your system.

We have a project which will recommend the user based on his activities on the Hosted page in the server.
This project will be written in 4 articles.

In first article we will see how we track the user activities and how we dump in to HDFS or HBASE.
After dumping the data in to hadoop cluster we can do some kind of basket analysis and will project the same to the transaction database for recommendations.

1) Fluming in to HBASE.

Step-1) Log in to Hbase shell -> bin/hbase shell
        Create a table User with activities as column family.

Step-2) Then we need to prepare a flume config (flume-hbaseagent.conf) with Avro as Source and Hbase as sink as below. 

# We have to tell to the hbaseagent what are its sources and sinks.
# hbaseagent which ones we want to activate.
hbaseagent.channels = ch1
hbaseagent.sources = avro-source1
hbaseagent.sinks = sink1

# Define an Avro source called avro-source1 on hbaseagent and tell it
# to bind to 0.0.0.0:41415. Connect it to channel ch1.
hbaseagent.sources.avro-source1.type = avro
hbaseagent.sources.avro-source1.bind = 0.0.0.0
hbaseagent.sources.avro-source1.port = 41415

# Define a memory channel called ch1 on hbaseagent
hbaseagent.channels.ch1.type = memory

#Define a Hbase sink called sink1 on hbaseagent and tell its hbase table and columnFamily

hbaseagent.sinks.sink1.type = org.apache.flume.sink.hbase.HBaseSink
hbaseagent.sinks.sink1.table = user
hbaseagent.sinks.sink1.columnFamily = activites
hbaseagent.sinks.sink1.serializer = org.apache.flume.sink.hbase.SimpleHbaseEventSerializer
hbaseagent.sinks.sink1.serializer.payloadColumn = col1
hbaseagent.sinks.sink1.serializer.keyType = timestamp
hbaseagent.sinks.sink1.serializer.rowPrefix = 1
hbaseagent.sinks.sink1.serializer.suffix = timestamp 

#communicate source and sink with the channel ch1
hbaseagent.sources.avro-source1.channels = ch1

hbaseagent.sinks.sink1.channel = ch1



Step-3) Start Flume with the above config file as:

bin/flume-ng agent --conf ./conf/ -f conf/flume-hbaseagent.conf -Dflume.root.logger=DEBUG,console -n agent1

Above will start the flume and your avro source will start listening at 41415.
If you want to test whether your avro source was listening at 41415.Run the below command then you will see the records of /etc/hosts into your Hbase table.

bin/flume-ng avro-client --conf conf -H localhost -p 41414 -F /etc/hosts  -flume.root.logger=DEBUG,console

Now you can see some records in the user table of Hbase.
Now we will flume the data in to Hbase from a webpage. For this write a java program in eclipse which will log the data of the user activities using LOG4J.

Step-4) Create a project in Eclipse and include all files in the flume lib folder as dependencies.
Create a log4j.propeties file and include this in the SRC folder of your project.

# Define the root logger with appender file
log = /home/vm4learning/WorkSpace/BigData/Log4J-Example/log
log4j.rootLogger = INFO, FILE, flume

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

# Define the flume appender
log4j.appender.flume = org.apache.flume.clients.log4jappender.Log4jAppender
log4j.appender.flume.Hostname = localhost
log4j.appender.flume.Port = 41415
log4j.appender.flume.UnsafeMode = false
log4j.appender.flume.layout=org.apache.log4j.PatternLayout


Here in the config file I am specifying that my java program will write the data in to log.out which was located at  /home/vm4learning/WorkSpace/BigData/Log4J-Example/log.Then this log.out will be taken from AVRO and connect to the flume-hbaseagent.conf which we ran in step-3.

Below is the Java Program.

import java.io.IOException;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class log4jExample {

    static Logger log = Logger.getRootLogger();
             
    public static void main(String[] args) throws IOException, SQLException {
         for (int i=1; i <=10; i++)
             log.info("Apple is:" + i*2);
     log.info("Samsung is:" +i);
    }
}


This will write the information of user activities like the phones he searched for the 10 times in to the log.out which will be flumed in to the HBASE table User for the activities column family.

Step-5) Scan the table user in Hbase and you will find the java program output as activities.
You even do the same above conf of flume with the source as Tail. Specify the log.out in the tail command in flume, this also automatically flumes the data in to HBASE.
Java Program -> Log.out ->specify in the Flume conf as Tail –F ${PATH}/Log.out in the source command.

hbase-agent.sources = tail
hbase-agent.sinks = sink1
hbase-agent.channels = ch1
hbase-agent.sources.tail.type = exec
hbase-agent.sources.tail.command = tail -F /home/vm4learning/tail.log
hbase-agent.sources.tail.channels = ch1
hbase-agent.sinks.sink1.type = org.apache.flume.sink.hbase.HBaseSink
hbase-agent.sinks.sink1.channel = ch1
hbase-agent.sinks.sink1.table = users
hbase-agent.sinks.sink1.columnFamily = activites
hbase-agent.sinks.sink1.serializer = org.apache.flume.sink.hbase.SimpleHbaseEventSerializer
hbase-agent.sinks.sink1.serializer.payloadColumn = col1
hbase-agent.sinks.sink1.serializer.keyType = timestamp
hbase-agent.sinks.sink1.serializer.rowPrefix = 1
hbase-agent.sinks.sink1.serializer.suffix = timestamp

hbase-agent.channels.ch1.type=memory




In the next article we will see how to sqoop the RDBMS table ITEMS in to HBASE table called ITEMS.And will perform some joins on the USER table with the ITEMS table of HBASE in HIVE with the help of HBASE storage Handlers or joins using Phoenix.

And we will prepare incremental load in sqoop to get the latest changed /inserted in the ITEMS table of RDBMS which was tied to the real time application(Web Page).This Incremental load script will be scheduled to run daily in the OOZIE Job.

Please add some ideas to make this more complex.