Tuesday, March 8, 2011

Cisco VPN Without A Cisco Client

A while ago I posted a blog outlining Cisco VPN Installation. This entry is how to get a VPN connection up and running without that software using vpnc instead.

Step one is to get vpnc. Most distributions seem to have a pre-built package so have a look around. For SuSE or RedHat it looks like this:
SuSE
# zypper install vpnc
RedHat
# yum install vpnc
Step two is to get a copy of your .pcf file. If you are using the Cisco VPN client, it is located under /etc/opt/cisco-vpnclient/Profiles/.pcf. This has three important pieces of information.
  • The host you are connecting to (Host=)
  • A group name (GroupName=)
  • An encoded group password (enc_GroupPwd=)
Now, vpnc won't take an encoded password file so you will need to decrypt it first. There is a handy utility for this which should have come in your vpnc package, aptly named cisco-decrypt. If its not included you can download it from here. To run it you will need to either cut and paste the hideously long HEX string after enc_GroupPwd= or just run the command below.
# grep enc_GroupPwd name.pcf | awk -F= '{print $2}' | xargs cisco_decrypt
Once you have this you can create a vpnc.conf file like this one
# vi /etc/vpnc/vpnc.conf
IPSec gateway host_or_ip_from_Host=
IPSec ID group_from_GroupName=
IPSec secret output_from_cisco_decrypt

e.g.
IPSec gateway 44.24.21.2
IPSec ID IPSec-Grp
IPSec secret mysecret
Xauth username myID
If you don't have a group name you should be able to use 'General' instead. You can also add Xauth username your_ID and Xauth password your_password as shown in the example. However, this file is stored in clear text so it is probably best to leave the password option out. VPNC will prompt you for any values not present.

Once that is all done, you can connect and disconnect like this
# vpnc /etc/vpnc/vpnc.conf
  Enter username for _host_: _id_
  Enter password for _id_@_host_: 
  Connect Banner:
  | 
  | Secure VPN Server
  | Authorized Users Only
  | Successfully Authenticated
  | 

  VPNC started in background (pid: 7726)...

# ifconfig
tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  
          inet addr:ip  P-t-P:ip  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1412  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500 
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

When you're done
# vpnc-disconnect
Terminating vpnc daemon (pid: 7726)
Nice and simple. Since it uses built in kernel modules, no more messing about with compiling, kernel versions or outdated code from Cisco.

Sunday, January 9, 2011

Cross Server Multipath

I was asked to come up with a method to compare multipath devices across an Oracle RAC cluster to ensure they are consistent. Beyond this there was one catch; it had to be run as a regular user. I would have normally run a multipath command but unfortunately that isn't available without elevated privileges. So my solution looks at /etc/multipath.conf, which is readable by a user, compare the entries across all nodes, and output a table at the end. You can see an example of the output in the initial comments.

#!/bin/bash                                                                                                                                                                         
# Script Information
# Version: 1.0
# Created By: Michael England
                                                                                    
# Parses /etc/multipath.conf on any number of nodes (with ssh) and produces a report comparing all of the entries
# e.g.
# WWID                                    node1                         node2                         node3                         Status
# 360060e8005be08000000be08000011ab       apps_001_40g                  --                            --                            INVALID
# 360060e8005be08000000be08000011ac       apps_002_40g                  --                            --                            INVALID
# 360060e8005be08000000be0800004000       ora_shared_data_001_407g      ora_shared_data_001_407g      ora_shared_data_001_407g      OK
# 360060e8005be08000000be0800004001       ora_shared_data_002_407g      ora_shared_data_002_407g      ora_shared_data_002_407g      OK

######
### function read_multipath
### reads a file looking for wwid and alias pairs
### e.g.
### multipath {
###     wwid    36006016015a019004e9820d8b56cde11
###     alias   vote_disk1
### }
### becomes
###     wwid 36006016015a019004e9820d8b56cde11 alias vote_disk1
### if it is missing a wwid or alias that part will be blank
### e.g.
###     wwid 36006016015a019004e9820d8b56cde11
### The first entry will be blank as we increment COUNT on the first multipath
######
function parse_multipath {
        COUNT=0
        unset MPATH_ENTRIES
        oldIFS=$IFS
        IFS=$'\n'
        for line in echo $NODE_MPATH_RESULT
        do
                # skip anything beginning with a comment
                # after bash 3.2 we can't use "" anymore on right hand side
                if [[ $line == \#* ]]
                then
                        continue
                fi
                # look for multipath keyword and increment array counter
                # \ .* excludes multipaths
                if [[ $line =~ multipath\ .* ]]
                then

                        (( COUNT++ ))
                # anything that starts with wwid or alias and add it to the current array element
                elif [[ $line =~ wwid* ]] || [[ $line =~ alias* ]]
                then
                        MPATH_ENTRIES[$COUNT]=`echo "${MPATH_ENTRIES[$COUNT]} $line"`
                fi
        done
        IFS=$oldIFS
}

######
### function search_wwid
### Args: 
###     $1 search key
### Searches the WWID_MAP array for a given key and returns the array position of that element
######
function search_wwid {
        key="$1"
        for index in ${!WWID_MAP[@]}
        do
                if [[ ${WWID_MAP[$index]} =~ $key ]]
                then
                        echo $index
                        # exit the function
                        exit
                fi
        done
        echo -1
}

######
### function search_node
### Args:
###     $1 search key
### Searches the NODE_ARRAY array for a given key and returns the array position of that element
######
function search_node {
        key="\<$1\>"
        for index in ${!NODE_ARRAY[@]}
        do
                if [[ ${NODE_ARRAY[index]} =~ $key ]]
                then
                        echo $index
                        exit
                fi
        done
        echo -1
}

######
### function assign_wwid
### populates WWID_MAP array with a common view to all nodes multipath entries
### reads from the current MPATH_ENTRIES which should be the output from parse_multipath for one node only
### array will look like the following
### WWID        ALIAS_node1     ALIAS_node2     ALIAS_node3     etc
### it does not include any status information
######
function assign_wwid {
        for index in ${!MPATH_ENTRIES[@]}
        do
                # count the number of items starting from 1 (wc -w is word)
                ITEM_COUNT=`echo ${MPATH_ENTRIES[index]} | wc -w`
                # make sure our entry is 4 words long (wwid  alias ), this is really an error condition as every wwid should have an alias
                # if it doesn't pad it with "--"
                for (( i=$ITEM_COUNT; $i <= 4; i++ ))
                do
                        MPATH_ENTRIES[$index]="${MPATH_ENTRIES[index]} --"
                done

                unset FILLER
                # set the key to the WWID and search the WWID_MAP to see if one already exists
                key=`echo ${MPATH_ENTRIES[$index]} | awk '{print $2}'`
                RETVAL=`search_wwid $key`
                if [[ $RETVAL -lt 0 ]]
                then
                        # this is a new WWID
                        # check to see what node ordinal this is (first, second, third, etc...)
                        # if this isn't the first node we will have to fill in -- for the ones before to indicate this WWID doesn't exist on previous nodes
                        NODE_POSITION=`search_node $1`
                        for (( i=0; $i < $NODE_POSITION; i++ ))
                        do
                                FILLER="$FILLER --"
                        done
                        # tack on a new element with the wwid, and filler required, and then the node alias
                        WWID_MAP[${#WWID_MAP[@]}]=`echo ${MPATH_ENTRIES[index]} | awk '{ print $2, filler, $4 }' filler="$FILLER"`
                else
                        # a WWID already exists, just add on
                        (( NODE_POSITION=`search_node $1` + 1 ))
                        MAP_LENGTH=`echo ${WWID_MAP[RETVAL]} | wc -w`
                        # the node position will be greater than the length if we have a hole... plug it with filler
                        for (( i=$MAP_LENGTH; $i < $NODE_POSITION; i++ ))
                        do
                                FILLER="$FILLER --"
                        done
                        # append any required filler and then the alias for this node
                        WWID_MAP[$RETVAL]=${WWID_MAP[$RETVAL]}\ $FILLER\ `echo ${MPATH_ENTRIES[$index]} | awk '{print $4}'`
                fi
        done
}

######
### function check_status
### -ensures each WWID_MAP is the correct length by first finding the longest entry
###  and then padding all others to that length with --
### -creates a WWID_STATUS array, each element aligns with a WWID_MAP element 
###  it checks if all aliases in WWID_MAP are the same, if so marks a green OK, if not a red INVALID
### WWID_STATUS array will have one entry for each WWID_MAP
###   OK
###   OK
###   INVALID
###   etc
######
function check_status {
        # find the longest element in WWID_MAP
        LONGEST=0
        for index in ${!WWID_MAP[@]}
        do
                LENGTH=`echo ${WWID_MAP[index]} | wc -w`
                if [[ $LENGTH > $LONGEST ]]
                then
                        LONGEST=$LENGTH
                fi
        done
        for index in ${!WWID_MAP[@]}
        do
                # count the number of items in this element
                COUNT=`echo ${WWID_MAP[index]} | wc -w`
                # another way to do this is convert to an array and then count the array elements
                # ARRAY=( $(echo ${WWID_MAP[index]}) )
                # for i in `seq ${#ARRAY[@]} $(( $LONGEST - 1 ))` or for i in `seq 2 $(( ${#ARRAY[@]} - 1))` when math rquired
                # if the array is shorter, pad it
                # longest is reduced by 1 because arrays are 0 based
                for i in `seq $COUNT $(( $LONGEST - 1 ))`
                do
                        WWID_MAP[$index]="${WWID_MAP[$index]} --"

                done

                # recount the element as its size may have just changed
                COUNT=`echo ${WWID_MAP[index]} | wc -w`
                if [ $COUNT -eq 2 ]
                then
                        WWID_STATUS[$index]="\e[0;32mOK\e[0;30m"
                fi
                # for all items starting at 2 (the third item) to the end - 1 (zero based)
                # compare with the item previous (i.e. 3:2, 4:3, 5:4, etc)
                for i in `seq 2 $(( $COUNT - 1))`
                do
                        ARRAY=( $(echo ${WWID_MAP[index]}) )
                        # if they don't match, or this item is "--" mark it as invalid
                        if [[ "${ARRAY[i]}" != "${ARRAY[i-1]}" ]] || [[ "${ARRAY[i]}" = "--" ]]
                        then
                                WWID_STATUS[$index]="\e[0;31mINVALID\e[0;30m"
                                break
                        else
                                WWID_STATUS[$index]="\e[0;32mOK\e[0;30m"
                        fi
                done
        done
}

######
### function exchange
### helper for bubble sort to swap both WWID_MAP and WWID_STATUS entries
######
function exchange {
        local temp=${WWID_MAP[$1]}
        local status_temp=${WWID_STATUS[$1]}
        WWID_MAP[$1]=${WWID_MAP[$2]}
        WWID_MAP[$2]=$temp

        WWID_STATUS[$1]=${WWID_STATUS[$2]}
        WWID_STATUS[$2]=$status_temp
}

######
### function sort_results
### a bubble sort of both WWID_MAP and WWID_STATUS based on a user specified sort field (SORT_FIELD)
### if SORT_FIELD = a digit, uses awk to compare values for that column
### if SORT_FIELD = valid | invalid simply compares the WWID_STATUS array elements to be either > or <
######
function sort_results {
        number_of_elements=${#WWID_MAP[@]}
        (( comparisons = $number_of_elements - 1 ))
        count=1
        while [ "$comparisons" -gt 0 ]
        do
                index=0
                while [ "$index" -lt "$comparisons" ]
                do
                        if [[ $SORT_FIELD = [[:digit:]]* ]]
                        then
                                if [[ `echo ${WWID_MAP[index]} | awk '{print $i}' i=$SORT_FIELD` > `echo ${WWID_MAP[ (( $index + 1 ))]} | awk '{print $i}' i=$SORT_FIELD` ]]
                                then
                                        exchange $index `expr $index + 1`
                                fi
                        elif [[ $SORT_FIELD = "invalid" ]]
                        then
                                if [[ ${WWID_STATUS[index]} > ${WWID_STATUS[`expr $index + 1`]} ]]
                                then
                                        exchange $index `expr $index + 1`
                                fi
                        elif [[ $SORT_FIELD = "valid" ]]
                        then
                                if [[ ${WWID_STATUS[index]} < ${WWID_STATUS[`expr $index + 1`]} ]]
                                then
                                        exchange $index `expr $index + 1`
                                fi
                        fi
                        (( index += 1 ))
                done
                (( comparisons -= 1 ))
                (( count += 1 ))
        done
}

######
### function echo_results
### outputs the collected results in WWID_MAP and WWID_STATUS to the screen
######
function echo_results {
        # put together a header row
        # WWID      Status
        RESULT_SET="WWID"
        for node in $NODE_LIST
        do
                RESULT_SET="$RESULT_SET $node"
        done
        RESULT_SET="$RESULT_SET Status"
        # print the header row, wwid (1st column) is 40 characters wide, everything else is 30
        echo -e $RESULT_SET | awk '{ printf "%-40s", $1 }'
        echo -e $RESULT_SET | awk '{ for (i=2; i<=NF; i++) printf "%-30s", $i }'
        awk 'BEGIN {printf "\n"}'
        echo "---------------------"
        # for each element print the first at 40 characters, all others (colume 2 - NF) at 30, then the status (using echo so the colours work)
        # NF is Number of Fields
        for index in ${!WWID_MAP[@]}
        do
                echo ${WWID_MAP[index]} | awk '{ printf  "%-40s", $1 }'
                echo ${WWID_MAP[index]} | awk '{ for (i=2; i<=NF; i++) printf "%-30s", $i }'
                echo -e "${WWID_STATUS[index]}"
        done
}

######
### function usage
### outputs help message
######
function usage {
        echo -e "Usage: `basename $0` -n {node1,node2,node3,etc} [-sort {field} | -sort_invalid | -sort_valid] [-user {username}]"
        echo -e "\t-n is a node list separated by commas, the script will ssh and read /etc/multipath.conf on each"
        echo -e "\t-sort {field} sorts the output. 0 sorts the WWID number, 1..x sorts for a specific node"
        echo -e "\t-sort_invalid places invalid alias entries at the top"
        echo -e "\t-sort_valid places valid alias entries at the top"
        echo -e "\t-user {username} allows a different username to be used than the one currently logged in"
        exit
}

######
### parse the command line for options
######
if [ -z "$1" ]
then
        usage
fi
until [ -z "$1" ]
do
        case "$1" in
        -n)
                shift
                NODE_LIST=`echo $1 | tr "," " "`
                ;;
        -sort)
                shift
                SORT_FIELD=`expr $1 + 1`
                ;;
        -sort_invalid)
                SORT_FIELD="invalid"
                ;;
        -sort_valid)
                SORT_FIELD="valid"
                ;;
        -user)
                shift
                USERNAME="-l $1"
                ;;
        *)
                usage
                ;;
        esac
        shift
done

# convert NODE_LIST to an array so we can search the position
NODE_ARRAY=( $(echo "$NODE_LIST") )

# for each node in the list
#  - grab its multipath.conf (ssh)
#  - parse out wwid and alias pairs (parse_multipath)
#  - add it to the master WWID list (assign_wwid)
# then fill in any blank holes and the overall status (check_status)
# sort the results as requested (sort_results)
# then output to display (echo_results)
for node in $NODE_LIST
do
        NODE_MPATH_RESULT=`ssh $node $USERNAME -C "cat /etc/multipath.conf" 2> /dev/null`
        RETVAL=$?
        if [ $RETVAL != 0 ]
        then
                echo "--- Error retrieving /etc/multipath.conf from node $node ---"
        fi
        parse_multipath $node
        assign_wwid $node
done
check_status
sort_results
echo_results

Tuesday, December 28, 2010

NFS Root

It's handy to be able to boot a system from an NFS root drive. I use it mostly for getting 'underneath' an operating system for things like installs or repairs, but you can also run indefinitely if that suits your environment.

If you look back to a post I did in September you will get the basics for setting up your PXE server. You will also need to create a custom kernel, or find one that allows for PXE booting with an NFS root partition. Generally I build a kernel with all of the required drivers installed including NFS root support.

The part that is generally a big problem for me is getting a root image setup to run from. I am a fan of building my own as I have more control in the operation and customization of a system but this can lead to problems. Local binaries included with the distributions I know all require libraries to which they are linked in order to run. So, I wrote a handy script to do all this work for me, from the current running system.

The following works for a RedHat based system. Unfortunately, distributions don't keep binaries in the same place, so if you want to use this you may have to change the file locations. There are four variables to do this job, SBIN_FILES, BIN_FILES, DEV_FILES, USER_BIN_FILES. Each correlates to a directory, for example SBIN_FILES = /sbin. Just find the files you want to include and put it in the corresponding variable. The script will take care of all the dependent libraries for you.

You can also specify some command line options if you like, -delete will clear out the destination directory before it does a build, and -bootdir will change the target build location.

The script uses udev so there isn't much need for /dev entries, otherwise have at it.

#!/bin/bash

BOOT_DIR=/tftpboot/boot-image
MOUNT_POINTS="proc sys mnt/src mnt/dest tmp"
LDD=/usr/bin/ldd

PRE_DELETE=0
SBIN_FILES="init ifconfig reboot poweroff mke2fs mkfs.ext3 mkfs.ext4 mkswap fdisk udevd udevadm mkinitrd ethtool fsck.ext3 fsck.ext4 hdparm shutdown"
BIN_FILES="bash mount cp umount dd rm ls cat more vim tar gzip ps"
DEV_FILES="console null"
USER_BIN_FILES="chroot tclsh vi"
LOG_FILE=/home/mike/nfs_build_log

######
### function setup_programs
### prepends required directories to overall file list to keep things looking clean
######
function setup_binaries {
        for file in $SBIN_FILES
        do
                FINAL_SBIN="$FINAL_SBIN /sbin/$file"
        done
        for file in $BIN_FILES
        do
                FINAL_BIN="$FINAL_BIN /bin/$file"
        done
        for file in $DEV_FILES
        do
                FINAL_DEV="$FINAL_DEV /dev/$file"
        done
        for file in $USER_BIN_FILES
        do
                FINAL_USER_BIN="$FINAL_USER_BIN /usr/bin/$file"
        done
        # delete everything in the boot directory if asked to
        if [ $PRE_DELETE -eq 1 ]
        then
                rm -rf $BOOT_DIR
        fi
}

function log {
        echo -e "`date +%H:%M:%S` -- "$1"" >> $LOG_FILE
}

######
### function create_etc
### populates the new /etc directory with a minimal set of startup scripts
### inittab, rc.sysinit, and boot.udev
######
function create_etc {
        mkdir -p $BOOT_DIR/etc

        # create inittab
        echo "id:3:initdefault:" > $BOOT_DIR/etc/inittab
        echo "si::sysinit:/etc/rc.sysinit" >> $BOOT_DIR/etc/inittab
        echo "id2:3:wait:/bin/bash" >> $BOOT_DIR/etc/inittab

        # create rc.sysinit
        echo "#!/bin/bash" > $BOOT_DIR/etc/rc.sysinit
        echo "echo \"--Running sysinit--\"" >> $BOOT_DIR/etc/rc.sysinit
        echo "echo -n \"Mounting proc filesystem: \"; mount -n -t proc /proc /proc; echo \"Done\"" >> $BOOT_DIR/etc/rc.sysinit
        echo "echo -n \"Mounting sys filesystem: \"; mount -n -t sysfs /sys /sys; echo \"Done\"" >> $BOOT_DIR/etc/rc.sysinit
        echo "echo -n \"Starting udev: \"; /etc/boot.udev; echo \"Done\"" >> $BOOT_DIR/etc/rc.sysinit
        echo "echo -n \"Configuring loopback network adapter: \"; /sbin/ifconfig lo 127.0.0.1; echo \"Done\"" >> $BOOT_DIR/etc/rc.sysinit
        echo "echo -n \"Clearing /etc/mtab\"; > /etc/mtab" >> $BOOT_DIR/etc/rc.sysinit
        chmod ug+x $BOOT_DIR/etc/rc.sysinit

        # create boot.udev assuming udevd and udevadm are in /sbin
        if [[ "$SBIN_FILES" == *udevd* ]] && [[ "$SBIN_FILES" == *udevadm* ]]
        then
                echo "#!/bin/bash" > $BOOT_DIR/etc/boot.udev
                echo "echo \"--Running udev--\"" >> $BOOT_DIR/etc/boot.udev
                echo "echo \"\" > /sys/kernel/uevent_helper" >> $BOOT_DIR/etc/boot.udev
                echo "echo -n \"Starting udevd \"" >> $BOOT_DIR/etc/boot.udev
                echo "rm -rf /dev/.udev" >> $BOOT_DIR/etc/boot.udev
                echo "/sbin/udevd --daemon" >> $BOOT_DIR/etc/boot.udev
                echo "/sbin/udevadm trigger --type=subsystems" >> $BOOT_DIR/etc/boot.udev
                echo "/sbin/udevadm trigger --type=devices" >> $BOOT_DIR/etc/boot.udev
                echo "/sbin/udevadm settle --timeout=180" >> $BOOT_DIR/etc/boot.udev
                chmod ug+x $BOOT_DIR/etc/boot.udev
        fi
}

######
### function get_libraries
### helper function for copy_files
### executes ldd against a binary to retrieve all dependent libraries
### executes copy_files with the "library_file" flag to prevent it from running get_libraries again
######
function get_libraries {
        local FILE_NAME="$1"
        log "Checking library for $FILE_NAME"
        LDD_OUTPUT=`ldd "${FILE_NAME}" 2> /dev/null`
        # e.g. libc.so.6 => /lib64/libc.so.6 (0x00007f7a03b64000)
        # look at each index in the output checking if it's a file, then pass it to copy_files e.g. /lib64/libc.so.6
        for index in $LDD_OUTPUT
        do
                if [ -f $index ]
                then
                        LIBRARY_FILES="$LIBRARY_FILES $index"
                fi
        done

}

######
### function copy_files
### copies a source file to BOOT_DIR with the proper destination directory
### e.g. /bin/ls becomes $BOOT_DIR/bin/ls
### if the file is a symbolic link, follow it through depending if it is a relative or absolute path
######
function copy_files {
        local FILE_NAME="$1"
        log "Copying $FILE_NAME"
        # find where this file should go based BOOT_DIR + it's original path
        # e.g. /tftpboot/boot-image + /sbin
        DEST_DIR="$BOOT_DIR/`dirname "$FILE_NAME"`"
        if [ ! -d "${DEST_DIR}" ]
        then
                mkdir -p "${DEST_DIR}"
        fi
        # the -a will preserve any symbolic links
        cp -a "${FILE_NAME}" "${DEST_DIR}"

        # if this is a link find what the real file is and copy that
        if [ -L "$FILE_NAME" ]
        then
                # ideally we could use canonicalize mode (-f) as that always returns an absolute path but that won't handle links pointing to links
                LINK_FILE=`readlink "$FILE_NAME"`
                # check to see if this is an absolute path
                # e.g. /lib64/libpthread.so.0 -> libpthread-2.10.1.so
                LINK_DIR=`dirname "$LINK_FILE"`         #e.g. ./
                if [ ! ${LINK_DIR:0:1} == "/" ]
                then
                        # find the path of the original file
                        FILE_DIR=`dirname "$FILE_NAME"` #e.g. /lib64
                        # change to the original path + relative path and find where we are with pwd
                        cd "$FILE_DIR"/"$LINK_DIR"              #e.g. cd /lib64/.
                        LINK_PATH=`pwd`                         #e.g. /lib64
                        # recreate the file with the proper path of the link
                        LINK_FILE="$LINK_PATH"/`basename "$LINK_FILE"`  # e.g. /lib64/libpthread-2.10.1.so
                fi
                copy_files "${LINK_FILE}" $2
                # need to copy the file, if it returns no path it is in the same dir, otherwise it will be absolute path
        fi
        if [ ! "$2" == "library_file" ]
        then
                get_libraries "$FILE_NAME"
        fi
}

######
### function create_mount_points
######
function create_mount_points {
        for mount in $MOUNT_POINTS
        do
                mkdir -p $BOOT_DIR/$mount
        done
}

######
### function usage
### outputs usage information for this script and then exits
######
function usage {
        echo ""
        echo -e "Usage:\n`basename $0` -delete -bootdir "
        echo "-delete"
        echo "  remove old data before creating new content, default is to keep"
        echo "-bootdir"
        echo "  directory to copy binaries to, default is /tftpboot/boot-image"
        echo ""
        exit 0
}

if [ $# -eq 0 ]
then
        usage
fi

until [ -z "$1" ]
do
        case "$1" in
        -delete)
                PRE_DELETE=1
                ;;
        -bootdir)
                shift
                BOOT_DIR="$1"
                ;;
        *)
                usage
                ;;
        esac
        shift
done


setup_binaries

for file in $FINAL_SBIN $FINAL_BIN $FINAL_DEV $FINAL_USER_BIN
do
        copy_files $file
done

if [ -n "$LIBRARY_FILES" ]
then
        LIBRARY_FILES=`echo $LIBRARY_FILES | tr " " "\n" | sort -u`
        for file in $LIBRARY_FILES
        do
                copy_files $file "library_file"
        done
fi

create_etc

Tuesday, October 19, 2010

KickStart Network Customization

One of the biggest problems I have found with the KickStart process is fine tuning the network values of a server. I couldn't find anything useful through the standard process so I decided to write my own. If you have seen my last post I reference some customized configuration scripts in the %post section of my KickStart file. In this post I will outline my first customization which I simply call general.cfg.

Basically this sets up the NTP daemon by rewriting the /etc/ntp.conf file and turns off services I don't need. But first it calls a special script called network_config.sh.
# cat general.cfg
# Clean up the network either based on existing DHCP or on configuration file

# network_config.sh requires an argument to tell it where the csv file is and where to output logs
/post_scripts/KickStart/net_config/network_config.sh /post_scripts/KickStart/net_config

# setup NTP
echo 'restrict default kod nomodify notrap nopeer noquery' > /etc/ntp.conf
echo 'restrict -6 default kod nomodify notrap nopeer noquery' >> /etc/ntp.conf
echo 'restrict 127.0.0.1' >> /etc/ntp.conf
echo 'restrict -6 ::1' >> /etc/ntp.conf
echo 'server 192.168.0.1' >> /etc/ntp.conf
echo 'server 127.127.1.0' >> /etc/ntp.conf
echo 'fudge 127.127.1.0 stratum 10' >> /etc/ntp.conf
echo 'driftfile /var/lib/ntp/drift' >> /etc/ntp.conf
chmod 644 /etc/ntp.conf

echo '192.168.0.1' >> /etc/ntp/ntpservers
echo '192.168.0.1' >> /etc/ntp/step-tickers

# modify the /etc/sysconfig/ntp file to add the -x startup option 
# required for Oracle 11gR2
echo 'OPTIONS="-u ntp:ntp -x -p /var/run/ntpd.pid"' > /etc/sysconfig/ntpd
echo 'SYNC_HWCLOCK=no' >> /etc/sysconfig/ntpd
echo 'NTPDATE_OPTIONS=""' >> /etc/sysconfig/ntpd

/usr/sbin/ntpdate 192.168.0.1

chkconfig ntpd on

# remove unnecessary services
chkconfig sendmail off

# printer
chkconfig cups off
chkconfig hplip off

network_config.sh is a bit long but I will post it in it's entirety here. Its primary job is to take input from a file called hostfile.csv and configure DNS, host name, and configure all of the interfaces. Network interfaces can be specified by adapter name (e.g. eth0, eth1, etc) or by MAC address just in case the enumeration isn't quite what you expect. It can also configure bonded interfaces which I am particularly happy with as this can be of significant annoyance getting production servers ready. Host names are defined as part of the dhcp options which I showed in this post. If no match is found, for example if there is no matching entry in hostfile.csv, the script will try to grab whatever IP has been assigned for the install and hard code that to the server. Logs are kept at a location specified on the command line which also happens to be the location of hostfile.csv.

Here is an example of a hostfile.csv entry for your reference when looking through the script.
# cat hostfile.csv
DOMAINSEARCH=example.com example2.com example3.com
# Format -- server_name,[bond|nic] eth# [eth#] IP MASK Primary,gw={gateway},dns={dns1 dns2 etc}
# as long as the server name comes first, the order of the rest doesn't really matter
# Primary is used to determine which interface should be placed in the host file
# an example with multiple bonded interfaces.
server1,bond=bond0 eth0 eth3 192.168.0.10 255.255.255.0 1,gw=192.168.0.1,bond=bond1 eth1 eth2 10.1.1.1 255.255.255.0,dns=192.168.0.254 192.168.1.254
# an example with one bond using MAC addresses
server2,bond=bond0 0050569c25e5 0050569c6cbd 192.168.0.11 255.255.255.0 1,gw=192.168.0.1,dns=192.168.0.254 192.168.1.254
# an example with a single nic
server3,nic=eth0 192.168.0.12 255.255.255.0 1,gw=192.168.0.1,dns=192.168.0.254

And here is the network_config.sh script itself
# cat network_config.sh
#!/bin/bash
DEBUG=off
IFCONFIG=/sbin/ifconfig

NIC_FILE_DIR=/etc/sysconfig/network-scripts/

GW_FILE=/etc/sysconfig/network

HOST_FILE=/etc/hosts

DNS_FILE=/etc/resolv.conf

DOMAIN_LIST="domain.com domain2.com"

####
## function readHostFile
## reads $HOST_MAP_FILE for specific network information about this host
## return 1 on error, 0 on success
## options can be in any order (nic, gw, or bond), broadcast and network address are calculated based on ip and mask
## calls functions to generate Gateway ($GW_FILE), Hosts ($HOST_FILE), and ifcfg ($NIC_FILE_DIR/ifcfg-{nic})
##
## host_map_file format
## {host},nic={eth#} ip mask [?primary],gw={gw_ip},bond={bond#} {nic1} {nic2} {ip} {mask},domain={dns_server},{dns_server}
## e.g. server1,nic=eth0 192.168.1.1 255.255.255.0,gw=192.168.0.1,nic=bond0 eth1 eth2 192.168.0.10 255.255.255.0 1,dns=192.168.0.254 192.168.1.254
####
readHostFile() {
        if [ -e $HOST_MAP_FILE ]
        then
                # override default DOMAIN_LIST if it exists
                DOMAIN_TMP=$(cat $HOST_MAP_FILE | grep -wi "DOMAINSEARCH" | cut -f2 -d =)
                if [ ! -z "$DOMAIN_TMP" ]
                then
                        log info "Domain search list found -- $DOMAIN_TMP"
                        DOMAIN_LIST="$DOMAIN_TMP"
                else
                        log info "Domain search not found, using defaults -- $DOMAIN_LIST"
                fi

                # parse the file for this host exactly (-w) and case insensitive
                HOST_INFO=$(cat $HOST_MAP_FILE | grep -wi `hostname`)
                # check to see there was an entry for this host
                if [ -z "$HOST_INFO" ]
                then
                        log warning "Host information for `hostname` was not found in HOST_MAP_FILE"
                        return 1
                fi
                log notify "Host information found for `hostname` in $HOST_MAP_FILE"
                log notify "Host info is $HOST_INFO"
                # parse HOST_INFO
                IFS=$','
                for entry in $HOST_INFO
                do
                        log debug "Working on entry $entry"
                        KEY=`echo $entry | cut -f1 -d =`
                        VALUE=`echo $entry | cut -f2 -d =`
                        case "$KEY" in
                        nic)
                                log debug "nic is specified -- $VALUE"
                                NIC=`echo $VALUE | cut -f1 -d " "`
                                if [ ${#NIC} -eq 12 ]
                                then
                                        # we are working with a MAC address
                                        NIC=$(getNIC $NIC)
                                fi
                                IPADDR=`echo $VALUE | cut -f2 -d " "`
                                MASK=`echo $VALUE | cut -f3 -d " "`
                                PRIMARY=`echo $VALUE | cut -f4 -d " "`
                                BROADCAST=$(getBroadcastAddress $IPADDR $MASK)
                                NETWORK=$(getNetworkAddress $IPADDR $MASK)
                                # MAC address for this card
                                MAC=$(getMAC $NIC)

                                if [ -z $NIC ]
                                then
                                        log error "Missing NIC information aborting file creation"
                                else
                                        log info "Values for NIC $NIC - MAC $MAC - IP $IPADDR - NetMask $MASK - Broadcast $BROADCAST - Network $NETWORK"
                                        genIPFile $NIC $MAC $IPADDR $MASK $BROADCAST $NETWORK
                                fi

                                if [ "$PRIMARY" == 1 ]
                                then
                                        genHostFile $IPADDR
                                fi
                                ;;
                        bond)
                        #nic=bond0 eth1 eth2 192.168.0.10 255.255.255.0 1
                                log debug "bond is specified -- $VALUE"
                                BOND=`echo $VALUE | cut -f1 -d " "`
                                NIC1=`echo $VALUE | cut -f2 -d " "`
                                if [ ${#NIC1} -gt 12 ]
                                then
                                        # we are working with a MAC address
                                        NIC1=$(getNIC $NIC1)
                                fi
                                NIC2=`echo $VALUE | cut -f3 -d " "`
                                if [ ${#NIC2} -gt 12 ]
                                then
                                        # we are working with a MAC address
                                        NIC2=$(getNIC $NIC2)
                                fi
                                IPADDR=`echo $VALUE | cut -f4 -d " "`
                                MASK=`echo $VALUE | cut -f5 -d " "`
                                BROADCAST=$(getBroadcastAddress $IPADDR $MASK)
                                NETWORK=$(getNetworkAddress $IPADDR $MASK)

                                log info "Values for BOND $BOND - NIC1 $NIC1 - NIC2 $NIC2 - IP $IPADDR - NetMask $MASK - Broadcast $BROADCAST - Network $NETWORK"
                                genBondFile $BOND $NIC1 $NIC2 $IPADDR $MASK $BROADCAST $NETWORK

                                if [ "$PRIMARY" == 1 ]
                                then
                                        genHostFile $IPADDR
                                fi
                                ;;
                        gw)
                                log debug "Gateway value - $VALUE"
                                genGWFile $VALUE
                                ;;
                        dns)
                                log debug "DNS is specified -- $VALUE"
                                genDNSFile "$VALUE"
                        esac
                done
        else
                log warning "Hostfile $HOST_MAP_FILE does not exist"
                return 1
                # configure eth0 as static based on the current DHCP address
        fi
}

####
## function getNIC {mac_addr}
## returns eth# based on MAC address
####
getNIC() {
        local RAW_MAC=$1
        # a properly formatted MAC address is 00:10:20:30:40:50 (17 characters)
        if [ ${#RAW_MAC} -ne 17 ]
        then
                # assume the user didn't put in : marks
                COUNT=0
                # in case this is IPv6 loop for the entire raw mac length
                while [ $COUNT -lt ${#RAW_MAC} ]
                do
                        if [ $COUNT -eq 0 ]
                        then
                                SEARCH_MAC=${RAW_MAC:$COUNT:2}
                        else
                                SEARCH_MAC="$SEARCH_MAC:${RAW_MAC:$COUNT:2}"
                        fi
                        COUNT=$(($COUNT + 2))
                done
        else
                SEARCH_MAC=$RAW_MAC
        fi

        # return eth# for a specific MAC
        local NIC=`$IFCONFIG -a | grep -i $SEARCH_MAC | awk '{print $1}'`
        if [ -z $NIC ]
        then
                log error "Network interface was not found for nic $SEARCH_MAC, this interface will not be configured correctly"
                log error "ifconfig output is \n`$IFCONFIG -a`"
        else
                log info "NIC $SEARCH_MAC found as $NIC"
        fi
        echo $NIC
}

####
## function genBondFile {bond#} {nic1} {nic2} {ip} {mask} {broadcast} {network}
## nic=bond0 eth0 eth1 192.168.0.10 255.255.255.0 
## nic=eth0 192.168.0.10 255.255.255.0 192.168.0.254 192.168.0.0
####
genBondFile() {
        local BOND=$1
        local NIC1=$2
        local NIC2=$3
        local IP=$4
        local MASK=$5
        local BROADCAST=$6
        local NETWORK=$7
        local BOND_FILE=${NIC_FILE_DIR}ifcfg-$BOND
        local NIC1_FILE=${NIC_FILE_DIR}ifcfg-$NIC1
        local NIC2_FILE=${NIC_FILE_DIR}ifcfg-$NIC2

        log info "Creating Bond file $BOND_FILE"
        echo "DEVICE=$BOND" > $BOND_FILE
        echo "BOOTPROTO=none" >> $BOND_FILE
        echo "ONBOOT=yes" >> $BOND_FILE
        echo "NETWORK=$NETWORK" >> $BOND_FILE
        echo "NETMASK=$MASK" >> $BOND_FILE
        echo "IPADDR=$IP" >> $BOND_FILE
        echo "BROADCAST=$BROADCAST" >> $BOND_FILE
        echo "USERCTL=no" >> $BOND_FILE
        echo "BONDING_OPTS=\"mode=active-backup miimon=100 primary=$NIC1\"" >> $BOND_FILE

        log info "Creating network file $NIC1_FILE"
        echo "DEVICE=$NIC1" > $NIC1_FILE
        echo "BOOTPROTO=none" >> $NIC1_FILE
        echo "HWADDR=$(getMAC $NIC1)" >> $NIC1_FILE
        echo "ONBOOT=yes" >> $NIC1_FILE
        echo "MASTER=$BOND" >> $NIC1_FILE
        echo "SLAVE=yes" >> $NIC1_FILE
        echo "USERCTL=no" >> $NIC1_FILE

        log info "Creating network file $NIC2_FILE"
        echo "DEVICE=$NIC2" > $NIC2_FILE
        echo "BOOTPROTO=none" >> $NIC2_FILE
        echo "HWADDR=$(getMAC $NIC2)" >> $NIC2_FILE
        echo "ONBOOT=yes" >> $NIC2_FILE
        echo "MASTER=$BOND" >> $NIC2_FILE
        echo "SLAVE=yes" >> $NIC2_FILE
        echo "USERCTL=no" >> $NIC2_FILE

        log info "Modifying modprobe.conf file /etc/modprobe.conf"
        echo "alias $BOND bonding" >> /etc/modprobe.conf
}

####
## function getMAC {nic}
## gets the MAC address for a given interface using ifconfig
####
getMAC() {
        HWINFO=`$IFCONFIG $1 | grep HWaddr` # eth0      Link encap:Ethernet     HWaddr 00:50:56:9C:1B:00
        if [ $? -ne 0 ]
        then
                log error "Cannot find MAC address for interface $1"
                # return nothing to the calling process
                echo " "
        else
                # return the MAC address 
                echo $HWINFO | awk '{print $5}'
        fi
}

####
## function genDomainFile {nameserver} {nameserver} {etc}
## creates a basic DNS file for nameserver entries
####
genDNSFile() {
        log info "Creating DNS file $DNS_FILE"
        OldIFS=$IFS
        IFS=" "
        > $DNS_FILE
        # create search entries
        echo "search $DOMAIN_LIST" >> $DNS_FILE
        # create server entries
        for dnsEntry in $1
        do
                echo "nameserver $dnsEntry" >> $DNS_FILE
        done
        IFS=$OldIFS
}
####
## function genHostFile {local_ip}
## creates a basic hosts file with loopback and this host
####
genHostFile() {
        local IP=$1
        log info "Creating host file $HOST_FILE"
        echo "127.0.0.1         localhost.localdomain localhost" > $HOST_FILE
        echo "$IP               `hostname`" >> $HOST_FILE

}

####
## function genGWFile {gateway_ip}
## create the default route file including default RedHat values
####
genGWFile() {
        local GW=$1
        log info "Creating gateway file $GW_FILE"
        echo "NETWORKING=yes" > $GW_FILE
        echo "NETWORKING_IPV6=no" >> $GW_FILE
        echo "HOSTNAME=`hostname`" >> $GW_FILE
        echo "GATEWAY=$GW" >> $GW_FILE
}

####
## function genIPFile {nic} {mac} {ip} {mask} {broadcast} {network}
## create the IP Address file (ifcfg-eth{x})
## e.g. nic=eth0 00:50:56:9C:1B:00 192.168.0.10 255.255.255.0 192.168.0.254 192.168.0.0
####
genIPFile() {
        local NIC=$1
        local MAC=$2
        local IP=$3
        local MASK=$4
        local BROADCAST=$5
        local NETWORK=$6
        local IP_FILE=${NIC_FILE_DIR}ifcfg-${NIC}

        log info "Creating network file $IP_FILE"
        echo "DEVICE=$NIC" > $IP_FILE
        echo "BOOTPROTO=static" >> $IP_FILE
        echo "BROADCAST=$BROADCAST" >> $IP_FILE
        echo "HWADDR=$MAC" >> $IP_FILE
        echo "IPADDR=$IP" >> $IP_FILE
        echo "NETMASK=$MASK" >> $IP_FILE
        echo "NETWORK=$NETWORK" >> $IP_FILE
        log debug "----------- ifcfg-$NIC file -----------"
        log debug "\n`cat $IP_FILE`"
        log debug "----------------------"
}

####
## function getNetworkAddress
## calculates the network address given an ip and subnet mask
## converts the ip and mask into an array and does a bitwise and for each element
####
getNetworkAddress() {
        OldIFS=$IFS
        IFS=.
        typeset -a IP_Array=($1)
        typeset -a MASK_Array=($2)
        IFS=$OldIFS
        echo $((${IP_Array[0]} & ${MASK_Array[0]})).$((${IP_Array[1]} & ${MASK_Array[1]})).$((${IP_Array[2]} & ${MASK_Array[2]})).$((${IP_Array[3]} & ${MASK_Array[3]}))
}

####
## function getBroadcastAddress
## calculates the broadcast address given an ip and subnet mask
## converts the ip and mask into an array and does a bitwise or (|) against an XOR (^)
####
getBroadcastAddress() {
        OldIFS=$IFS
        IFS=.
        typeset -a IP_Array=($1)
        typeset -a MASK_Array=($2)
        IFS=$OldIFS
        echo $((${IP_Array[0]} | (255 ^ ${MASK_Array[0]}))).$((${IP_Array[1]} | (255 ^ ${MASK_Array[1]}))).$((${IP_Array[2]} | (255 ^ ${MASK_Array[2]}))).$((${IP_Array[3]} | (255 ^ ${MASK_Array[3]})))
}

####
## function readDHCPAddress
## reads information currently running and writes it out as a static IP entry
####
readDHCPAddress() {
        log info "Host information was not found for this server, copying information from running configuration (DHCP)"
        # the grep will grab two lines of output and merge them together
        # eth0      Link encap:Ethernet  HWaddr 00:50:56:9C:1B:00
        # inet addr:192.168.0.10  Bcast:192.168.0.254  Mask:255.255.255.0
        HWINFO=`$IFCONFIG | grep -A 1 -i hwaddr`
        NIC=`echo $HWINFO | cut -f1 -d " "`
        MAC=`echo $HWINFO | cut -f5 -d " "`
        for i in $HWINFO
        do
                case "$i" in
                addr:*)
                        IP=`echo $i | cut -f2 -d :`
                        ;;
                Bcast:*)
                        BROADCAST=`echo $i | cut -f2 -d :`
                        ;;
                Mask:*)
                        MASK=`echo $i | cut -f2 -d :`
                        ;;
                esac
        done
        NETWORK=$(getNetworkAddress $IP $MASK)
        log debug "DHCP information is NIC $NIC - MAC $MAC - IP $IP - MASK $MASK - BROADCAST $BROADCAST - NETWORK $NETWORK"
        genIPFile $NIC $MAC $IP $MASK $BROADCAST $NETWORK
        genHostFile $IP
        GATEWAY=`netstat -rn | grep -w UG | awk '{print $2}'`
        genGWFile $GATEWAY
}

####
## function log
## logs activities to the screen, a file, or both
####
log() {
        LOG_TYPE="$1"
        LOG_MSG="$2"
        TIME=`date +'%H:%M:%S %Z'`
        # specify the log file only once
        if [ ! -d $SOURCE_DIR/logs ]
        then
                mkdir ${SOURCE_DIR}/logs
        fi
        if [ -z $LOG_FILE ]
        then
                LOG_FILE="$SOURCE_DIR/logs/network_config-`hostname`-`date +%Y%m%d-%H%M%S`"
        fi
        if [ $LOG_TYPE == "error" ]
        then
                echo -e "$TIME - **ERROR** - $LOG_MSG" >> $LOG_FILE
        elif [ $LOG_TYPE == "debug" ]
        then
                if [ $DEBUG == "on" ]
                then
                        echo -e "DEBUG - $LOG_MSG" >> "$LOG_FILE"
                fi
        elif [ $LOG_TYPE == "warning" ]
        then
                echo -e "$TIME - **WARNING** - $LOG_MSG" >> $LOG_FILE
        else
                echo -e "$TIME - $LOG_MSG" >> "$LOG_FILE"
        fi
}

# read source directory from command line.  This is where we will read the hostfile.csv and output logs to
SOURCE_DIR=$1
HOST_MAP_FILE=$SOURCE_DIR/hostfile.csv

readHostFile
if [ $? -ne 0 ]
then
        readDHCPAddress
fi

Sunday, October 3, 2010

Modular KickStart

I am a big fan of the modular kickstart setup. This allows easier administration of multiple configurations and tends to keep things clean and consistent. KickStart allows this through the %include directive but in order to reference an external file, a small trick is required. You see, the kickstart configuration file is in fact read twice. Once looking for any %pre directives and another to actually parse the file. So, it's in this %pre section that you can setup your config file location.

I like to use NFS for my configuration and OS files. It is relatively easy to setup and can allow multiple kickstart servers to reference it if required. Here is a sample pre section:
%pre
mkdir /post_scripts
mount -t nfs -o nolock NFS_SERVER:/tftpboot/kickstart /post_scripts
Basically it says to mount a share to /post_scripts so I can reference the files. On the server I place my configuration files in /tftpboot/kickstart/ks_cfg/ and call them like this:
%include /post_scripts/ks_cfg/CONFIG_FILE
Here are the basic sections of my kickstart file:
# cat /tftpboot/ks_cfg/oracle_5.5.ks
install
nfs --server=NFS_SERVER --dir=/tftpboot/kickstart/OS/RHEL5.5/
key --skip
lang en_US.UTF-8
keyboard us
xconfig --startxonboot
network --bootproto dhcp 
rootpw --iscrypted YOUR_PASSWORD
firewall --disabled
firstboot --disable
authconfig --enableshadow --enablemd5
selinux --disabled
timezone --utc America/Vancouver
bootloader --location=mbr --append="rhgb quiet"
clearpart --all --initlabel
part /boot --fstype="ext3" --size=100
part pv.2 --size=0 --grow
volgroup rootvg --pesize=32768 pv.2
logvol swap --fstype="swap" --name=swap --vgname=rootvg --size=2048
logvol /var --fstype="ext3" --name=var --vgname=rootvg --size=2048
logvol / --fstype="ext3" --name=root --vgname=rootvg --size=1 --grow
reboot

%packages
%include /post_scripts/ks_cfg/packages.cfg

%post
chvt 3
%include /post_scripts/ks_cfg/generic.cfg
%include /post_scripts/ks_cfg/oracle.cfg
%include /post_scripts/ks_cfg/multipath.cfg

%pre
mkdir /post_scripts
mount -t nfs -o nolock NFS_SERVER:/vol/KICKSTART /post_scripts

# cat /tftpboot/ks_cfg/packages.cfg
@editors
@gnome-desktop
@core
@base
@ftp-server
@network-server
@java
@legacy-software-support
@base-x
@server-cfg
@admin-tools
@graphical-internet
emacs
kexec-tools
fipscheck
device-mapper-multipath
dnsmasq
xorg-x11-utils
system-config-boot
# Oracle Required Packages
elfutils-libelf-devel
gcc
gcc-c++
glibc-devel
libaio-devel
libstdc++-devel
sysstat
# these are for Oracle 10G
libXp
openmotif
# Oracle 11GR2
unixODBC
unixODBC-devel
I'll cover off some of the more 'advanced' features in a later post.

Saturday, September 18, 2010

Linux PXE Boot

Over the next few posts I thought I would outline my version of diskless booting and imaging a Linux system (Kickstart specifically). To start with we'll be setting up PXELINUX and the required services, TFTP, NFS and DHCP.

TFTP Server
When PXE booting a client, Trivial File Transfer Protocol Daemon is responsible for passing the kernel binaries. Because it's directory structure forms the basis for the rest of our files, its a good idea to have it installed first. Once installed, enable the daemon by editing /etc/xinetd.d/tftp and changing disabled = yes to disabled = no, or you can run a sed script as shown below, then restart xinetd. This is also the file to edit if you want to place files in a different folder. The default is /tftpboot which I will be using through the rest of the example.
SuSE
# zypper install tftp
RedHat
# yum install tftp

# sed -e 's/disable.*=\ yes/disable\t\t\t= no/' /etc/xinetd.d/tftp > /etc/xinetd.d/tftp.temp
# mv /etc/xinetd.d/tftp.temp /etc/xinetd.d/tftp
# /etc/init.d/xinetd restart

PXELINUX
PXELINUX is a derivative project of SYSLINUX which allows you to boot Linux from a network server. I used to use Etherboot for this purpose but it requires a device specific image to be pushed to the card. This can create all kinds of headaches whereas PXELINUX is quite simple; one binary to all cards as long as they conform to the Intel PXE specification (Pre-Execution Environment). I don't know of a server today that doesn't have a PXE compliant NIC and in fact many desktop cards do as well.

Most distributions have a package for SYSLINUX which includes PXELINUX, or if you want to do things manually you can grab the binaries from here. This is perhaps already installed with a default directory structure which I also follow.
SuSE
# zypper install syslinux
RedHat
# yum install syslinux
There should be a directory under /tftpboot called linux-boot with a single file, pxelinux.0. If not you can create them as shown below.
# mkdir -p /tftpboot/linux-boot
# cp /usr/share/syslinux/pxelinux.0 /tftpboot/linux-boot

NFS Server
The NFS Server requirements are pretty basic and largely depends on what you want to do. For now we will setup two exports, one for diskless booting and another for Kickstart. They actually don't have to be on the same physical box, if you have a fancy NAS server you can host it there but for the purposes of this exercise we will host it under /tftpboot/boot-image and /tftpboot/kickstart. Edit /etc/exports as shown and startup your NFS server.
# mkdir -p /tftpboot/boot-image
# mkdir -p /tftpboot/kickstart
# vi /etc/exports
/tftpboot/boot-image *(rw,no_root_squash)
/tftpboot/kickstart *(rw,no_root_squash)
# /etc/init.d/nfsserver start

DHCP Server
Asside from the details of setting up PXELINUX itself, the DHCP server contains most of the configuration information. Listed below is a generic configuration that should give you a good starting point. I generally have a listing for each one of my servers as it provides me with some additional flexibility such as providing general DHCP services to other hosts on the same network.

The first option ddns-update-style turns off dynamic DNS. The second next-server is used to tell the client from which server it should retrieve it's initial boot as specified by the filename option. Otherwise things should be pretty straight forward.
ddns-ddns-update-style       none;
next-server             192.168.0.1;

subnet 192.168.0.0 netmask 255.255.255.0 {

}

group {
        option domain-name              "pxeboot.net";
        filename                        "linux-install/pxelinux.0";
        option routers                  ;
        option domain-name-servers      ;
        use-host-decl-names             on;
        host node01 {
                hardware ethernet       00:AE:56:9C:5D:81;
                fixed-address           192.168.0.10;
        }
        host node02 {
                hardware ethernet       00:50:56:99:4E:41;
                fixed-address           192.168.0.11;
        }
        host node03 {
                hardware ethernet       00:50:56:99:E0:68;
                fixed-address           192.168.0.12;
        }
}

Once this is completed you will probably have to edit the dhcpd configuration file, /etc/sysconfig/dhcpd, in order to tell it which interface to listen to. It's generally the first option (after the comments) and is called DHCPD_INTERFACE. Simply append on the appropriate interface and restart dhcpd with /etc/init.d/dhcpd restart. There is generally decent error information on the command line if you have any typos or missed anything.

Configuring PXELINUX
When PXELINUX is booted it will look in a sub-directory called pxelinux.cfg to find a configuration file for a specific host. Because this is a relative directory, ours will be called /tftpboot/linux-install/pxelinux.cfg. There is an order to the files its looking for which you can read all about here but given that this is a generic boot server, I am going to use the catch all default file.

In the example below I use numbers to control what to boot from rather than typing names. There is a display option display msgs/logicalshift.msg that shows the available boot choices (see below) and a corresponding label which does the actual work. My default is a generic installation, there is a prompt for the user to input a value and a 10 second timeout. You can find more about these options from the syslinux man pages.

Under each kernel I have two important options; the append option to tell the kernel to load an appropriate initrd, where to find its kickstart file and which device to use for the kickstart; in this case the interface that was booted from. And ipappend, used to tell PXELINUX that it should pass along IP information to the kernel given by the DHCP server.

In my configuration I specify a local boot option, a setup to run completely from an NFS server and two kickstart configurations; a generic install and one pre-configured to run Oracle. More on these to follow.

/tftpboot/linux-install/pxelinux.cfg/default
default 4
prompt 1
timeout 100
display msgs/logicalshift.msg

label 1
        localboot 0

label 2
        kernel CUSTOM/bzImage_x64-2.6.34
        append rw nfsroot=:/tftpboot/boot-image ip=dhcp

label 3
        kernel RHEL_5.4/vmlinuz
        append ksdevice=bootif initrd=RHEL_5.5/initrd.img ks=nfs::/tftpboot/KickStart/cfg/generic_5.5.ks
        ipappend 2

label 4
        kernel RHEL_5.4/vmlinuz
        append ksdevice=bootif initrd=RHEL_5.5/initrd.img ks=:/tftpboot/KickStart/cfg/oracle_5.5.ks
        ipappend 2


/tftpboot/linux-install/pxelinux.cfg/msgs/logicalshift.msg
This file doesn't provide any logic, it is just for display to give the user the available options. Escape characters are there to provide some colour, just for fun. I use an online ascii generator with a rounded font from here if you are interested in doing your own version.
^L

           ^O09Welcome to the ^O0cLogical Shift Installer^O07
^O0a
 _             _             _          _     _    ___       
| |           (_)           | |        | |   (_)  / __)  _   
| | ___   ____ _  ____ _____| |     ___| |__  _ _| |__ _| |_ 
| |/ _ \ / _  | |/ ___|____ | |    /___)  _ \| (_   __|_   _)
| | |_| ( (_| | ( (___/ ___ | |   |___ | | | | | | |    | |_ 
 \_)___/ \___ |_|\____)_____|\_)  (___/|_| |_|_| |_|     \__)
        (_____|                                              

                           
^O07

Enter number of the Operation System you wish to install:

1. Local (HDD) boot
2. Custom NFS root
3. Generic RHEL 5.5
4. RHEL 5.5 with Oracle Prerequisites (default)

Boot Kernel and KickStart File
One last step remains to give us some basic functionality, a Kernel and initial RAM disk to boot from and a kick start file to install from. I like to keep multiple kernel versions around so I have a directly relative to pxelinux.0 called RHEL_5.5.

In my pxe config file above I reference a directory for a RedHat 5.5. This is again a relative directory to pxelinux so it will be located under /tftpboot/linux-install as RHEL_5.5. You can get the kernel and initial RAM disk from the RedHat DVD; the steps are outlined below. The easiest way to create a kick start file is to perform a manual install, save the results and copy the file to the NFS location specified on the append line of your pxelinux.cfg/default file. From this base line you can customize your installation but I will cover that in a latter post.
# mkdir -p /tftpboot/linux-install/RHEL_5.5
# mount -o loop rhel_5.5.iso /mnt
# cp /mnt/images/pxeboot/vmlinuz /tftpboot/linux-install/RHEL_5.5/
# cp /mnt/images/pxeboot/initrd.img /tftpboot/linux-install/RHEL_5.5/
# umount /mnt

Saturday, August 7, 2010

Cisco VPN chkconfig errors

There is (at least) one more error I have seen when running the Cisco VPN client under Linux. For those systems that use LSB or Linux Standard Base (you can see my blog entry on startup scripts here) you will get an error whenever running chkconfig like this:
insserv: warning: script 'K01vpnclient_init' missing LSB tags and overrides
insserv: warning: script 'vpnclient_init' missing LSB tags and overrides
To fix this message, edit the /etc/init.d/vpn_client_init script to bring it up to LSB standards. I put the following just above the Source function library and just after the chkconfig information included with the comments.
### BEGIN INIT INFO
# Provides: ciscovpn
# Required-Start: $network
# Required-Stop:
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 3
# Short-Description: vpnclient
# Description: Cisco VPN Client
### END INIT INFO