Tuesday, 30 April 2013

HBase: Bulk upload using ImportTsv in HBase Table


ImportTsv helps you to upload data in HBase from a tsv file placed on hdfs.
Lets take and example hbase table , "employee" with column family "basic_info"
Following is an example file on hdfs:

$ hadoop fs -cat /user/hadoop/importtsv
1    emp1    24
2    emp2    26
3    emp3    24

Uploading data int o employee table using ImportTsv

$HBASE_HOME/bin/hbase org.apache.hadoop.hbase.mapreduce.ImportTsv -Dimporttsv.columns=HBASE_ROW_KEY,basic_info:empname,basic_info:age employee hdfs/namenode:address/user/hadoop/importtsv

First column of the file will be stored as  row key, second column will be stored as  "empname" and third column will be stored as age as follows:

hbase(main):013:0>scan 'employee'
ROW                                                  COLUMN+CELL                                                                                                                                             
 1                                                   column=basic_info:age, timestamp=1360238054613, value=24                                                                                               
 1                                                   column=basic_info:empname, timestamp=1360238054613, value=emp1                                                                                       
 2                                                   column=basic_info:age, timestamp=1360238054613, value=26                                                                                               
 2                                                   column=basic_info:empname, timestamp=1360238054613, value=emp2                                                                                  
 3                                                  column=basic_info:age, timestamp=1360238054613, value=24                                                                                               
 3                                                   column=basic_info:empname, timestamp=1360238054613, value=emp3

Hive/HBase Integration ( Enter data in hbase table using hive)

For hive 0.6 or lesser,  use hbase-0.26.  If we want to use hbase-xxx xxx>0.26, use hive-0.7 or greater.
1)    Software requisite ( Flowing are the software stack I used )
      . hadoop
      . hbase
      . hive

2)   Assuming we have Hadoop , Hbase & Hive installed & hadoop and Hbase are up and running.

3)   Go to lib folder in hive instillation and look for hbase-xx version.  This should match the  hbase master that we have started. If not we can  replace the correct version of jars. Make sure the delete or rename the previous HBase jar after copying correct version of jars.
     Perform the same operation for zookeeper

4) Run following command from HiVE_HOME to start HIVE CLI

   bin/hive --auxpath $HIVE_HOME/lib/hive-hbase-handler-0.8.1.jar,$HIVE_HOME/lib/hbase-0.92.1.jar,$HIVE_HOME/lib/zookeeper-3.4.3.jar,$HIVE_HOME/lib/guava-r06.jar -hiveconf hbase.zookeeper.quorum=zk(addreess of zookeeper system)

    If there are multiple zookeepers then run it as follows:  

    bin/hive --auxpath $HIVE_HOME/lib/hive-hbase-handler-0.8.1.jar,$HIVE_HOME/lib/hbase-0.92.1.jar,$HIVE_HOME/lib/zookeeper-3.4.3.jar,$HIVE_HOME/lib/guava-r06.jar -hiveconf hbase.zookeeper.quorum=zk1,zk2,zk3

  Make sure you correct the version of jar as per your setup
    Also , you can set "HIVE_AUX_JARS_PATH" variable in hive-env.sh and add these jars there
     Note:$HADOOP_HOME must be set or hadoop must be in the path

5)In order to create a new HBase table which is to be managed by Hive, run below command from Hive.             

  CREATE TABLE hbase_table(key int, value string)                     
STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler'              
WITH SERDEPROPERTIES ("hbase.columns.mapping" = ":key,cf1:val")               T
TBLPROPERTIES ("hbase.table.name" = "xyz");

  The table is known as hbase_table within Hive, and as xyz within Hbase.
  Here we created physical table. IF table already exists in HBase, you can create External Table in Hive.     

6) We can cross check in Hbase shell givinglist command. It will list down the table “XYZ”.

7)    Try inserting records from Hive to Hbase by giving command.


INSERT INTO TABLE hbase_table SELECT 1,'test' from dummy limit 1;

8 )   Use HBase shell to verify that the data actually got loaded through command scan "xyz"

Hive : Custom User Defined Function (UDF)

Hive provides many inbuilt functions. However, you can also create your custom functions and use it like inbuilt functions. Following is an example custom function that converts the string to uppercase

package com.test.hive;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;

@Description(name = "uppercase",
value = "uppercase(string) - converts string to uppercase ",
extended = "Example:\n"
+ " > SELECT uppercase(string) FROM src;\n")

public class UpperCase extends UDF{
    
    public String evaluate(String input)
    {
        String value=input;
        value=value.toUpperCase();
        return value;
    }
    }

Here, you need to extend "org.apache.hadoop.hive.ql.exec.UDF" class and override "evaluate" function. 

The @Description(...) is an optional Java annotation. This is how function documentation is defined and you should use these annotations to document your own UDFs.

When a user invokes DESCRIBE FUNCTION ..., this desription gets displayed

Create jar file of the project and add it in hive as follows:

hive>add jar /pathto/jar;

Then you create your custom function as follows:

hive>create temporary function uppercase as 'com.test.hive.UpperCase';

Now , your function is available to use

hive> select uppercase("test function") from dummy;
TEST FUNCTION

Also, you create an hql file with all these commands and run it from prompt as follows:

$cat check.hql
add jar /pathto/jar;
create temporary function uppercase as 'com.test.hive.UpperCase';
select uppercase("test") from dummy;
$ hive -f /pathto/check.hql

Hadoop: Map Reduce: Using command line arguments in Mapper Class

In Map Reduce if we pass command line arguments it goes to driver class . However, if want to use it in Mapper class , it can be done as follows:
In Driver class , set the command line argument's value in the configuration object as follows:

public class TestDriver
{
    public static void main(String[] args) throws IOException,InterruptedException,ClassNotFoundException
    {
         Configuration conf = new Configuration();
         conf.set("val1", args[0]);
        conf.set("val2", args[1]);
  }
}

 Now , in Mapper , you can get these values as follows:
  
public class TestMapper extends Mapper
{
  public void map(Object key,Text value,Context context) throws IOException,InterruptedException
    {
        val1=context.getConfiguration().get("val1");
        val2=context.getConfiguration().get("val2");

    }
}

Hadoop: Map Reduce Example: Calculate mean in Map Reduce


Following Map Reduce job will calculate mean of all the values of a column of a file placed on HDFS 

package com.impetus;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.Path;

import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.io.NullWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.mapreduce.Job;

import org.apache.hadoop.mapreduce.Mapper;

import org.apache.hadoop.mapreduce.Reducer;

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MeanDriver {
    public static class MeanMapper extends
            Mapper<Object, Text, Text, IntWritable> {
        Text word = new Text("key");
        IntWritable val = new IntWritable();
        public void map(Object key, Text value, Context context)
                throws InterruptedException, IOException {
            String columns[] = value.toString().split("\t");
            val.set(Integer.parseInt(columns[0]));
            context.write(word, val);
        }
    }
    public static class MeanReducer extends
            Reducer<Text, IntWritable, NullWritable, IntWritable> {
        NullWritable out = NullWritable.get();
        IntWritable result = new IntWritable();
        int count = 0;
        public void reduce(Text key, Iterable<IntWritable> values,
                Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
                count += 1;
            }
            sum = sum / count;
            result.set(sum);
            context.write(out, result);
        }
    }
    public static void main(String args[]) throws IOException,
            InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        if (args.length != 2) {
            System.err.println("Usage: Wordcount <in> <out>");
            System.exit(2);
        }
        Job job = new Job(conf, "calculate mean");
        job.setJarByClass(MeanDriver.class);
        job.setMapperClass(MeanMapper.class);
        job.setReducerClass(MeanReducer.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(IntWritable.class);
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}

Hadoop:Copy files from one hadoop cluster to other hadoop cluster

Files can be copied from one hadoop cluster to other hadoop cluster as follows:

$ hadoop distcp hdfs://host1:9000/test hdfs://host2:9000/test

I will copy file "test" from one cluster to other.

File names can be same or different.

You need to use hostnames because IP address will not work with this command.

Also, here port number is 9000 which should be replaced with the port number on which namenode is configured.

Thursday, 25 April 2013

Unix: Split a large file into small files

split command can be used to split a large file into small files.
Options:
-b : Split files based on size
-l: Split file based on number of lines

Example:

Split the file into 20 MB pieces

$ split -b 20M filename

Split the file based up on the number of lines

$ split -l 1500  filename

Unix Shell Script :How to Use functions


User defined functions can be created in shell scripts. Syntax for creating a function is :

Syntax:
function_name()
{
#code
}

Functions needs to be created before they are called.

Syntax for calling a function in shell script is :

function_name arg1 arg2

Also, command line arguments works similarly they work in shell  scripts. So $1 would be the first argument inside the function , $2 would be the second argument and so on.

Following is an example shell script which contains a fucntion "func()" :

$ cat testfunction.sh
#!/bin/bash
func()
{
echo $1
}
func hello

$ ./testfunction.sh
hello

Unix:Renice Command: Change priority of already running process

"Renice"  is the command that is used to change the priority of already running process.

Options:
-u : Change priority of processes of a user
-p : Changing priority of a process with its pid . It is the default option

Example:

$ renice 15 process_id

It will change the priority of this process to 15

$sudo renice 10 -u user_name

It will change the priority of all the process of given user

Note:
1) Users other than the super-user may only alter the priority of processes they own,and can only increase their  nice value within the range 0 to 20.
2) The super-user may alter the priority of any process and set the priority to any value in the range (-20) to (19)
3) Any negative value of priority makes process execution very fast.

Unix Shell Script: Remove invalid control characters(ctrl-a,ctrls-m) etc from file


Following is  an example file :

$ cat test
row-1[]colfam1[]quan1[]val1
row-2[]colfam1[]quan2[]val2

It has control characters between lines.

Following is the way to remove these characters from file.

$ cat test | tr  -c "[:print:]^\n" " "
row-1 colfam1 quan1 val1
row-2 colfam1 quan2 val2

Unix Shell Script: Capitalize first letter of every word of a line

Lets take an example file as follows:

$ cat file
capiltalize first letter of every word of a line
using shell script

If you want to capitalize first letter of every word of all lines, it can be done as follows:

$ sed -i -e 's/^./\U&/g; s/ ./\U&/g' file
$ cat file
Capiltalize First Letter Of Every Word Of A Line
Using Shell Script

^. - represents  character that follows beginning of a line i.e. first character of the line
  .(space and dot) - represents every character that follows space
U - represents uppercase ( L can be used for lowercase if needed)
If you want line to perform this operation on selective lines , you can provide line number as follows:

$ sed -i -e '1,3 s/^./\U&/g; s/ ./\U&/g' file

Now, this operation will be performed on first three lines

Unix Shell Script: Finding unique lines of a file without sorting the file

Let's take an example file as follows:

$ cat file
AAAA
FFFF
BBBB
BBBB
CCCC
AAAA
FFFF
DDDD

If you want to find unique lines of this file, it can be done as


$ cat file|sort|uniq
AAAA
BBBB
CCCC
DDDD
FFFF

However, it changes the order of occurrence of lines.

Following "awk" command will find unique lines of a file without sorting the file:

$ awk '!x[$0]++' file
AAAA
FFFF
BBBB
CCCC
DDDD

awk 'x[$0]++' keep on incrementing the hash array "x" of line from 0 or undefined to 1,2 and so on. Since there is no code for awk in {}, so it by default prints the line. When ! is appended in front of x[$0]++ , it will only print line when value of its hash array "x" is 0 or undefined. 

Unix Awk Script: Print all fields except last two fields of a file

Lets take an example file as follows:

$ cat file
A    B    C    D    E
A    B    C    D    E

If you want to print all fields except last two fields , it can be done using "awk" as follows: 

$ awk '{$NF="";$(NF-1)="";print $0}' file
A B C   
A B C                                                                                                  

Unix : Reading content of tar file without Extracting

To read the contents of tar file without extracting use "tar -tf" option as follows:

$ tar -tf filename.tar.gz

If the archive contains multiple files and directories, it is recommended to force the output to less for easier viewing, as the following;

$ tar tf filename.tar.gz | less

You will be able to view contents .tar, .tar.gz files without extracting them

Unix: Adding a user and a group

Adding a Group:

#addgroup group_name

Adding a User:

#useradd -m -g group_name -s /bin/bash user_name

Options:
-m: created home directory for a user i.e. /home/user_name .It will throw an error if this directory is already existing. Also, it wil create enviorment files for that user in this directory
-g: specifies the group in which user will be added
-s: specifies the default shell for the user

Unix: Execute Java Command in crontab

For executing java command in crontab , create a shell script with the Java command in it and execute it in crontab :
For Example , take a look at following script :

#!/bin/bash
 #script name : javacheck placed in /home/user
cpath="/home/user"
/usr/lib/jvm/jdk1.6.0_25/bin/java -cp $cpath/jar1:$cpath/jar2 classname >/home/user/javacheck

Always provide absolute path of java binary as well as of the jars since crontab won't be able to read environment variables of user. Otherwise , you can manually set variables in script or in crontab itself so that they can be referred.
Make the file executable to user

Crontab Entry:
* * * * * /home/user/javacheck 

Don't put sh or bash in front of crontab entry.
Also, if you want to execute java in crontab without writing shell script, it can be done as follows;

* * * * * /usr/lib/jvm/jdk1.6.0_25/bin/java -version 2>/home/user/javaversion

Again don't include sh or bash in front of java command because sh or bash won't execute binary file. Also, output of java -version will be redirected as standard error not standard output, thats why i used standard error redirection here

Unix Shell Script : Removing Leading and Trailing spaces from a string

Leading spaces from value of a variable can be removed as follows:

$ echo $var | sed 's/^ *//g'

Trailing spaces from value of a variable can be removed as follows:

$ echo $var | sed 's/ *$//g'

Unix Shell Script - Reading a file using For loop

If you want to read whole/full line in for loop , you need to set IFS(Internal Field Separator) to new line which is by default space as  follows:

#!/bin/bash
OIFS=$IFS #Original Internal field separator
# Setting Internal Field Separator to new line
IFS="
"
for line in `cat filename`
do
echo $line
done

Unix Shell Script: ssh under while loop

When you try to do ssh in while loop  as follows:, it will do ssh once then quit the loop. In other words looping won't happen

while read line
do
 ssh  user@$line "jps"
done

So the solution is run ssh as background process i.e use -n option with ssh as follows:

while read line
do
 ssh -n user@$line "jps"
done

One more benefit, executing it in backgroud is that in case there is some error while doing ssh to some machine, loop wont quit since process is running in background. So it will fire ssh process on all other machines that appear after the erroneous machine in the file

Also, you can use for loop for it.

OIFS=$IFS #Original Internal field separator
IFS=" # Setting Internal Field Separator to new line
"
for  line in `cat filename`
do
ssh user@$line "jps"
done

Unix Shell Script - Read not working inside While Read

If you want to read some input inside while read lline loop , it can be done as follows:

while read line
do
line=`echo $line`
echo "Enter choice"
read choice</dev/tty
echo "$choice" " " "$line"
done<filename

read does not work under while because we have already used "read" in reading line from a file .

Unix:sudo - checking permissions , giving permissions(visudo), configuration files(sudoers.so)


sudo:
To make changes in sudo config, use visudo utility.
________________________________

To list current permissions:

$ sudo -l
Matching Defaults entries for impadmin on this host:
    env_reset,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin

User impadmin may run the following commands on this host:
    (ALL : ALL) ALL
________________________________

'sudo' is located in "/usr/bin/sudo".
1. It must not be writable by any other user except 'root', otherwise none will be able to sudo.  
2. It must have 's' permission for 'root' instead of 'x' permission.

$ ls -l /usr/bin/sudo
-rwsr-xr-x 1 root root 65608 Jan 31 21:14 /usr/bin/sudo
________________________________

File "/usr/lib/sudo/sudoers.so" must only be writable by 'root'.

$ ls -l /usr/lib/sudo/sudoers.so
-rw-r--r-- 1 root root 177452 May 16 10:54 sudoers.so

Unix Shell Script:Running mysql queries in shel script

Take a look at following script

#!/bin/bash
mysql -h192.168.1.1 -uroot -proot<<EOF
use information_schema;
show tables;
EOF

Here  "-h" specifies the host where mysql is running
"-u" and  "-p" specify username and password
information_schema is the database name

Note: Database should be accessible from 'user'@'host' if you are accessing it from remote host

Unix - To record everything printed on screen i.e. commands, output etc


'script'  is a command that records everything printed on your screen. The record is recorded to the filename, if no filename is specified results are recorded to the file typescript.

$ script myfile.txt

Will log all results into the file myfile.txt. This will open a sub-shell and records all information through this session. The script ends when the forked shell exits (user types exit) or when CTRL-D is typed.
Note: If the script file is deleted during the script process the script still remains in memory however will not log the results.Also, till the time you dont exit or type CTRL-D , no data gets flushed in to scriptfile

Options :
-a Append the session record to filename, rather than overwrite it.
-f Will flush the output in scriptfile after every write( Recommended )
________________________________________________________

$ script
Script started, file is typescript
$ cat "Hello"
cat: Hello: No such file or directory
$ echo "HELLO"
HELLO
$ exit
Script done, file is typescript

________________________________________________________
$ cat typescript
Script started on Monday 03 December 2012 03:59:13 PM IST
$ cat "Hello"
cat: Hello: No such file or directory
$ echo "HELLO"
HELLO
$ exit
Script done on Monday 03 December 2012 03:59:27 PM IST

Unix: Grep consecutive lines with duplicates field values

Here is a file :

8.txt  07:34:12 -> CONTENT START
8.txt  07:34:42 <-CONTENT END
8.txt  07:35:08 -> CONTENT START
8.txt  07:36:33 <-CONTENT END
8.txt  07:57:51 -> CONTENT START
8.txt  07:57:52 -> CONTENT START
8.txt  07:58:25 <-CONTENT END
8.txt  07:58:36 -> CONTENT START
8.txt  07:59:24 <-CONTENT END
8.txt  08:20:23 -> CONTENT START
8.txt  08:21:22 <-CONTENT END
8.txt  08:22:44 -> CONTENT START
8.txt  07:34:12 -> CONTENT START
8.txt  08:23:07 <-CONTENT END

Output expected:

8.txt 07:57:51 -> CONTENT START
8.txt 07:57:52 -> CONTENT START
8.txt 08:22:44 -> CONTENT START
8.txt 07:34:12 -> CONTENT START

That is we want only those lines which have same  value in the last field and are appearing consecutively.

It can be done as follows: 

$ uniq -D -f4 file

Unix Shell Script: Convert value of a variable to lowercase or uppercase

For example , we have a variable "check" as follows:

$ check="Unix Shell Script"

If you want to convert it into lowercase , it can be done as follows:

$ check=`echo $check | tr [:upper:] [:lower:]`
$ echo $check
unix shell script

Or if you want to convert it into uppercase , it can be done as follows:

 $ check=`echo $check | tr [:lower:] [:upper:]`
 impadmin@sourav:~$ echo $check
 UNIX SHELL SCRIPT

Wednesday, 24 April 2013

Unix:Convert rpm files to debian files and vice versa

Alien is the utility. that helps you to convert rpm file into deb files

sudo alien package_file.rpm

It would convert the package_file.rpm to package_file.deb 

To convert debain file to rpm file

sudo alien -r package_file.deb

You can install "alien" as 

sudo apt-get install alien

Unix: dpkg (Package Manager for Debian)


dpkg (Package Manager for Debian):

dpkg is a tool to install, build, remove and  manage  Debian packages.  To use, become root or use sudo.

To list installed packages:

dpkg --get-selections

To list installed packages with version:

dpkg -l
dpkg --list
dpkg-query -l
dpkg-query --list

To install a .deb file:

dpkg -i package_name.deb

To uninstall a .deb file:

dpkg -r package_name

To find version of a package installed:

dpkg -l package_name

Unix: Apt-Get (Advanced Packaging Tool):Info, Problems and solutions

Apt-Get (Advanced Packaging Tool):

The apt-get command is a powerful command-line tool used to work with Ubuntu's Advanced Packaging Tool (APT) performing such functions as installation of new software packages, upgrade of existing software packages, updating of the package list index, and even upgrading the entire Ubuntu system.

Install a Package:
sudo apt-get install

Remove a Package:
sudo apt-get remove

Update the Package Index:
The APT package index is essentially a database of available packages from the repositories defined in the /etc/apt/sources.list file. To update the local package index with the latest changes made in repositories, type the following: 

sudo apt-get update

Upgragde Packages:
sudo apt-get upgrade
_______________________________________________________
PROBLEM: Unable to install or remove anything, it gives below error:
root@impetusN087:~# apt-get install synaptic
Reading package lists... Done
Building dependency tree       
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 python-setuptools : Depends: python-pkg-resources (= 0.6.16-1ubuntu0.1) but 0.6.24-1ubuntu1 is to be installed
 synaptic : Depends: libept1.4.12 but it is not going to be installed
            Depends: libvte9 (>= 1:0.24.0) but it is not going to be installed
            Recommends: rarian-compat but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I tried to use
apt-get install
apt-get -f install
apt-get update; apt-get upgrade

but, nothing works.

apt-get install gave me a clue that there's something fishy with sources.list file.  So, I scp that file from someone's system.

Then, tried “apt-get install” , then “apt-get upgrade” , still nothing worked.

Then, I used “apt-get purge python-setuptools”.  All this did is, it deleted all the configuration files for that package.  Then, I used “apt-get install packagename” and works.