Friday, August 6, 2010

Backing Up a django Web Server

I have a webserver I want to backup weekly and keep 4 weeks of backup history.
The webserver runs CentOS 5.4 and Django.
In the event of a server crash I'd like to be able to recover my website rather easily.  I figure it would be relatively easy to reinstall the OS and install the applications.  Then all I would need to do is restore the configuration files and the database.

Assumptions:
You have django installed and working
$DBDUMPDIR = where ever you want the Database Dump files to go
$BKUPDIR = where ever you want the Backup files to go.  Note:  This backup directory could be a remote server such as an NFS mount or SMB mount.  This is suggested so if this server crashes, your backups would be on another server.
Edit the scripts below to for "your" appropriate directories and file names.



Here are the four files I will need to backup:
*  /etc/httpd/conf/httpd.conf
*  /etc/httpd/conf/mysite.conf
*  /etc/www/django
*  $DBDUMPDIR/data.json

I created a script called dumpfiles.bash and put it in root's bin directory "/root/bin/dumpfiles.bash".
Make sure that permissions are right to be able to execute the file.
chmod 770 /root/bin/dumpfiles.bash

Here is the script:
----- start of script -----
#!/bin/bash
#
# SCRIPT: dumpfiles.bash
# AUTHOR: Bob
# DATE: 07/01/2010
# REV: 1.blah
#
# PURPOSE: This script is used to backup webserver specific data
#
# set -x # Uncomment to debug this script
#
# set -n # Uncomment to check the script.s syntax
#        # without any execution. Do not forget to
#        # recomment this line!
#
####################
# Define Variables #
####################
# Capture the shell script file name
THIS_SCRIPT=$(basename $0)
#
# Define the start time of the script
STARTTIME=`date +%T`
#
#Set Backup and DB Dump Directories
#Change the directories below to match your environment
BKUPDIR=/mnt/backup/webserver
DBDUMPDIR=/root
#
##################
# Increment Backups #
##################
rm -f $BKUPDIR/bkup4.tar.gz
mv -f
$BKUPDIR/bkup3.tar.gz $BKUPDIR/bkup4.tar.gz
mv -f
$BKUPDIR/bkup2.tar.gz $BKUPDIR/bkup3.tar.gz
mv -f
$BKUPDIR/bkup1.tar.gz $BKUPDIR/bkup2.tar.gz
#
###################
# Dump Database #
###################
# export PYTHONPATH for dumpdata script
export PYTHONPATH='/var/www/django':'/var/www/django/apps'
#
#Change Directories to /var/www/django/mysite
cd /var/www/django/mysite
#
#Backup the DJango database and files to a flat file
python manage.py dumpdata > $DBDUMPDIR
/data.json
#
#Get out of the /var/www/django/mysite directory
#Let us go home
cd /root

#
###############################
# Backup and compress important files #
###############################
tar cvfz $BKUPDIR/bkup1.tar.gz /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/mysite.conf /var/www/django $DBDUMPDIR/data.json
----- end of script -----

I want to schedule a weekly backup so I'll use root's cron to do this.
Edit root's cron (assuming you are logged in as root).

Enter the following line to root's cron.
0 4 * * 1 /root/bin/dumpfiles.bash

This will run the script every Monday morning at 4:00 AM.
Now each time the script runs bkup1.tar.gz will be created.  If it already exists the old files will be incremented up to the number 4 giving you four weeks of backup files.

In the event of a disaster and you rebuilt a new server, you'd untar the backup files and copy the files back to their appropriate place and you the manage.py script to restore the django database.

Hope this helps someone out there.

Tuesday, June 29, 2010

Expect - Using expect to Automate Processes or Generate Reports

I have 51 Linux servers that I manage (soon to grow to well over 70).  Over the past year the company I am with has moved and we have redesigned the network (a few times).  During this redesign we changed which servers provide DNS and NTP services.  I like to think I am a pretty thorough person and believe I updated all 51 servers with the correct DNS and NTP IP Addresses, but I also want to validate my thoroughness as a sanity check and a c.y.a. BTW - I use IP Addresses for the DNS and NTP settings just in case DNS is unavailable

I really don't want to log in to 51 different servers and verify the contents of 3 different configuration files on each of these servers.  It would be nice if I could spend a few minutes writing a script that could poll each server and write out a report that I could review.  So that is just what I did.

A few things I needed to have in place before I got started.
1.  A linux account defined on all 51 servers that has remote SSH permissions and the ability to read the three configuration files I am interested in.  I don't allow root to remotely SSH to any server.
2.  On the computer I will be running the script from (my Linux laptop) a linux utility called expect.
3.  A list of all 51 servers in a text file.

Number 1 is easy as I have a service account (we'll call it saccount) that has access to every server but has very little permissions (but enough to read the files I am interested in).  For number 2 I had to install expect on my laptop which is running a flavor/type-of Redhat Linux.  Expect should be available in your repository for updates.  Number 3 was easy too.  I had a file containing all of my Linux servers.

I ended up with 3 files (not including the report file generated after running the script/s).
File 1:  serverlist.txt - this file contains a list of my servers.  One server name per line.  Example:
serverA
serverB
serverC
server1
server2
server3
   you get the idea...

File 2:  dnsntpreport.exp - you can call it anything you want.  Just make sure it is executable.  the contents of the files are as follows:

   #!/usr/bin/expect -f
   spawn ./dnsntpreport.ksh
   expect {
   "*re you sure you want to continue connecting (yes/no)?"
   {send -- "yes\r\n"
   exp_continue}
   "*assword:*"
   {send "#######\r\n"
   exp_continue}
   }
   exit

where you see #######, you would put the actual password for the user you are using.  This script will watch for certain prompts and answer them with the text you entered automatically.

File 3:  dnsntpreport.ksh - you can call it whatever you want but notice that the above script will call this script so if you change the file name you will need to edit the script above.  The contents of this script are as follows:

   #!/bin/ksh
   for line in $(cat ./serverlist.txt)
   do
   echo -e "\n###$line###" >> dnsntp_report.txt
   echo -e "/etc/resolv.conf file" >> dnsntp_report.txt
   ssh saccount@$line grep -e "10\." /etc/resolv.conf >> dnsntp_report.txt
   echo -e "\n/etc/ntp.conf file" >> dnsntp_report.txt
   ssh saccount@$line grep -e "10\." /etc/ntp.conf >> dnsntp_report.txt
   echo -e "\n/etc/ntp/step-tickers file" >> dnsntp_report.txt
   ssh saccount@$line grep -e "10\." /etc/ntp/step-tickers >> dnsntp_report.txt
   echo -e "###" >> dnsntp_report.txt
   done

So what is going on here?  File 3 will SSH to a server and look through three files for IP Addresses starting with a "10" and record its finds to a file called dnsntp_report.txt.  During our moves and reconfigures the first octet has remained "10" but the others have changed.  Of course when you SSH to a server (assuming you do not have Passwordless SSH setup) you are sometimes prompted whether you trust the key and then for a password.  This is where File 2 comes in and is actually the file you execute from the command-line since it will call File 3.  This file (File 2) will look for two specific prompts and answer them automatically so we don't have to respond 51 or more times.  Obviously, where you see "saccount" in the above script replace with the account you are using.  Remember, the password is stored in File2.

Assuming you have all three files in the same directory and File 2 and File 3 executable all you need to do is run File 2 from the command line.  After the script runs you should have a text file called dnsntp_report.txt that indicates the settings you were (or in this case I was) interested in.

I hope this helps someone else out there.

Wednesday, June 2, 2010

A Quick and Dirty Virtual IP (VIP) Address for HA Purposes

A virtual IP address?  Why do I want one of those?  I have two servers (not clustered) set up to run an application.  High Availability is important, but I do not need automatic failover.  So I have the application run on a specific IP address on Server-A while the application is off on Server-B.  In the event Server-A needs to be brought down for maintenance or has an issue, I want to be able to start the application on Server-B with the same IP Address.


Here is the quick and dirty way to do it.
Assumption:  IP Network is 192.168.1.0/255.255.255.0
We will pick 192.168.1.100 for our Virtual IP (VIP) Address


On Server-A:
1.  Create a file called start_adm_vip.sh in /usr/local/sbin
Its contents should be as follows:
/sbin/ifconfig eth0:1 192.168.1.100 netmask 255.255.255.0
/sbin/arping -q -U -c 3 -I eth0 192.168.1.100

2.  Create a file called shutdown_adm_vip.sh
Its contents should be as follows:
/sbin/ifconfig eth0:1 down

3.  Modify permissions on these files so they are executable. 750 should suffice.
chmod 750 *adm_vip.sh

4.  Edit the /etc/hosts file to add a friendly name to the VIP.  Obviously use the name and the IP Address you choose here:
192.168.1.100     appadm.mydomain.net     appadm

5.  Copy the two scripts you just created to Server-B and place them in /usr/local/sbin as well.

On Server-B:
1.  Edit the /etc/hosts file to add a friendly name to the VIP.  Obviously use the name and the IP Address you choose here:

192.168.1.100     appadm.mydomain.net     appadm

Starting the VIP

Now run the script "start_adm_vip.sh" on Server-A.  You should be able to ping "appadm" from both Server-A and Server-B.  Do not go and run the start script on Server-B.  If you do you will have duplicate IP Addresses on the network.  If you want to move the VIP to Server-B, shut it down on Server-A first.

Shutting the VIP down
If you want to manually move the VIP to Server-B you need to shut it down on Server-A first.
On Server-A run the "shutdown_adm_vip.sh".  Now "appadm" should not be pingable from either server.

Go to Server-B and run the script "start_adm_vip.sh".  "appadm" should now be live on Server-B and pingable from both Server-A and Server-B.


Like I said, this is a quick and dirty way to have a VIP.  Hope this helps someone out there.

Thursday, April 29, 2010

snmpd Information Filling up the /var/log/messages File

I am using net-snmp on my linux servers so cacti can poll for data and graph statistics.  I noticed that the /var/log/messages file was filling up with snmpd messages.  All of which were merely informational and benign.  I know snmpd works and is configured properly and those log messages in my /var/log/messages file makes it hard to find anything useful in it.

I found that (at least in the version of net-snmp that I am using) debug logging is turned on by default.  Well, I don't want debug level logging.  In fact I don't want any logging for snmpd to go to my /var/log/messages file.

I run Oracle Enterprise Linux and Ubuntu.

On any flavor of Red Hat Enterprise Linux (example:  RHEL, OEL, CentOS) modify the /etc/sysconfig/snmpd.options file.  If it doesn't exist, create it.

The contents of that file should be changed to this:

     # snmpd command line options
     OPTIONS="-Lf /dev/null -p /var/run/snmpd.pid -a"

This will turn off all logging for snmpd.  Remember to restart snmpd for the changes to take affect.
     service snmpd restart

On Ubuntu edit the /etc/init.d/snmpd file and change the line that looks like this:
     SNMPDOPTS='-Lsd -Lf /dev/null -p /var/run/snmpd.pid'
to this
     SNMPDOPTS='-Lf /dev/null -p /var/run/snmpd.pid'

That's it.  Remember to restart snmpd for the changes to take affect
     /etc/init.d/snmpd restart

Wednesday, February 24, 2010

Interactive Tape Backups using TAR and Linux

I sometimes want to run an on-demand backup of either a particular directory or file system.  I wrote an interactive script to do this and thought I would share it.
Assumptions:
1.  You have a tape device attached to your Computer or Server.
2.  You know what device your tape drive is.  Example: /dev/st0
3.  You have the mt-st package installed to manage the tape device.
4.  The tape you are using will be overwritten.
5.  You copy the contents of the script below in to a utility like notepad and check the contents.  Then copy from there in to a script called (whatever you want).
6.  Pay close attention to the command that starts like this:  TAPECHK=$(mt  It show up correctly in this post but if you cut and past the script in to notepad the lines do not match.  Edit it so it looks like it does here in the post.
7.  You make the script executable.
8.  I placed the script in /usr/local/sbin but you can put it where ever it make sense to you.

Here is the script:

#!/bin/bash
#
# SCRIPT: Interactive_2_tape.bash
# AUTHOR: Bob
# DATE: 02/24/2010
# REV:
#
# PURPOSE: This script is used to backup files
# from $SOURCE to $TAPEDEV
#
# set -x # Uncomment to debug this script
#
# set -n # Uncomment to check the script.s syntax
#        # without any execution. Do not forget to
#        # recomment this line!
#
####################
# Define Variables #
####################

# Capture the shell script file name
THIS_SCRIPT=$(basename $0)

# Define the start time of the script
STARTTIME=`date +%T`

# Define current directory to return to at end of script
CURRENTDIR=$PWD

# Ask for the source of the backup
echo "What directory or filesystem do you want to backup?"
echo "Type the directory in this format /dir1/dir2 followed by [ENTER]:"
read SOURCE
echo "Using $SOURCE as the source directory you want to backup."

# Ask for tape device
TAPEDEV="/dev/st0"
echo "I assume your tape device is $TAPEDEV"
read -p "Am I correct? yes/no: "
if [ "$REPLY" = "no" ]; then
     echo "What is your tape device? "
     read TAPEDEV
     echo "Using $TAPEDEV as your tape device."
else
     echo "Using $TAPEDEV as your tape device."
fi


################
# Main Section #
################

# Verify there is a tape in the
# drive and rewind the tape
TAPECHK=$(mt -f $TAPEDEV rewind 2>&1 1>/dev/null)
# If there is no tape tell me and exit out
#  If the mt command return any data then there is an error

#  Check the results of the mt command
if [ "$TAPECHK" != "" ]; then
     echo $TAPECHK
     echo "Check to see if there is a tape in the drive or if the device you entered is valid."
     exit
fi

# If we made it here, there is a tape in the drive and it has rewinded.
# Change to the directory to be backed up
cd $SOURCE
echo "Changing to the $SOURCE directory."

# Back up data
tar cvf $TAPEDEV .

# Rewind the tape again
mt -f $TAPEDEV rewind

# Change back to the directory from where you came
cd $CURRENTDIR
echo "Changing back to the directory you started from: $CURRENTDIR"
# Define the end time of this script
ENDTIME=`date +%T`

# Display the start and end time of this script
echo "$THIS_SCRIPT began at $STARTTIME and finished at $ENDTIME"

exit
#################
# End of Script #
#################


I hope this helps others out there trying to do the same thing.

Monday, February 15, 2010

Using tar to Copy a Large File into a Tight Space

I do a lot of work with virtual machine images.  I ran in to a situation where I wanted to copy a file called System.img from one server to another and even though I knew I had enough room to do it, I would get messages stating that there was not enough space.  What in the world was going on?  The file system I wanted to copy the file to was 33G in size.  The file was just under 33G in size.  I knew it should fit.  I knew this because the file system this file is coming from is also 33GB in size (same identical size).  When it was all said and done I should of had about 150M of free space according to the source.

I tried FTP, SCP, and various other mechanisms to copy the file from the one server to the other.  No joy.
So I copied the file to the destination server but to a different and larger file system.  That obviously was successful, but I still wanted it on my 33G file system.  So I tried copying the file locally from the larger file system to the 33G file system.  No joy again... I got a message after a few minutes stating there was not enough space, and the process errored out.

I found a solution!  Now, to be honest, I do not know why it works, but it does.

Assumptions: You are in the directory the System.img file is located.  The file resides on the same server you are copying to.  You have done the math and according to the calculator the file will fit on the destination file system.

Run this command with the appropriate path of your destination.

Note:  The following command is all on one line.
# tar cvf - System.img | ( cd /destination file system/destination folder/;tar xvf - )

Works like a charm.  I have used this little gem a dozen times in the past few months.

This should be obvious but...  Remember, you can not copy/place a file that is larger than the space available on the destination.  Hope this helps others out there.

Tuesday, January 12, 2010

Filesystem Replication Using rsync and SHH

There are many reasons you may need to replicate a file system.  My reason was for DR purposes.  In a previous post I set up Passwordless SSH sessions between two systems.  This is a requirement if you want to sync file systems on an automated schedule.  I looked on the web for a script that would do what I wanted and I could not find something that met my needs.  So I wrote the script below.  To give credit where credit is due, I borrowed from some ideas and code from Randal K. Michael, author of Mastering UNIX Shell Scripting.  I placed the script below in /usr/local/bin directory on the "source" node and called it fsrsync.bash.  This script will replicated a designated filesystem from a source node to two different nodes after confirming they are "alive".  I used rsync because after the initial sync, future replications are much faster since only update and/or changes are sent and not the entire filesystem.

Here is the script below.  Highlight the contents and select copy.
Note:  When you grab the test here and paste it, do a sanity check on the text to verify the formatting has not changed.
Edit/create /usr/local/bin/fsrsync.bash and paste in the contents.
# vi /usr/local/bin/fsrsync.bash

Script starts below.

#!/bin/bash
#
# SCRIPT: fsrsync.bash
# AUTHOR:
# DATE:
# REV:
#
# PURPOSE: This script is used to replicate the
# /somedir/test filesystem from Node A to Node B and C
#
# set -x # Uncomment to debug this script
#
# set -n # Uncomment to check the script.s syntax
#        # without any execution. Do not forget to
#        # recomment this line!
#
##############################################
# DEFINE FILES AND GLOBAL VARIABLES HERE
##############################################

# Define the target machines to copy data to.
# To specify more than one host enclose the
# hostnames in double quotes and put at least
# one space between each hostname
#
# EXAMPLE: MACHINE_LIST="fred yogi booboo"

MACHINE_LIST="nodeB nodeC"

# Capture the shell script file name

THIS_SCRIPT=$(basename $0)

# The FS_PATTERN variable defines the regular expression
# matching the filesystems we want to replicate with rsync.
# Example:  FS_PATTERN="/home"

FS_PATTERN="/somedir/test"

# Query the system for the hostname

THIS_HOST=$(hostname)

##############################################
# BEGINNING OF MAIN
##############################################

# Comfirm the nodes are alive and replicate
# the filesystems.
echo -e "\n####################################################\n"
echo -e "$THIS_SCRIPT started execution $(date)\n"
echo -e "Verifying the node is alive..."

for M in $MACHINE_LIST
do
    echo "Pinging $M..."
    ping -c1 $M >/dev/null 2>&1
    if (( $? != 0 ))
    then
        echo -e "ERROR: $M host is not pingable...cannot continue..."
        echo -e "...EXITING...\n"
        echo -e "####################################################"
        exit 2
    else
        echo -e "$M is alive... Starting rsync process!\n"
        echo -e "Replicating $FS_PATTERN/ from $THIS_HOST to $M\n"
        #The rsync command is all on one line although it doesn't appear so here.  This comment can be removed.
        rsync -aqz --delete -e ssh $FS_PATTERN/ root@$M:$FS_PATTERN
    fi
echo -e "$THIS_SCRIPT finished execution $(date)\n"
echo -e "####################################################"
done

###############################################
# END OF SCRIPT
###############################################

Make sure you make the file executable.
# chmod 754 /usr/local/bin/fsrsync.bash

You can manually run the file by simply running this command as a user with the appropriate rights.
# /usr/local/bin/fsrsync.bash

Do you want to schedule this script to replicate the file system every 5 minutes and log results?  Add the following entry to the crontab.
# crontab -e
0,5,10,15,20,25,30,35,40,45,50,55 * * * *     /usr/local/bin/fsrsync.bash 2>&1 >> /var/log/fsrsync.log


Do you want to rotate your log file (assuming you use logrotate)?  If so create a file in /etc/logrotate.d/ called fsrsync.
# vi /etc/logrotate.d/fsrsync

The contents of the file should look like this:
/var/log/fsrsync.log {
        weekly
        rotate 4
        nocompress
        missingok
}

I hope this helps someone out there.

PS:  If you want to test logrotate without having to wait a week you can do the following.
# /usr/sbin/logrotate -v /etc/logrotate.d/fsrsync
This will give you details on what it will do and rotate the log if needed.  If you want to force a log rotation, do the following.
# /usr/sbin/logrotate -f /etc/logrotate.d/fsrsync