Monday, 14 January 2013

Rotating Linux Log Files

Rotating Linux Log Files
Logrotate is a great utility to manage and administer log files in a system. It provides you with a lot of options, namely, automatic rotation, compression and mailing of log files. Each log file can be rotated hourly, daily, weekly or monthly. In this article, I will show you how to manage your log files using logrotate.
Any type of logs can be managed using logrotate. It runs as a daily cron job. These days most of the operating systems come with logrotate pre-installed so you probably won't have to deal with the installation. Lets start with looking at the files and directories used by logrotate.
Files and Directories used by Logrotate
The 2 important files in case of logrotate are
/etc/logrotate.conf
/var/lib/logrotate.status    or    /var/lib/logrotate/status
The first file is where the whole configuration and default options of logrotate is stored. The second file contains the information about the last rotation times of different log files.
The directory thats usually used by logrotate is
/etc/logrotate.d
The options specified in /etc/logrotate.conf are used as default for rotating and managing log files. But if we want to specify separate settings for a set of log files then we can add their config files in this directory /etc/logrotate.d. Although we can even use another directory to save config files by changing an option in /etc/logrotate.conf.
Now, enough of the theory let’s see how these config files really look and what all the different options in it mean.
Logrotate Options
Let me first show you some commonly used options of logrotate and then we will see how to configure various options in the config file.
rotate <num>
Log files are rotated "num" times before getting deleted or mailed.
daily
When used this means log files should be rotated daily
weekly
Log files should be rotated weekly
monthly
Log files should be rotated monthly
notifempty
Don't rotate the log if its empty
compress
Compress the files after rotating them
delaycompress
This options means to delay the compression of a log file to the next rotation cycle. This is used in combination with compress.
missingok
If the log file is missing, go on to the next one without issuing an error message.
create <mode> <owner> <group>
After rotation create a new empty file with the following properties. e.g create 640 root adm. Just "create" will ensure to inherit the properties of previous log files.

Logrotate config files
As stated above, /etc/logrotate.conf is where the default options to handle logs are specified. A typical log file will look something like this.
# rotate log files weekly
weekly
# keep 4 weeks worth of backlogs
rotate 4
# create new (empty) log files after rotating old ones
create
# uncomment this if you want your log files compressed
#compress
# Packages drop log rotation information into this directory
include /etc/logrotate.d
# no packages own wtmp, or btmp -- we'll rotate them here
/var/log/wtmp {
    missingok
    monthly
    create 0664 root utmp
    rotate 1
}
/var/log/btmp {
    missingok
    monthly
    create 0660 root utmp
    rotate 1
}
The options mentioned in the config file above means that the logs are going to be rotated "weekly" and only 4 copies of backlogs will be maintained. On every rotation "create" a new empty file with properties inherited from the previous logs. Compression of backlogs is disabled.
The "include" directive is used to mention the directory in which the package specific log config files will be saved.
Managing Package specific log files in /etc/logrotate.d
Now, if there is an application which generates logs how would it be able to use logrotate to control and manage its logs. This is all done using its /etc/logrotate.d directory. This is where applications drop the information required by logrotate to manage their logs. e.g consider the example of apache logs. My apache logrotate config file looks something like this (its /etc/logrotate.d/apache2).
/var/log/apache2/*.log {
    weekly
    missingok
    rotate 5
    compress
    delaycompress
    notifempty
    create 640 root adm
    sharedscripts
    postrotate
        if [ -f "`. /etc/apache2/envvars ; echo ${APACHE_PID_FILE:-/var/run/apache2.pid}`" ]; then
            /etc/init.d/apache2 reload > /dev/null
        fi
    endscript
}
Now, cross checking  the options from the table mentioned above the following properties of the logs can be inferred.
·         It’s going to be a weekly rotation
·         5 backlogs will be maintained in compressed format. But since we are using 'delaycompress' as well, the compression of a backlog will take place in the next rotation.
·         No rotation will take place if file is empty.
·         No error in case no log is found.
·         On every rotation a new file will be created with owner root, group adm and permission 640
We haven't discussed anything about 'sharedscripts' or 'postrotate' yet. Let’s begin with prerotate/endscript and postrotate/endscript.
Prerotate and Postrotate
Both of these options control the scripts that will need to be run either before or after rotating a log file. Let’s take the above example.
postrotate
        if [ -f "`. /etc/apache2/envvars ; echo ${APACHE_PID_FILE:-/var/run/apache2.pid}`" ]; then
            /etc/init.d/apache2 reload > /dev/null
        fi
endscript
'endscript' is mandatory to be mentioned in both prerotate and postrotate to specify the ending of the script.
You would have also noticed the sharedscripts option in the apache2 logrotate config file. Now, if sharedscripts options is not specified, prerotate and postrotate will run the scripts on each log file which is rotated. But if you look carefully at the file logs mentioned in the apache2 logrotate conf file, its a wild card /var/log/apache2/*.log i.e. not just a single file but a bunch of files matching a pattern. These files in our case will be /var/log/apache2/access.log and error.log. So, for every rotation we will have 2 log files.
But look at the script that we want to run after rotation. It reloads the apache server and there is probably no need to run this script twice. So, by using sharedscripts we are ensuring that the script doesn't run on every rotated log file but only once.
I hope this howto will be helpful for a lot of you. If you have any doubts or want something to be corrected here, feel free to comment.


Wednesday, 31 October 2012

IP Address Configuration in UBUNTU



IP Addressing

The following section describes the process of configuring your systems IP address and default gateway needed for communicating on a local area network and the Internet.
Temporary IP Address Assignment
For temporary network configurations, you can use standard commands such as ip, ifconfig and route, which are also found on most other GNU/Linux operating systems. These commands allow you to configure settings which take effect immediately, however they are not persistent and will be lost after a reboot.
To temporarily configure an IP address, you can use the ifconfig command in the following manner. Just modify the IP address and subnet mask to match your network requirements.
sudo ifconfig eth0 10.0.0.100 netmask 255.255.255.0
To verify the IP address configuration of eth0, you can use the ifconfig command in the following manner.
ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 00:15:c5:4a:16:5a 
          inet addr:10.0.0.100  Bcast:10.0.0.255  Mask:255.255.255.0
          inet6 addr: fe80::215:c5ff:fe4a:165a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:466475604 errors:0 dropped:0 overruns:0 frame:0
          TX packets:403172654 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2574778386 (2.5 GB)  TX bytes:1618367329 (1.6 GB)
          Interrupt:16
To configure a default gateway, you can use the route command in the following manner. Modify the default gateway address to match your network requirements.
sudo route add default gw 10.0.0.1 eth0
To verify your default gateway configuration, you can use the route command in the following manner.
route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
10.0.0.0        0.0.0.0         255.255.255.0   U     1      0        0 eth0
0.0.0.0         10.0.0.1        0.0.0.0         UG    0      0        0 eth0
If you require DNS for your temporary network configuration, you can add DNS server IP addresses in the file/etc/resolv.conf. The example below shows how to enter two DNS servers to /etc/resolv.conf, which should be changed to servers appropriate for your network. A more lengthy description of DNS client configuration is in a following section.
nameserver 8.8.8.8
nameserver 8.8.4.4
If you no longer need this configuration and wish to purge all IP configurations from an interface, you can use the ip command with the flush option as shown below.
ip addr flush eth0
Note:
Flushing the IP configuration using the ip command does not clear the contents of /etc/resolv.conf. You must remove or modify those entries manually.
Dynamic IP Address Assignment (DHCP Client)
To configure your server to use DHCP for dynamic address assignment, add the dhcp method to the inet address family statement for the appropriate interface in the file /etc/network/interfaces. The example below assumes you are configuring your first Ethernet interface identified as eth0.
auto eth0
iface eth0 inet dhcp
By adding an interface configuration as shown above, you can manually enable the interface through the ifup command which initiates the DHCP process via dhclient.
sudo ifup eth0
To manually disable the interface, you can use the ifdown command, which in turn will initiate the DHCP release process and shut down the interface.
sudo ifdown eth0
Static IP Address Assignment
To configure your system to use a static IP address assignment, add the static method to the inet address family statement for the appropriate interface in the file /etc/network/interfaces. The example below assumes you are configuring your first Ethernet interface identified as eth0. Change the address, netmask, and gateway values to meet the requirements of your network.
auto eth0
iface eth0 inet static
address 10.0.0.100
netmask 255.255.255.0
gateway 10.0.0.1
By adding an interface configuration as shown above, you can manually enable the interface through the ifup command.
sudo ifup eth0
To manually disable the interface, you can use the ifdown command.
sudo ifdown eth0
Loopback Interface
The loopback interface is identified by the system as lo and has a default IP address of 127.0.0.1. It can be viewed using the ifconfig command.
ifconfig lo
lo        Link encap:Local Loopback 
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:2718 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2718 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:183308 (183.3 KB)  TX bytes:183308 (183.3 KB)
By default, there should be two lines in /etc/network/interfaces responsible for automatically configuring your loopback interface. It is recommended that you keep the default settings unless you have a specific purpose for changing them. An example of the two default lines are shown below.
auto lo
iface lo inet loopback

Wednesday, 26 September 2012

Creation of raw device for oracle table Space datafiles.


Creation of raw device for oracle table Space datafiles. (Unix Team Activity)

Recently the following storage has been created (on UAT):
/dev/sdao
/dev/sdap

Each of the above raw devices is hosted from the XP1024 storage array, and can accommodate 5 x 8gb devices to be allocated to the database.

The following instructions assume that the user is root, and the oracle environments are fully down.

1)     Partition the new devices using fdisk following below partition table for cylinder guidance, repeating for all new devices sdao and sdap, start on serverdb1:

# fdisk /dev/sdao

Disk /dev/sdao: 42.9 GB, 42949672960 bytes
255 heads, 63 sectors/track, 5221 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

    Device Boot      Start         End      Blocks   Id  System
/dev/sdao1               1        1045     8393931   83  Linux
/dev/sdao2            1046        2090     8393962+  83  Linux
/dev/sdao3            2091        3135     8393962+  83  Linux
/dev/sdao4            3136        5221    16755795    5  Extended
/dev/sdao5            3136        4180     8393931   83  Linux
/dev/sdao6            4181        5221     8361801   83  Linux

And…

Disk /dev/sdap: 44.1 GB, 44197360640 bytes
255 heads, 63 sectors/track, 5373 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

    Device Boot      Start         End      Blocks   Id  System
/dev/sdap1               1        1075     8634906   83  Linux
/dev/sdap2            1076        2150     8634937+  83  Linux
/dev/sdap3            2151        3225     8634937+  83  Linux
/dev/sdap4            3226        5373    17253810    5  Extended
/dev/sdap5            3226        4300     8634906   83  Linux
/dev/sdap6            4301        5373     8618841   83  Linux

2)     Once the above partitions tables have been added and written to serverdb1, go to serverdb2 and fdisk the same devices. The partitions tables should already be populated as per serverdb1, just ensure you write the partition tables to commit these changes.

3)     Backup /etc/DATA_RAC_RAW file on serverdb1 and serverdb2 and edit /etc/DATA_RAC_RAW to reflect the addition of the new devices, e.g.

# cp /etc/DATA_RAC_RAW /etc/DATA_RAC_RAW.preCMxxxxx

Append the following new entries in /etc/DATA_RAC_RAW onto the end of the existing files

/dev/eudata/unused24_8g:/dev/sdao1:c:162:266:8010
/dev/eudata/unused25_8g:/dev/sdao2:c:162:267:8010
/dev/eudata/unused26_8g:/dev/sdao3:c:162:268:8010
/dev/eudata/unused27_8g:/dev/sdao5:c:162:269:8010
/dev/eudata/unused28_8g:/dev/sdao6:c:162:270:8010
/dev/eudata/unused29_8g:/dev/sdap1:c:162:271:8010
/dev/eudata/unused30_8g:/dev/sdap2:c:162:272:8010
/dev/eudata/unused31_8g:/dev/sdap3:c:162:273:8010
/dev/eudata/unused32_8g:/dev/sdap5:c:162:274:8010
/dev/eudata/unused33_8g:/dev/sdap6:c:162:275:8010


4)     For each newly added device, make the character devices on serverdb1 and serverdb2

Using the above devices (repeat for all new devices), example:

# mknod /dev/eudata/unused24_8g c 162 266
# chown oracle:dba /dev/eudata/unused24_8g

Note that the minor number (266 in this case) must be unique in the OS and therefore must be incremented with each new device, 266…267… as per the above entries in the /etc/DATA_RAC_RAW file

mknod /dev/eudata/unused24_8g c 162 266
mknod /dev/eudata/unused25_8g c 162 267
mknod /dev/eudata/unused26_8g c 162 268
mknod /dev/eudata/unused27_8g c 162 269
mknod /dev/eudata/unused28_8g c 162 270
mknod /dev/eudata/unused29_8g c 162 271
mknod /dev/eudata/unused30_8g c 162 272
mknod /dev/eudata/unused31_8g c 162 273
mknod /dev/eudata/unused32_8g c 162 274
mknod /dev/eudata/unused33_8g c 162 275

5)     Bind new raw devices on both nodes, serverdb1 first, then serverdb2

Using the above example device (repeat for all new devices):

# raw /dev/eudata/unused24_8g /dev/sdao1

raw /dev/eudata/unused25_8g /dev/sdao2
raw /dev/eudata/unused26_8g /dev/sdao3
raw /dev/eudata/unused27_8g /dev/sdao5
raw /dev/eudata/unused28_8g /dev/sdao6
raw /dev/eudata/unused29_8g /dev/sdap1
raw /dev/eudata/unused20_8g /dev/sdap2
raw /dev/eudata/unused31_8g /dev/sdap3
raw /dev/eudata/unused32_8g /dev/sdap5
raw /dev/eudata/unused33_8g /dev/sdap6

-- At this point we have successfully added the new devices to Linux. The devices (“unused*”) will be ready to allocate when necessary, and can be allocated without any disruption to the Oracle environment as steps 1-5 have been completed.

6)     Release the system to the dba’s to add the new devices to oracle and test.

Monday, 17 September 2012

Linux Command History Advanced Features

Linux Command History Advanced Features
“History” command is a very important command in Linux to check the last executed commands in your system. We can use “history” command in some advanced manner with using some extra functionality. You can find this command more enjoyable by using following document.
1.    Display Time Format using HISTSIZEFORMAT

When you run simple “history” it displays only number of command and last running command. For auditing purpose the time for running command is important. Timestamp can be added in history command as shown below.

# export HISTTIMEFORMAT="%F %T "
# history | more
   1  2012-09-12 10:48:00 ls
   2  2012-09-12 10:48:07 history
   3  2012-09-12 10:48:24 ls -ltr
   4  2012-09-12 10:54:57 ls
   5  2012-09-12 10:55:05 ls -ltr
   6  2012-09-12 10:55:22 cat ff_unix

2.    Search the history using Control+R

When you’ve already executed a very long command, you can simply search history using a keyword and re-execute the same command without having to type it fully. Press Control+R and type the keyword. In the following example, I searched for red, which displayed the previous command “cat /etc/redhat-release” in the history that contained the word red.In the following example, I searched for red, which displayed the previous command “cat /etc/redhat-release” in the history that contained the word red.
# [Press Ctrl+R from the command Prompt, which will display reverse –i-search prompt.]
(reverse-i-search)`red': cat /etc/redhat-release
[Note: Press enter when you you see command, which will execute from history.]

[root@qmailprd ~]# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.2 (Santiago)

Sometimes you want to edit a command from history before executing it. For e.g. you can search for httpd, which will display service httpd stop from the command history, select this command and change the stop to start and re-execute it again as shown below.
# [Press Ctrl+R from the command prompt,which will display the reverse-i-search prompt]
(reverse-i-search)`httpd': service httpd stop
[Note: Press either left arrow or right arrow key when you see your
command, which will display the command for you to edit, before executing it]
# service httpd start



3.    Repeat previous command quickly using 4 different methods
Sometime you may end up repeating the previous commands for various reasons. Following are the 4 different ways to repeat the last executed command.
1.    Use the up arrow to view the previous command and press enter to execute it.
2.    Type !! and press enter from the command line
3.    Type !-1 and press enter from the command line.
4.    Press Control+P will display the previous command, press enter to execute it

4. Execute a specific command from history

In the following example, If you want to repeat the command #998, you can do !998 as shown below
  997  vi pop3d-ssl
  998  pwd
  999  openssl s_client -connect localhost:993 -quiet
 1000  history
 1001  cat /etc/issue
 1002  cat /etc/redhat-realease
 1003  history
[root@qmailprd ~]# !998
pwd
/root

5. Execute previous command that starts with a specific word

Type ! followed by the starting few letters of the command that you would like to re-execute. In the following example, typing !ps and enter, executed the previous command starting with ps, which is ‘ps aux | grep http’.
[root@qmailprd ~]# !ps
ps -ef | grep http
root      1830     1  0 Aug03 ?        00:00:35 /usr/sbin/httpd
apache   22502  1830  0 Sep16 ?        00:00:00 /usr/sbin/httpd
apache   22503  1830  0 Sep16 ?        00:00:00 /usr/sbin/httpd

6. Control the total number of lines in the history using HISTSIZE

Append the following two lines to the .bash_profile and relogin to the bash shell again to see the change. In this example, only 1500 command will be stored in the bash history.
# vi ~/.bash_profile
HISTSIZE=1500
HISTFILESIZE=1500
 

7. Change the history file name using HISTFILE

By default, history is stored in ~/.bash_history file. Add the following line to the .bash_profile and relogin to the bash shell, to store the history command in .commandline_warrior file instead of .bash_history file. I’m yet to figure out a practical use for this. I can see this getting used when you want to track commands executed from different terminals using different history file name.
# vi ~/.bash_profile
HISTFILE=/root/.commandline_warrior
 

8. Eliminate the continuous repeated entry from history using HISTCONTROL

In the following example pwd was typed three times, when you do history, you can see all the 3 continuous occurrences of it. To eliminate duplicates, set HISTCONTROL to ignoredups as shown below.
# pwd
# pwd
# pwd
# history | tail -4
44  pwd
45  pwd
46  pwd [Note that there are three pwd commands in history, after
executing pwd 3 times as shown above]
47  history | tail -4
 
# export HISTCONTROL=ignoredups
# pwd
# pwd
# pwd
# history | tail -3
56  export HISTCONTROL=ignoredups
57  pwd [Note that there is only one pwd command in the history, even after
executing pwd 3 times as shown above]
58  history | tail -4
 

9. Erase duplicates across the whole history using HISTCONTROL

The ignoredups shown above removes duplicates only if they are consecutive commands. To eliminate duplicates across the whole history, set the HISTCONTROL to erasedups as shown below.
# export HISTCONTROL=erasedups
# pwd
# service httpd stop
# history | tail -3
38  pwd
39  service httpd stop
40  history | tail -3
 
# ls -ltr
# service httpd stop
# history | tail -6
35  export HISTCONTROL=erasedups
36  pwd
37  history | tail -3
38  ls -ltr
39  service httpd stop
[Note that the previous service httpd stop after pwd got erased]
40  history | tail -6
 

10. Force history not to remember a particular command using HISTCONTROL

When you execute a command, you can instruct history to ignore the command by setting HISTCONTROL to ignorespace AND typing a space in front of the command as shown below. I can see lot of junior sysadmins getting excited about this, as they can hide a command from the history. It is good to understand how ignorespace works. But, as a best practice, don’t hide purposefully anything from history.
# export HISTCONTROL=ignorespace
# ls -ltr
# pwd
#  service httpd stop [Note that there is a space at the beginning of service,
to ignore this command from history]
# history | tail -3
67  ls -ltr
68  pwd
69  history | tail -3

 

11. Clear all the previous history using option -c

Sometime you may want to clear all the previous history, but want to keep the history moving forward.
# history -c

12. Subtitute words from history commands

When you are searching through history, you may want to execute a different command but use the same parameter from the command that you’ve just searched.
In the example below, the !!:$ next to the vi command gets the argument from the previous command to the current command.
# ls anaconda-ks.cfg
anaconda-ks.cfg
# vi !!:$
vi anaconda-ks.cfg
In the example below, the !^ next to the vi command gets the first argument from the previous command (i.e cp command) to the current command (i.e vi command).
# cp anaconda-ks.cfg anaconda-ks.cfg.bak
anaconda-ks.cfg
# vi  !^
vi anaconda-ks.cfg

 

 

13. Substitute a specific argument for a specific command.

In the example below, !cp:2 searches for the previous command in history that starts with cp and takes the second argument of cp and substitutes it for the ls -l command as shown below.
# cp ~/longname.txt /really/a/very/long/path/long-filename.txt
# ls -l !cp:2
ls -l /really/a/very/long/path/long-filename.txt
In the example below, !cp:$ searches for the previous command in history that starts with cp and takes the last argument (in this case, which is also the second argument as shown above) of cp and substitutes it for the ls -l command as shown below.
# ls -l !cp:$
ls -l /really/a/very/long/path/long-filename.txt

14. Disable the usage of history using HISTSIZE

If you want to disable history all together and don’t want bash shell to remember the commands you’ve typed, set the HISTSIZE to 0 as shown below.
# export HISTSIZE=0
# history
# [Note that history did not display anything]

15. Ignore specific commands from the history using HISTIGNORE

Sometimes you may not want to clutter your history with basic commands such as pwd and ls. Use HISTIGNORE to specify all the commands that you want to ignore from the history. Please note that adding ls to the HISTIGNORE ignores only ls and not ls -l. So, you have to provide the exact command that you would like to ignore from the history.
# export HISTIGNORE="pwd:ls:ls -ltr:"
# pwd
# ls
# ls -ltr
# service httpd stop
 
# history | tail -3
79  export HISTIGNORE="pwd:ls:ls -ltr:"
80  service httpd stop
81  history
[Note that history did not record pwd, ls and ls -ltr]