Linux Filesystem colour codes

When we fire ls –all in linux cli, files may be listed in different colours  

The color code of the files is as follows:

Blue: Directory file

White: Normal file

Green: Executable file

Yellow: Device file

Magenta: Picture file

Cyan: link file

Red: Compressed file

File Symbol

-(Hyphen) = Normal file

d=directory

l=link file

b=Block device file

c=character device file
Advertisements

Recovery of deleted files in Hadoop

There may be incidents which we accidently delete necessary files from hadoop. Sometimes the entire file system may get deleted. For doing recovery process the below steps may help you.

For doing this recovery method  trash should be enabled in hdfs. Trash can be enabled by setting the property  fs.trash.interval greater than 0. By default the value is zero.  Its value is number of minutes after which the checkpoint gets deleted. If zero, the trash feature is disabled. We have to set this property in core-site.xml.

<property>
  <name>fs.trash.interval</name>
  <value>30</value>
  <description>Number of minutes after which the checkpoint
  gets deleted.
  If zero, the trash feature is disabled.
  </description>
</property>

There is one more property which is having relation with the above property called fs.trash.checkpoint.interval. It is the number of minutes between trash checkpoints. This should be smaller or equal to  fs.trash.interval. Everytime the checkpointer runs, it creates a new checkpoint out of current and removes checkpoints created more than fs.trash.interval minutes ago.The default value of this property is zero.

<property>
  <name>fs.trash.checkpoint.interval</name>
  <value>15</value>
  <description>Number of minutes between trash checkpoints.
  Should be smaller or equal to fs.trash.interval.
  Every time the checkpointer runs it creates a new checkpoint 
  out of current and removes checkpoints created more than 
  fs.trash.interval minutes ago.
  </description>
</property>

If the above properties are enabled in your cluster. Then the deleted files will be present in .Trash directory of hdfs. You have time to recover the files until the next checkpoint occurs. After the new checkpoint the deleted files will not be present in the .Trash. So recover before the new checkpoint. If this property is not enabled in your cluster,  you can enable this for future recovery.. 🙂

Changing the Default GUI boot mode of Ubuntu

If you want to change the default GUI mode  boot of ubuntu machine, just do the following changes. Here actually we are not removing the GUI, just changing the default booting as text mode. By doing this you can reduce the memory consumption.

Open the terminal as root user or sudo user.

open /etc/default/grub as and add text to the

sudo nano /etc/default/grub

And in the file, change this line:

GRUB_CMDLINE_LINUX_DEFAULT="text"

Then update your Grub

sudo update-grub

To view the changes, reboot the system. Then the system will always boot in text mode. This is applicable to Ubuntu OS only.

If you want to get the UI without changing the configuration from text mode, execute startx command in the terminal. Then the UI will be loaded.

A Simple Multithreaded Program in Java

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

Here I am explaining a simple multi-threaded program.

The main thread writes 5000 to 1 in a file named MainThread.txt and the child thread writes 1 to 5000 in a file named childthread.txt.
Both will happen at the same time. That is it will run in parallel.

We are creating a child thread class by implementing a method Runnable.

This class will contain a method named run() where we do our functionality.

We will instantiate this thread class in the main method, so it will run along with the main thread.

The child thread class is

package com.amal.thread;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ThreadTest implements Runnable {
	Thread t;
	ThreadTest()
	{
		t=new Thread(this,"My Test");
		System.out.println("My test thread");
		t.start();

	}
	public void run() {
		File file=new File("childthread.txt");

		try {

			FileWriter fwt = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bwt = new BufferedWriter(fwt);

			for(int i=0; i<5000; i++)
			{
				bwt.write("thread "+i);
				bwt.newLine();
			}				
			bwt.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}

The main class is

package com.amal.thread;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class MainClass {
	public static void main(String[] args) throws IOException {
		new ThreadTest();
		File file1=new File("MainThread.txt");
		FileWriter fw = new FileWriter(file1.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);

		for (int i=5000;i>1;i--)
		{
			bw.write("main "+i);
			bw.newLine();
		}
		bw.close();
	}
}

Making Custom Auto completion mechanism for Pig

One handy feature of pig’s Grunt shell is completion mechanism, which will try to complete

Pig Latin keywords and functions when you press the Tab key. For example, consider

the following incomplete line:

grunt> a = foreach b ge

If you press the Tab key at this point, ge will expand to generate, a Pig Latin keyword:

grunt> a = foreach b generate

We can customize the completion tokens by putting our necessary tokens in a file named autocomplete and put it in the pig class path or in the directory where we are invoking the grunt shell

For example: I created a file named autocomplete which contains the tokens

Julie

India

Software

Engineer

Hadoop

Bigdata

Then after saving this if u press the corresponding alphabet and press tab, it will display the choices for autocompletion.

Note: The tokens that I mentioned above is not related to pig commands or funtions. It is just for an example only. Like this you can create your own custom scripts or tokens for making the scripting handy

Accessing Unix Server through Putty using Private Key

Type hostname or ipaddress

Capture1

Then in the left side part of putty, click on SSH and expand.

Capture2

Then you can see a section auth

Click on auth

Capture3

There you will get a window with browse button.

Capture4

Load your private key file (.ppk) and press open.

Then enter username and passphrase-key (if given) and login

This is the method we usually use to login to unix  cloud instances .

Creating a Public and Private Key using PuttyGen

On a Windows machine, you can use PuttyGen to generate a public/private key pair.

PuttyGen can be downloaded from http://www.putty.org/

The private key is what you need on the client machine – for use with Putty for example. The public key goes to the host machine.

Open PuTTY Key Generator (puttygen.exe in the putty folder) which should look something like this.

2

PuTTYGen supports 3 key types:

  1. SSH-1 (RSA),
  2. SSH-2 RSA, and
  3. SSH-2 DSA

SSH-2 contains more features than SSH-1. SSH-1 has some design flaws which make it more vulnerable than SSH-2. Only choose SSH-1 if the server/client you want to connect to does not support SSH-2. The default SSH-2 RSA is probably better than SSH-2 DSA.

The Number of bits in a genereted key sets the size of your key, and thus the security level. For SSH-2 RSA, it’s recommended to set this at a minimum of 2048. PuTTYGen defaults to 1024. Setting this to 4096 would provide an even stronger key, but is probably overkill for most uses.

2

Click Generate to start the key generation. You will see something like the figure below ( move your mouse as suggested above the progress bar):

3

The result of the key generation is shown below. (in the box labelled Public key for pasting into OpenSSH authorized_keys file).

4

The Key comment enables you to generate multiple keys and easily tell them apart. It’s general recommended to set this to username@hostname, where the username is the username used for login, and hostname is, as it says on the tin, the name of the host machine. For example, for a user ‘amal’ on domain ‘example.com’, set this to amal@example.com.

The Key passphrase is an additional way to protect your private key, and is never transmitted over the internet. The strength of your key is not affected by the passphrase in any way. If you set one, you will be asked for it before any connection is made via SSH . Setting it might gain you a few extra moments if your key falls into the wrong hands, as the culprit tries to guess your passphrase. Obviously if your passphrase is weak, it rather defeats the purpose of having it.

If you don’t want the passphrase key, you can leave it empty.

Note that if your set a passphrase and forget it, there is no way to recover it. When you reload a previously saved private key (using the Load button), you will be asked for the passphrase if one is set.

Here is what PuTTYGen looks like after editing the key comment and the passphrase.

5

Now save your keys – one private and one public – using the Save private key and Save public key buttons respectively. You can save the public key in any format – *.txt is good. The private key is saved in PuTTY’s format – *.PPK. PuTTY will need this private key for authentication.

6

last

The public key in the highlighted box is all in one line as expected by OpenSSH, and is in the correct format (unlike the version you just saved). If you are using OpenSSH, this is what you paste in your .ssh/authorized_keys file.

SSH Key based access to Unix Servers

Access to Linux and Unix systems via Secure Shell (SSH) is standard practice.  It offers encrypted access to enable you to administer your server which is vital over the big bad internet.

There are different ways to access SSH: password, user keys and host-based keys.  Passwords are the most common but are less secure than key-based access.  Passwords are susceptible to keylogger attacks, as well as more likely to fool users into a “man-in-the-middle” attack (one where you think you’re logging onto your server, but you are actually proxying your connection through another server which has been compromised and is recording every keystroke and data transfer.)

Key based access is more secure as it requires two parts of a key to be present before access is granted.  When dealing with cloud based services such as Rackspace and Amazon Web Services, key based access is enabled by default.  Key based access is also known as “passwordless access” as access is granted by your key, not by asking for any passwords.  The exception to this is if you put a password on your key (but you can enable services that ask for this password once and it is cached for the rest of your session).

Setting this up on your Linux server is very simple, and most installations of SSH (OpenSSH) enable both password and key-based access by default.  Let’s assume user@client needs to access user@server

Ensure OpenSSH is installed on your Linux server (server)

Debian/Ubuntu

sudo apt-get install openssh-server

CentOS/Fedora/RedHat/Oracle Enterprise Linux

sudo yum install openssh-server

Ensure the following lines has been uncommented from /etc/ssh/sshd_config

RSAAuthentication yes
PubkeyAuthentication yes

Restart OpenSSH

Debian/Ubuntu

sudo /etc/init.d/ssh restart

CentOS/Fedora/RedHat/Oracle Enterprise Linux

sudo /etc/init.d/sshd restart

On your Linux client (desktop or other server you’ll be using to connect to the server configured in steps 1-3)

Generate your public and private keys

ssh-keygen -t rsa

You will see output like the following:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Created directory ‘/home/user/.ssh’.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
79:e1:08:77:c2:0d:c4:ff:35:22:64:9a:4d:03:b8:67 user@client
The key’s randomart image is:
+–[ RSA 2048]—-+
|       ++.                      |
|      …o=                    |
|      ..+O+.                 |
|      .oE*+.. o             |
|       oS oo o .            |
|         .  .                     |
|                                  |
|                                  |
|                                  |
+—————–+

This produces two important pieces of data.  Your PRIVATE KEY (~/.ssh/id_rsa) and your PUBLIC KEY (~/.ssh/id_rsa.pub).  You must keep your PRIVATE KEY safe.  Your public key can be given to anyone.  Without your private key your public key is just a string of characters and you can’t generate a private key from a public key.  Equally, you can’t generate a public key from a private key.  Together they make your key-pair.
To enable your private key to access the server running SSH configured in steps 1-3 (server) you simply copy the contents of your public key onto the server.
Copy the public key from your client machine to server

scp .ssh/id_rsa.pub user@server:
(enter your password)

Login to server

ssh user@server
(enter your password)

Copy the public key to authorized_keys

cat .ssh/id_rsa.pub >> .ssh/authorized_keys

Change the permission of authorized_keys file to 600 (rw——-)

chmod 0600 .ssh/authorized_keys

This creates the directory .ssh/ and relevant authorized_keys file with the correct permissions (anything less strict will not work).  You can put in a number of public keys in here, line-by-line.  When there are multiple entries it allows multiple people to connect to that account using their keys.  This becomes useful when a team of system administrators require access to systems with minimal accounts installed, but each are accountable for audit purposes as to who logged onto the system.

Log out of that session and log back in again and you shouldn’t be asked for a password.

Hadoop FS Shell Commands

FS Shell

FS shell means FileSystem shell. The file system may be hdfs or the local file system(linux file system.

For HDFS the scheme is hdfs,

Eg: hdfs://namenodehost:<port>/user/test

For the local filesystem the scheme is file.

Eg: file:///testfile

If no schema is specified, the default scheme specified in the configuration is used. By default it is hdfs.

Majority of the commands in FS shell behave like corresponding Unix commands. Differences are described with each of the commands.

cat

Usage: hadoop fs -cat URI [URI …]

Copies source paths to stdout.

Example:

  • hadoop fs -cat hdfs://nn1.example.com/file1 hdfs://nn2.example.com/file2
  • hadoop fs -cat file:///file3 /user/hadoop/file4

Exit Code:
Returns 0 on success and -1 on error.

chgrp

Usage: hadoop fs -chgrp [-R] GROUP URI [URI …]

Change group association of files. With -R, make the change recursively through the directory structure. The user must be the owner of files, or else a super-user. Additional information is in the HDFS Admin Guide: Permissions.

chmod

Usage: hadoop fs -chmod [-R] <MODE[,MODE]… | OCTALMODE> URI [URI …]

Change the permissions of files. With -R, make the change recursively through the directory structure. The user must be the owner of the file, or else a super-user. Additional information is in the HDFS Admin Guide: Permissions.

chown

Usage: hadoop fs -chown [-R] [OWNER][:[GROUP]] URI [URI ]

Change the owner of files. With -R, make the change recursively through the directory structure. The user must be a super-user. Additional information is in the HDFS Admin Guide: Permissions.

copyFromLocal

Usage: hadoop fs -copyFromLocal <localsrc> URI

Similar to put command, except that the source is restricted to a local file reference.

copyToLocal

Usage: hadoop fs -copyToLocal [-ignorecrc] [-crc] URI <localdst>

Similar to get command, except that the destination is restricted to a local file reference.

count

Usage: hadoop fs -count [-q] <paths>

Count the number of directories, files and bytes under the paths that match the specified file pattern. The output columns are:
DIR_COUNT, FILE_COUNT, CONTENT_SIZE FILE_NAME.

The output columns with -q are:
QUOTA, REMAINING_QUATA, SPACE_QUOTA, REMAINING_SPACE_QUOTA, DIR_COUNT, FILE_COUNT, CONTENT_SIZE, FILE_NAME.

Example:

  • hadoop fs -count hdfs://nn1.example.com/file1 hdfs://nn2.example.com/file2
  • hadoop fs -count -q hdfs://nn1.example.com/file1

Exit Code:

Returns 0 on success and -1 on error.

cp

Usage: hadoop fs -cp URI [URI …] <dest>

Copy files from source to destination. This command allows multiple sources as well in which case the destination must be a directory.
Example:

  • hadoop fs -cp /user/hadoop/file1 /user/hadoop/file2
  • hadoop fs -cp /user/hadoop/file1 /user/hadoop/file2 /user/hadoop/dir

Exit Code:

Returns 0 on success and -1 on error.

du

Usage: hadoop fs -du URI [URI …]

Displays aggregate length of files contained in the directory or the length of a file in case its just a file.
Example:
hadoop fs -du /user/hadoop/dir1 /user/hadoop/file1 hdfs://nn.example.com/user/hadoop/dir1
Exit Code:
Returns 0 on success and -1 on error.

dus

Usage: hadoop fs -dus <args>

Displays a summary of file lengths.

expunge

Usage: hadoop fs -expunge

Empty the Trash. Refer to HDFS Architecture for more information on Trash feature.

get

Usage: hadoop fs -get [-ignorecrc] [-crc] <src> <localdst>

Copy files to the local file system. Files that fail the CRC check may be copied with the -ignorecrc option. Files and CRCs may be copied using the -crc option.

Example:

  • hadoop fs -get /user/hadoop/file localfile
  • hadoop fs -get hdfs://nn.example.com/user/hadoop/file localfile

Exit Code:

Returns 0 on success and -1 on error.

getmerge

Usage: hadoop fs -getmerge <src> <localdst> [addnl]

Takes a source directory and a destination file as input and concatenates files in src into the destination local file. Optionally addnl can be set to enable adding a newline character at the end of each file.

ls

Usage: hadoop fs -ls <args>

For a file returns stat on the file with the following format:
filename <number of replicas> filesize modification_date modification_time permissions userid groupid
For a directory it returns list of its direct children as in unix. A directory is listed as:
dirname <dir> modification_time modification_time permissions userid groupid
Example:
hadoop fs -ls /user/hadoop/file1 /user/hadoop/file2 hdfs://nn.example.com/user/hadoop/dir1 /nonexistentfile
Exit Code:
Returns 0 on success and -1 on error.

lsr

Usage: hadoop fs -lsr <args>
Recursive version of ls. Similar to Unix ls -R.

mkdir

Usage: hadoop fs -mkdir <paths>

Takes path uri’s as argument and creates directories. The behavior is much like unix mkdir -p creating parent directories along the path.

Example:

  • hadoop fs -mkdir /user/hadoop/dir1 /user/hadoop/dir2
  • hadoop fs -mkdir hdfs://nn1.example.com/user/hadoop/dir hdfs://nn2.example.com/user/hadoop/dir

Exit Code:

Returns 0 on success and -1 on error.

moveFromLocal

Usage: dfs -moveFromLocal <localsrc> <dst>

Similar to put command, except that the source localsrc is deleted after it’s copied.

moveToLocal

Usage: hadoop fs -moveToLocal [-crc] <src> <dst>

Displays a “Not implemented yet” message.

mv

Usage: hadoop fs -mv URI [URI …] <dest>

Moves files from source to destination. This command allows multiple sources as well in which case the destination needs to be a directory. Moving files across filesystems is not permitted.
Example:

  • hadoop fs -mv /user/hadoop/file1 /user/hadoop/file2
  • hadoop fs -mv hdfs://nn.example.com/file1 hdfs://nn.example.com/file2 hdfs://nn.example.com/file3 hdfs://nn.example.com/dir1

Exit Code:

Returns 0 on success and -1 on error.

put

Usage: hadoop fs -put <localsrc> … <dst>

Copy single src, or multiple srcs from local file system to the destination filesystem. Also reads input from stdin and writes to destination filesystem.

  • hadoop fs -put localfile /user/hadoop/hadoopfile
  • hadoop fs -put localfile1 localfile2 /user/hadoop/hadoopdir
  • hadoop fs -put localfile hdfs://nn.example.com/hadoop/hadoopfile
  • hadoop fs -put – hdfs://nn.example.com/hadoop/hadoopfile
    Reads the input from stdin.

Exit Code:

Returns 0 on success and -1 on error.

rm

Usage: hadoop fs -rm URI [URI …]

Delete files specified as args. Only deletes non empty directory and files. Refer to rmr for recursive deletes.
Example:

  • hadoop fs -rm hdfs://nn.example.com/file /user/hadoop/emptydir

Exit Code:

Returns 0 on success and -1 on error.

rmr

Usage: hadoop fs -rmr URI [URI …]

Recursive version of delete.
Example:

  • hadoop fs -rmr /user/hadoop/dir
  • hadoop fs -rmr hdfs://nn.example.com/user/hadoop/dir

Exit Code:

Returns 0 on success and -1 on error.

setrep

Usage: hadoop fs -setrep [-R] <path>

Changes the replication factor of a file. -R option is for recursively increasing the replication factor of files within a directory.

Example:

  • hadoop fs -setrep -w 3 -R /user/hadoop/dir1

Exit Code:

Returns 0 on success and -1 on error.

stat

Usage: hadoop fs -stat URI [URI …]

Returns the stat information on the path.

Example:

  • hadoop fs -stat path

Exit Code:
Returns 0 on success and -1 on error.

tail

Usage: hadoop fs -tail [-f] URI

Displays last kilobyte of the file to stdout. -f option can be used as in Unix.

Example:

  • hadoop fs -tail pathname

Exit Code:
Returns 0 on success and -1 on error.

test

Usage: hadoop fs -test -[ezd] URI

Options:
-e check to see if the file exists. Return 0 if true.
-z check to see if the file is zero length. Return 0 if true
-d check return 1 if the path is directory else return 0.

Example:

  • hadoop fs -test -e filename

text

Usage: hadoop fs -text <src>

Takes a source file and outputs the file in text format. The allowed formats are zip and TextRecordInputStream.

touchz

Usage: hadoop fs -touchz URI [URI …]

Create a file of zero length.

Example:

  • hadoop -touchz pathname

Exit Code:
Returns 0 on success and -1 on error.