Sunday, July 03, 2011

How A Simple Test Script Evolve

I will try to walk you through how a simple test script evolve from a one-time throw-away script to a more generic program that can be re-use.

The requirement is pretty simple. "Can I have a script to submit program-a to run 5 times for 10 minutes, 3 times for 5 minutes and 2 times for half an hour?". There you go with a one-time throw-away script. BTW, this is supposed to run on a Linux system

#! /bin/sh

./program-a --duration 600
./program-a --duration 600
./program-a --duration 600
./program-a --duration 600
./program-a --duration 600

./program-a --duration 300
./program-a --duration 300
./program-a --duration 300

./program-a --duration 1800
./program-a --duration 1800

Our job is done. What if the requirement for duration needs to be changed and we will have to modify quite a few places in the above script. So the script evolved to do some looping.

#! /bin/sh

for i in 1 2 3 4 5
do
    ./program-a --duration 600
done

for i in 1 2 3
do
    ./program-a --duration 300
done

for i in 1 2
do
   ./program-a --duration 1800
done

Not too bad! But there are still a few places where we hard code things like how many times we loop and the duration. OK, may be we can do some form of input instead of fix values

#! /bin/sh

while read duration howmany
do
    seq $howmany | while read count
    do
        ./program-a --duration $duration
    done
done <<EOF
600 5
300 3
1800 2
EOF

Now all I have to do is to change the input data (within the EOF) in the script to control the duration in seconds and how many times to loop through. Hey, but I still need to modify the program every time there is a change in requirement. Can't we have that information to be controlled by input arguments. Also, I want to tell the script in terms of day/hour/minute/second instead of just seconds because I am lazy to calculate. Not a problem at all. Let say the input argument takes the form of "1d23h45m6sx7" to represent looping through the prgroam 7 times with a duration of 1 day 23 hours 45 minutes 6 seconds (that is 171906 seconds, if you work it out). This calculation can be easily done by using sed to substitute day (d) with '*86400+', hour (h) with '*3600+', minute (m) with '*60+' and second (s) with ''. You also need to remove any ending '+' to avoid illegal arthematic epxpression.

#! /bin/sh

if [ $# -eq 0 ]; then
    echo "Usage: $0  [?d?h?m?sx?]"
    echo "       Eg. $0 1d23h45m6sx17 4h30sx8 1hx7"
    exit 1
fi


# check arg syntax
for arg in $@
do
    echo $arg | egrep '^([1-9][0-9]*d)?([1-9][0-9]*h)?([1-9][0-9]*m)?([1-9][0-9]*s)?x[1-9][0-9]*$' > /dev/null 
    if [ $? -ne 0 ]; then
        echo "Error. $arg syntax not correct"
        exit 2
    fi
done


for arg in $@
do

    duration=`echo ${arg%x*} | sed -e 's/d/*86400+/;s/h/*3600+/;s/m/*60+/;s/s//;s/+$//' | bc`
    for count in `seq ${arg#*x}`
    do
        ./program-a --duration $duration
    done
done

If you need to run program-a 1.5 day once, 3 hour and 5 seconds twice and 30 minutes thrice, all you need to do is
./loop.sh 1d12hx1 3h5sx2 30mx3
I hope this blog shows you how a simple script can evolve into something so generic that your future test scripts can be based on.

Labels:

Sunday, May 29, 2011

Monitor Solaris Zones with prstat

Solaris provides an interactive command line tool, prstat, to help you to monitor the zone utilisation if you provide "-Z" flag. The screen displays both processes info and zones info to fit your terminal window.
   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP       
  8632 chihung  7204K 6792K cpu10   49    0   0:00:00 0.0% prstat/1
   584 root     1696K  684K sleep   59    0   0:00:00 0.0% smcboot/1
   260 root     2008K 1244K sleep   59    0   0:00:00 0.0% ttymon/1
   228 root     2264K  924K sleep   59    0   0:01:16 0.0% cron/1
   112 root     3524K 2600K sleep   59    0   0:00:00 0.0% picld/5
   110 root     2140K 1288K sleep   59    0   0:00:00 0.0% syseventd/14
   255 root     1696K  904K sleep   59    0   0:00:05 0.0% sac/1
   231 daemon   2280K  940K sleep   59    0   0:00:00 0.0% rpcbind/1
   130 root     7952K 6216K sleep   59    0   0:00:03 0.0% devfsadm/72
 22936 root     3348K 1356K sleep   59    0   0:00:00 0.0% sshd/1
  9186 root     4424K 2508K sleep   59    0   0:00:00 0.0% htt_server/2
   237 daemon   2028K 1276K sleep   60  -20   0:00:00 0.0% nfs4cbd/2
   138 daemon   4076K 2188K sleep   59    0   0:09:56 0.0% kcfd/4
   238 daemon    495M  494M sleep   59    0   0:06:46 0.0% nfsmapid/4
   137 root     1312K  888K sleep   59    0   0:00:00 0.0% powerd/2
     9 root     9672K 8720K sleep   59    0   0:03:00 0.0% svc.configd/17
     7 root       12M   10M sleep   59    0   0:02:47 0.0% svc.startd/13
   239 daemon   2336K 1512K sleep   59    0   0:00:00 0.0% statd/1
ZONEID    NPROC  SIZE   RSS MEMORY      TIME  CPU ZONE                        
     0      123 1489M 1008M   3.0%  10:01:44 0.0% global                      
    26       29   90M   56M   0.1%   0:18:41 0.0% john                      
    27       33  169M  123M   0.3%   0:23:04 0.0% mark                 
     5       31  155M  118M   0.3%   0:18:47 0.0% node102                     
     2       32  161M  122M   0.3%   1:21:49 0.0% sgeexec2                    
    62       33  168M  122M   0.3%   0:22:38 0.0% henry                     
    19       29   89M   54M   0.1%   0:18:56 0.0% peter                     
Total: 2221 processes, 8427 lwps, load averages: 1.65, 4.26, 2.60

With "-c" flag to avoid overwritting the previous display and "-n 1,99999" to tell prstat to display up to 99999 zones (that should be enough for all your zones) information, you can pipe that to AWK to extract the MEMORY and CPU. If you schedule this task to start at mid-night daily at a sampling interval of 300 with 288 samples, you cover the whole day monitoring of all your zones.

Here is a script to convert the prstat zone data to CSV

#! /bin/ksh


export PATH=/usr/bin:/bin:/usr/sbin:/sbin


# zone IDs store as comma separated
zids=`zoneadm list -v | awk 'NR>1{printf("%d,",$1)}'`
zids=${zids%,}

# zone NAMEs store as comma separated
znames=`zoneadm list -v | awk 'NR>1{printf("%s,",$2)}'`
znames=${znames%,}


prstat -Z -n 1,99999 $1 $2 | nawk -v zids=$zids -v znames=$znames '
# print header (mem/* and cpu/*)
BEGIN {
 n=split(zids,a,",")
 m=split(znames,b,",")
 # %mem ($5)
 for(i=1;i<=n;++i){
  printf("mem/%s,",b[i])
 }
 # %cpu ($7)
 for(i=1;i<=n;++i){
  printf("cpu/%s,",b[i])
 }
 printf("\n")
}
# store each interval in array
/ZONEID/,/Total/ {
 if ( $0 !~ /ZONEID/ && $0 !~ /Total/ ) {
  gsub("%","")
  mem[$1]=$5
  cpu[$1]=$7
 }
}
/Total/ {
 for(i=1;i<=n;++i) {
  printf("%s,",mem[a[i]])
 }
 for(i=1;i<=n;++i) {
  printf("%s,",cpu[a[i]])
 }
 printf("\n")
}'

Let's run through it with an interval of 10 seconds for 4 samples. If you have 3 zones in this machine, the output will look like this

./zstat.sh 10 4
mem/global,mem/zone1,mem/zone2,mem/zone3,cpu/global,cpu/zone2,cpu/zone3,
3.2,1.2,1.0,1.0,23.0,5.0,7.0,9.0,2.0,
4.7,1.5,1.7,1.5,31.0,15.0,6.0,9.0,1.0,
11.0,5.7,2.3,3.0,40.0,5.0,22.0,13.0,5.0,
13.2,7.2,4.0,2.0,34.0,5.0,17.0,10.0,7.0,
I ran this script in my machines with 67 zones and imported the CSV into openoffice, here is the sample output:

Labels: , ,

Saturday, March 05, 2011

No More Hanging Jobs in Cron

Have you encountered 'prtdiag' or other commands hang for whatever reason? If your script happens to run these commands and launch from cron, your job will simply pile up until cron hits the limit. By default, Solaris configured cron to run 100 concurrent jobs and the next 101th job will just fail.

I developed a launcher program (watchdog) to limit the runtime of script (worker) that may have the above mentioned behaviour. It works well with my worker script and it should work for other programs too. So, no more hanging job in cron !!

#! /bin/ksh
#
# A watchdog program to limit the elapsed time of the worker shell script
# to avoid hanging processes that can pile up if worker runs under cron
#


export PATH=/usr/bin:/usr/sbin:/bin


#
# default time limit is 60 seconds
#
timelimit=${1:-60}

B
worker="${0%/*}/check-worker.ksh"
worker_name=${worker##*/}
worker_name=${worker_name%.*}
if [ ! -f $worker ]; then
    echo "Error. \"$worker\" cannot be found"
    exit 1
fi
if [ ! -x $worker ]; then
    echo "Error. \"$worker\" is not executable"
    exit 2
fi


watchdog()
{
    sleep 1; # wait for the worker to start
    while [ $timelimit -gt 0 ]
    do
        # pgrep is available since 5.8, else use ps -ef | grep -v grep | grep $worker_name
        jobid=`pgrep $worker_name`
        if [ $? -eq 1 ]; then
            break
        else
            sleep 1
        fi
        ((timelimit-=1))
    done
    if [ $timelimit -eq 0 ]; then
        # kill worker + child processes
        ptree $jobid | awk '$1=='$jobid'{start=1}start==1{print $1}' | while read pid
            do
                kill -TERM "$pid" > /dev/null 2>&1
            done
    fi
}


#
# start the watchdog before the worker
#
watchdog &


tmpfile="/tmp/.$work_name.$$"
$worker > $tmpfile 2>&1 &
worker_id=$!
wait $worker_id > /dev/null 2>&1
rc=$?


if [ $rc -ne 0 ]; then
    # replace this line to do whatever you want, send email, sms, logger....
    #
    # echo .... | mailx someone@somewhere.com

    details=`cat $tmpfile 2>/dev/null`
    echo "Exit status=$rc. There is a problem with the server '`hostname`' - $details"
fi


rm -f $tmpfile

Labels: ,

Feel Like A Scripting Guy Again!

I have not been scripting for quite a while and feel like I don't quality as a "Scripting Guy in the Lion City" anymore. Luckily my colleage (now is ex-colleague, 'cos I will be starting my new job next week) approached me to develop script to check hardware error messages from the /var/adm/messages in Solaris. Now I am as happy as a sandboy, or I should say "As Happy As A Scripting Guy!"

Anyway, here is my last script in the company.

If this script is going to run periodically via cron, we cannot just 'grep' certain pattern from the file. What if the /var/adm/messages has not been rotated for days or even weeks, it will be pretty inefficient to simply scan through the entire file. BTW, I have seen /var/adm/messages as big as few GB. Also, problem fixed previously will also appear in /var/adm/messages if it is not rotated.

The only way is to 'grep' only the content from where it left off in the previous run. It is easy to keep track of the current file size and store this information somewhere for the next poll to consume. The challenge is to 'seek' to the previous location and output only the content between the two polls. However, I am not able to find any UNIX commands that allow me to 'cat' file based on byte range.

In order to accomplish this, some high level scripting languages are used. Perl is selected because it is available since Solaris 8. Below one-liner is able to 'cat' only the updated contents in /var/adm/messages.

POS=$prev_pos perl -e 'open(F,"/var/adm/messages");seek(F,$ENV{"POS"},0); while($line=<F>){print $line;}'

Who say shell script is slow and inefficient! Always challenge yourself for a better solution.

Here is the complete script doing all the checking

#! /usr/bin/ksh
#
# Check on all the faults
#       hardware, svm, vx, df, /var/adm/messages, ifconfig, psrinfo
# Exit 1 if there is an error
#



PATH=/usr/bin:/usr/sbin:/usr/platform/`arch -k`/sbin:/usr/sfw/bin:/usr/local/bin
export PATH
LD_LIBRARY_PATH=/usr/lib:usr/platform/`arch -k`/lib:/usr/sfw/lib:/usr/local/lib
export LD_LIBRARY_PATH


Update()
{
    # if you do not want output, simply comment out the 'echo' command
    # remember to leave the colon (no-ops) command there
    echo "$1,\c"
    :
}


RC=0


#
# prtdiag(1M) - display system diagnostic information
#
# Exit Status
# 0 No failures or errors are detected in the system.
# 1 Failures or errors are detected in the system.
# 2 An internal prtdiag error occurred, for example, out of memory.
#
prtdiag > /dev/null 2>&1
[ $? -ne 0 ] && ((RC+=1)) && Update prtdiag



#
# fmadm(1M) - fault management configuration tool
#
# Exit Status
# 0 Successful completion.
# 1 An error occurred. Errors include a failure to communicate with fmd or 
#   insufficient privileges to perform the requested operation.
# 2 Invalid command-line options were specified.
#
osver=`uname -r`
if [ "${osver#*.}" -ge 10 ]; then
    fmadm faulty > /dev/null 2>&1
    [ $? -ne 0 ] && ((RC+=1)) && Update fmadm
fi



#
# df(1M) - displays number of free disk blocks and free files
#
# Exit Status
# 0  Successful completion.
# >0 An error occurred.
#
df -l > /dev/null 2>&1
[ $? -ne 0 ] && ((RC+=1)) && Update df



#
# ifconfig(1M) - configure network interface parameters
#
# Interface flag:
# FAILED
#     The  interface  has  failed.  New  addresses  cannot  be
#     created  on this interface. If this interface is part of
#     an IP network multipathing group, a failover will  occur
#     to another interface in the group, if possible
#
ifconfig -a | grep FAILED > /dev/null 2>&1
[ $? -eq 0 ] && ((RC+=1)) && Update ifconfig



#
# check svm via metadb and metastat
#
pkginfo SUNWmdu > /dev/null 2>&1
if [ $? -eq 0 ]; then
    metaset=`metaset`
    metadb > /dev/null 2>&1
    if [ $? -eq 0 -a ! -z $metaset ]; then

        # output should not have these characters from metadb, see metadb -i man page
        # d - replica does not have an associated device ID.
        # r - replica does not have device relocation information
        # W - replica has device write errors
        # M - replica had problem with master blocks
        # D - replica had problem with data blocks
        # F - replica had format problems
        # S - replica is too small to hold current database
        # R - replica had device read errors
        # B - tagged data associated with the replica is not valid
        metadb -i | sed -n '2,$s/[1-9][0-9].*//p' | egrep '[drWMDFSRB]' > /dev/null 2>&1
        rc1=$?
        #
        metastat | awk '$1=="State:" && $2!="Okay" {exit(1)}'
        rc2=$?
        if [ $rc1 -ne 0 -o $rc2 -ne 0 ]; then
            ((RC+=1))
            Update svm
        fi
    fi
fi



#
# psrinfo(1M) - displays information about processors
# Exit Status
# 0  Successful completion.
# >0 An error occurred.
#
psrinfo > /dev/null 2>&1
rc1=$?
psrinfo | awk '$2!="on-line"{exit(1)}'
rc2=$?
if [ $rc1 -ne 0 -o $rc2 -ne 0 ]; then
    ((RC+=1))
    Update psrinfo
fi



#
# VX
#
pkginfo VRTSvxfs VRTSvxvm > /dev/null 2>&1
if [ $? -eq 0 ]; then
    vxdisk list 2>&1 | grep -i fail > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        ((RC+=1))
        Update vx
    fi
fi



#
# 'grep' from /var/adm/messages
# need to seek to the previous position, instead of scan through the whole file again
#
hidden=${0##*/}
hidden="/tmp/.${hidden%%.*}_var-adm-messages"
prev_pos=0
if [ -f $hidden ]; then
    prev_pos=`cat $hidden`
fi
# if previous position is less than current file size, likely file has been recycled
filesize=`ls -l /var/adm/messages | awk '{print $5}'`
if [ $prev_pos -gt $filesize ]; then
    prev_pos=0
fi
#
perl -e 'open(F,"/var/adm/messages");seek(F,'$prev_pos',0); while($line=<F>){print $line;}' | \
    egrep -i 'ECC error|PS[0-9] has FAILED|Link Down|reboot after panic|file system full|by NR list: I/O error|fmd.*SEVERITY: Critical' > /dev/null 2>&1
if [ $? -eq 0 ]; then
    ((RC+=1))
    Update /var/adm/messages
fi
ls -l /var/adm/messages | awk '{print $5}' > $hidden



if [ $RC -gt 0 ]; then
    exit 1
fi

Labels: , ,

Monday, November 01, 2010

Merger of the Merger

I was given 50+ EMC Navisphere performance data and asked to merge them into a single data file for Navisphere to import. The bad news is the existing EMC Navisphere Analyzer Command Line Interface (naviseccli) can only allow to merge 2 files at a time.
naviseccli analyzer -archivemerge -data archive1 archive2 [-out outputarchive] [-overwrite y|n]

Working with this limitation, I developed a merger shell to merge all these performance data. Assuming you have the following performance files with timestamp builtin in the filename, my approach is to generate the 1st merger file based on the first two files. After that, I will loop through the rest (starting from the 3rd file) of them together with the merger file to form a new archive. You will need to have a temporary file to house the intermediate archive and swap it before the next loop.

# ls -1
CKM12345678901_SPA_2010-10-24_17-00-41-GMT_P08-00.nar
CKM12345678901_SPA_2010-10-24_19-00-41-GMT_P08-00.nar
CKM12345678901_SPA_2010-10-24_21-00-41-GMT_P08-00.nar
CKM12345678901_SPA_2010-10-26_20-00-55-GMT_P08-00.nar
...
CKM12345678901_SPA_2010-10-29_10-00-46-GMT_P08-00.nar
CKM12345678901_SPA_2010-10-29_12-00-46-GMT_P08-00.nar
CKM12345678901_SPA_2010-10-29_14-00-47-GMT_P08-00.nar
CKM12345678901_SPA_2010-10-29_16-00-46-GMT_P08-00.nar
CKM12345678901_SPA_2010-10-29_18-00-46-GMT_P08-00.nar

Here is the merger.sh script

#! /bin/ksh


if [ $# -ne 1 ]; then
        echo "Usage: $0 <mergefile>"
        exit 1
fi
mergefile="$1"
if [ -f $mergefile ]; then
        echo "Error. $file already exist"
        exit 2
fi


export PATH=/opt/Navisphere/bin:/usr/bin:/bin:/usr/sbin:/usr/local/bin
export LD_LIBRARY_PATH=/opt/Navisphere/lib:/usr/lib:/lib:/usr/local/lib


tmpls=`mktemp`
tmpmerge=`mktemp`


ls -1 CKM*.nar > $tmpls


#
# do the first 2 files
#
file1=`head -1 $tmpls`
file2=`head -2 $tmpls | tail -1`
echo "Processing $file1 $file2 ... \c"
naviseccli analyzer -archivemerge -data $file1 $file2 -out $mergefile
echo "Completed."


#
# do the rest of the files
#
awk 'NR>2&&NR<=10' $tmpls | while read fileN
do
        echo "Processing $fileN ... \c"
        naviseccli analyzer -archivemerge -data $mergefile $fileN -out $tmpmerge
        mv $tmpmerge $mergefile
        echo "Completed."
done


rm -f $tmpls $tmpmerge

See merger.sh in action:

# ./merger.sh new.nar
Processing CKM12345678901_SPA_2010-10-24_17-00-41-GMT_P08-00.nar CKM12345678901_SPA_2010-10-24_19-00-41-GMT_P08-00.nar ... Completed merging archives.
Completed.
Processing CKM12345678901_SPA_2010-10-24_21-00-41-GMT_P08-00.nar ... Completed merging archives.
Completed.
Processing CKM12345678901_SPA_2010-10-26_20-00-55-GMT_P08-00.nar ... Completed merging archives.
Completed.
...
Processing CKM12345678901_SPA_2010-10-29_10-00-46-GMT_P08-00.nar ... Completed merging archives.
Completed.
Processing CKM12345678901_SPA_2010-10-29_12-00-46-GMT_P08-00.nar ... Completed merging archives.
Completed.
Processing CKM12345678901_SPA_2010-10-29_14-00-47-GMT_P08-00.nar ... Completed merging archives.
Completed.
Processing CKM12345678901_SPA_2010-10-29_16-00-46-GMT_P08-00.nar ... Completed merging archives.
Completed.
Processing CKM12345678901_SPA_2010-10-29_18-00-46-GMT_P08-00.nar ... Completed merging archives.
Completed.

Labels:

Saturday, October 16, 2010

Key-Value Pair in Multi-line Records

If you have to deal with multi-line records, AWK is definitely your friend. Sometimes the records come in the form of first record is the key and the next record is the value. To make matter worse, the value record can be optional, ie it may not exist at all.

For example, the following sample data set have the above characteristics. What we need is a script to list down the values for a particular pool name. The first 3 lines are headers which can we going to ignore.

$ cat testdata.txt
media media robot robot robot side/ ret    size status
 ID type type   # slot face level  KBytes
----------------------------------------------------------------------------
One pool

A00001 HCART    TLD   0   26  -  10     101568 AVAILABLE

Two pool

B00001 HCART    NONE   -   -  -  -     - AVAILABLE
B00002 HCART    NONE   -   -  -  -     - AVAILABLE

Three pool

C00001 HCART    NONE   -   -  -  -     - AVAILABLE
C00002 HCART    NONE   -   -  -  -     - AVAILABLE
C00003 HCART    NONE   -   -  -  -     - AVAILABLE

Zero pool

Four pool

D00001 HCART2   NONE   -   -  -  -     - AVAILABLE
D00002 HCART3   NONE   -   -  -  -     - AVAILABLE
D00003 HCART3   NONE   -   -  -  -     - AVAILABLE
D00004 HCART3   NONE   -   -  -  -     - AVAILABLE

By changing the default AWK FS (field separator) and RS (record separator) to be newline and blank line repsectively, we are able to handle the above multi-line records. In order to accommodate zero 'value' in a record, we need to put in the logical in the AWK code.

$ cat pool.sh
#! /bin/sh

PATH=/usr/bin:/bin:/usr/sbin:/usr/local/bin
LD_LIBRARY_PATH=/usr/lib:/lib:/usr/local/lib


if [ $# -ne 2 ]; then
 echo "Usage: $0  \n"
 exit 1
fi
txtfile=$1
pool=$2
if [ ! -f $txtfile ]; then
 echo "Error. $txtfile does not exist\n"
 exit 2
fi


sed -n '4,$p' $txtfile | awk -v pool="$pool" '
BEGIN {
 FS="\n"
 RS=""
 poolname=sprintf("%s pool", pool)
}
$1 == poolname {
 start=1
 next
}
start==1 && $0 ~ /pool/ {
 exit
}
start==1 {
 for (i=1;i<=NF;++i ) {
         print $i
 }
 exit
}'

See script in action.

$ ./pool.sh testdata.txt One
A00001 HCART    TLD   0   26  -  10     101568 AVAILABLE

$ ./pool.sh testdata.txt Two
B00001 HCART    NONE   -   -  -  -     - AVAILABLE
B00002 HCART    NONE   -   -  -  -     - AVAILABLE

$ ./pool.sh testdata.txt Three
C00001 HCART    NONE   -   -  -  -     - AVAILABLE
C00002 HCART    NONE   -   -  -  -     - AVAILABLE
C00003 HCART    NONE   -   -  -  -     - AVAILABLE

$ ./pool.sh testdata.txt Four
D00001 HCART2   NONE   -   -  -  -     - AVAILABLE
D00002 HCART3   NONE   -   -  -  -     - AVAILABLE
D00003 HCART3   NONE   -   -  -  -     - AVAILABLE
D00004 HCART3   NONE   -   -  -  -     - AVAILABLE

$ ./pool.sh testdata.txt Unknown

$ ./pool.sh testdata.txt Zero

$ 

So what is the big deal ? This is the kind of output you will get from NetBackup /usr/openv/netbackup/bin/goodies/available_media. With this script, you can handle the available_media output with ease.

Labels: ,

Friday, August 27, 2010

Z to gz On The Fly

If you have a lot of compress files (*.Z) and you want to convert them to gzip format to space disk space, here is the function that you can use. The function, Z2gz, make use of standard input and standard output to dynamically uncompress and gzip on the fly to avoiding any intermediate file to be created. Also, it will set the permission, ownership and timestamp to be the same as the original file.

Z2gz()
{
for Z in *.Z
do
    gz="${Z%.Z}.gz"
    uncompress < $Z | gzip > $gz
    touch -r $Z $gz
    getfacl $Z | setfacl -f - $gz
    rm -f $Z
done
}

Z2gz in action. In this exercise, we saved 11,970,771 bytes

$ ls -l *.Z
-rw-------   1 chihung   chihung     5278987 Feb  2  2009 apache.tar.Z
-rw-r-----   1 chihung   chihung     1479993 Aug 27 09:29 freetype-2.3.1-sol10-sparc-local.Z
-rw-r-----   1 chihung   chihung     25318755 Feb  2  2009 ganglia.tar.Z
-rw-r-----   1 chihung   chihung      797471 Aug 27 09:29 libgcc-3.4.6-sol10-sparc-local.Z
-rw-r--r--   1 chihung   chihung     4039745 Feb 19  2009 mediawiki-1.6.12.tar.Z

$ Z2gz

$ ls -l *.gz
-rw-------   1 chihung   chihung     3641373 Feb  2  2009 apache.tar.gz
-rw-r-----   1 chihung   chihung     1019829 Aug 27 09:29 freetype-2.3.1-sol10-sparc-local.gz
-rw-r-----   1 chihung   chihung     16940517 Feb  2  2009 ganglia.tar.gz
-rw-r-----   1 chihung   chihung      527891 Aug 27 09:29 libgcc-3.4.6-sol10-sparc-local.gz
-rw-r--r--   1 chihung   chihung     2814570 Feb 19  2009 mediawiki-1.6.12.tar.gz

Labels: ,

Sunday, August 01, 2010

Failsafe gzip

If you try to gzip file that is currently opened by other process, your program will lose the handler and therefore will not be able to read/write to it. You can verify that the i-node (ls -li) is different after gzip.

In Solaris, you can use fuser to check what processes are currently holding on to the file.

Below script is a fail-safe version to gzip file that has no process holding on to the file.

#! /bin/ksh
#
# gzip those files that no process is holding on to it
#


PATH=/usr/bin:/bin:/usr/sbin


usage()
{
        echo "Usage: $0 -n <name> [-d <dir>] [-b] [-e] [-[1-9]]"
        echo "       -n <name>: part of the file name"
        echo "       -d <dir> : directory to search, default to current"
        echo "       -b       : begins with the <name>"
        echo "       -e       : ends with the <name>"
        echo "       -1 .. -9 : gzip compression flag, default to -6"
}


set -- `getopt n:d:be123456789 $*`
if [ $? != 0 ]; then
        usage
        exit 1
fi


finddir="."
gzip="-6"
for i in $*
do
        case $i in
        -n)
                name=$2
                findname="*${name}*"
                shift 2
                ;;
        -d)
                finddir=$2
                shift 2
                ;;
        -b)
                findname="${name}*"
                shift
                ;;
        -e)
                findname="*${name}"
                shift
                ;;
        -[1-9])
                gzip="$i"
                shift
                ;;
        esac
done


#
# checking
#
if [ -z $findname ]; then
        usage
        exit 2
fi
if [ ! -d $finddir ]; then
        echo "Error. $finddir does not exist"
        exit 3
fi


find $finddir -name "$findname" -type f 2>/dev/null | while read f
do
        pids=`fuser -u $f 2>/dev/null`
        if [ -z $pids ]; then
                echo "Running $gzip $f ... \c"
                gzip $gzip "$f"
                echo OK
        fi
done

Labels: ,

Thursday, July 29, 2010

Filenames With Spaces

Filename with space may be okay in Windows environment, but not for UNIX. Recently I encountered a lot of partial backup due to filenames ended with space(s). You will be surprised to see the kind of files the user created or transferred from Windows to UNIX and I blogged about it a year ago.

To be able to evenly split the backup streams into roughly equal amount of size, my script uses find /some/dir -mount -type f -ls to generate the file list. The output will then be piped to a while loop to sum up the file size. However, shell will auto-collapse white space into a single space if you do not quote the variable. Although quoting variable is able to preserve white spaces, it will not be able to tackle filename ends with space

By applying padding (I used "==" in my below test case) to the end of the filename, I am able to preserve the original filename. Simply truncate the padding before writing to file list will resolve all these white space issue.

BTW, my environment is running Solaris.

$ touch 'a' 'b' 'c' ' start1space' '  start2space' '   start3space' \
        'mid 1space' 'mid  2space' 'mid   3space' \
        'end1space ' 'end2space  ' 'end3space   '

$ find . -type f -ls | while read x x x x x x x x x x filename
do
  echo --$filename--
done                               
--./a--
--./b--
--./c--
--./ start1space--
--./ start2space--
--./ start3space--
--./mid 1space--
--./mid 2space--
--./mid 3space--
--./end1space--
--./end2space--
--./end3space--

$ find . -type f -ls | while read x x x x x x x x x x filename
do
  echo "--$filename--"
done                             
--./a--
--./b--
--./c--
--./ start1space--
--./  start2space--
--./   start3space--
--./mid 1space--
--./mid  2space--
--./mid   3space--
--./end1space--
--./end2space--
--./end3space--

$ find . -type f -ls | sed 's/$/==/' | while read x x x x x x x x x x filename
do
  echo "--${filename%==}--"
done
--./a--
--./b--
--./c--
--./ start1space--
--./  start2space--
--./   start3space--
--./mid 1space--
--./mid  2space--
--./mid   3space--
--./end1space --
--./end2space  --
--./end3space   --

Labels: ,

Wednesday, April 14, 2010

How Deep Is The Directory Structure

Recently our Netbackup failed due to some very long full-path name, guess what's the max length of the full-path? The length is 1037 character long. Below one-liner can tell you how deep is your directory and the corresponding directory I am running this in my home directory under Cygwin.
$ find /home/user -type d | awk -F"/" '{if(NF>max){max=NF;maxpath=$0}}END{print max-1, maxpath}'
12 /home/user/src/Django-1.1.1/build/lib/django/contrib/gis/db/backend/mysql

Labels:

Tuesday, March 23, 2010

Older == Not Newer

Quite often we need to clean up old files in directory, but the criteria is often based on ctime/atime/mtime in find with unit in days. In certain situation, this may not be fine-grain enough to locate files. In find, you can specify the -newer flag to locate files newer than the file reference. However, find does not have -older. What you can do is to specify 'not newer' to represent 'older':
\( ! -newer reference \)

Here I created a lot of files (4320) with file name based on time stamp and tried to use this trick to delete files older than the reference (log-200912301450). See my previous post in how I use the -newer flag too.



# yr=2009

# for mth in `seq -w 7 12`
do
    for day in `seq -w 1 30`
    do
        for hr in `seq -w 2 6 24`
        do
                for min in `seq -w 0 10 50`
                do
                        touch -t $yr$mth$day$hr$min log-$yr$mth$day$hr$min
                done
        done
    done
done

# ls | wc -l
4320

# ls -lrt | head
total 0
-rw-r--r-- 1 root root 0 2009-07-01 02:00 log-200907010200
-rw-r--r-- 1 root root 0 2009-07-01 02:10 log-200907010210
-rw-r--r-- 1 root root 0 2009-07-01 02:20 log-200907010220
-rw-r--r-- 1 root root 0 2009-07-01 02:30 log-200907010230
-rw-r--r-- 1 root root 0 2009-07-01 02:40 log-200907010240
-rw-r--r-- 1 root root 0 2009-07-01 02:50 log-200907010250
-rw-r--r-- 1 root root 0 2009-07-01 08:00 log-200907010800
-rw-r--r-- 1 root root 0 2009-07-01 08:10 log-200907010810
-rw-r--r-- 1 root root 0 2009-07-01 08:20 log-200907010820

# ls -lrt | tail
-rw-r--r-- 1 root root 0 2009-12-30 14:20 log-200912301420
-rw-r--r-- 1 root root 0 2009-12-30 14:30 log-200912301430
-rw-r--r-- 1 root root 0 2009-12-30 14:40 log-200912301440
-rw-r--r-- 1 root root 0 2009-12-30 14:50 log-200912301450
-rw-r--r-- 1 root root 0 2009-12-30 20:00 log-200912302000
-rw-r--r-- 1 root root 0 2009-12-30 20:10 log-200912302010
-rw-r--r-- 1 root root 0 2009-12-30 20:20 log-200912302020
-rw-r--r-- 1 root root 0 2009-12-30 20:30 log-200912302030
-rw-r--r-- 1 root root 0 2009-12-30 20:40 log-200912302040
-rw-r--r-- 1 root root 0 2009-12-30 20:50 log-200912302050

# find . \( ! -newer log-200912301450 \) -type f -exec rm -f {} \;

# ls -lrt
total 0
-rw-r--r-- 1 root root 0 2009-12-30 20:00 log-200912302000
-rw-r--r-- 1 root root 0 2009-12-30 20:10 log-200912302010
-rw-r--r-- 1 root root 0 2009-12-30 20:20 log-200912302020
-rw-r--r-- 1 root root 0 2009-12-30 20:30 log-200912302030
-rw-r--r-- 1 root root 0 2009-12-30 20:40 log-200912302040
-rw-r--r-- 1 root root 0 2009-12-30 20:50 log-200912302050

Labels:

Thursday, February 04, 2010

My Solaris Cannot Fork

Recently one of my Solaris servers cannot fork due to "Resource temporarily unavailable". It was flagged out in the system message via syslog

Although I was still active in my ssh login session, I was not able to run any command (like ls, w, cat...) 'cos they need to fork out processes from the shell. In this kind of scenario, you are basically handicapped. After some searching on the web, I found this link that showed you how to simulate other commands using shell built-in functions. With this, there is no forking involved. Basically it take advantage of loop construct and file redirection.

I am trying to show you how you can do a few things with built-in functions that may help you to save the day. I believe it can do more than what I described here. BTW, they run on Korn shell.

Equivalent of "cat":

my_cat()
{
        while read line
        do
                echo $line
        done < $1
}

Equivalent of "wc":

my_wc()
{
        nl=0
        nw=0
        nc=0
        in=$1
        while read line
        do
                ((nl=nl+1))
                set -- $line
                ((nw=nw+$#))
                ((nc=nc+${#line}+1))
        done < $in
        echo "\t$nl\t$nw\t$nc\t$in"
}

Equivalent of "ls"

my_ls()
{
my_ls()
{
        echo $@ | while read i
        do
                echo $i
        done
}

In such situation, you may want to count the total number of files opened in the system (based on /proc/*/fd/*, exclude stdin/stdout/stderr):

my_nfd()
{
        n=0
        for fd in /proc/[0-9]*/fd/*
        do
                # exclude stdin/stdout/stderr (0/1/2)
                if [ ${fd##*/} -gt 2 ]; then
                        ((n=n+1))
                fi
        done
        echo $n
}

Labels: , ,

Friday, January 15, 2010

HBA I/O Utilisation Monitoring

I recently just finished the development of monitoring 17 Brocade fibre channel switches with over 1200+ ports in total. The implementation is solely based on UNIX shell script, RRDtool, Tcl, Apache Web Server by polling the switches using SNMP.

Instead of polling individual port, we 'snmpwalk' the swFCPortTxWords (1.3.6.1.4.1.1588.2.1.1.1.6.2.1.11) and swFCPortRxWords (1.3.6.1.4.1.1588.2.1.1.1.6.2.1.12) MIB branches. With this, we only have to do two polls per switch. The output will be parsed by a Tcl program to output 'update somefile.rrd N:value' data stream and pipe it to 'rrdtool -' to update all the rrd files in one parse. Here is a sample pseudo code

for switch in $all_switches
do
  for mib in swFCPortTxWords swFCPortRxWords
  do
      snmpwalk -v $version -c $community $switch $mib | tcl-program
      # expected output: "update somefile.rrd N:value"
  done
done | rrdtool -

All these runs on Solaris. BTW, the search form allows you to key in search patten using regular expression. The return page provides a summary plot link to aggregate all traffic in one plot.

Below shows some of the screen dump.
Main page shows all the switches.

Click on the 4th switch and this will show you all the FC ports:

Click on the 4th port in the 4th switch. It shows you the daily, weekly, monthly and yearly Tx/Rx traffic

If you use the search form, which can take regular expression, it returns the matching switch ports. The result page will include a Summary plot link to allow user to put all the traffic in one single page.

A daily summary plot

A weekly summary plot

Labels: , , ,

Thursday, November 19, 2009

The AWK Way

Today I was given the task of converting few hundred files (743 to be exact) into CSV format. The filename is prefixed with hostname with a fix suffix and the content contains all the local user names. The task is to put them in rows with hostname in the 1st column and usernames in the 2nd column onwards. One more requirement is to exclude a few users in the output. My initial solution is very much unix shell script-based. Although this is an one-off 'throw-away' solution, it is pretty inefficient because there is a lot of process creation within a for loop. It took 1 min 39.453 sec. After some thoughts, I reckoned it is possible to do it efficiently in just AWK. With the help of some of the built-in variables like FILENAME / NR / FNR, we can process all the input files within a single AWK code. The below code works in Cygwin. The runtime for the AWK code is 2.797 sec, that's 35 times faster !
$ ls *txt
host1_root.txt  host2_root.txt  host3_root.txt  host4_root.txt

$ paste *txt
usera   usere   userm   userx
userb   userx   userx   userw
userc   userf   usern   usery
userd   userg   usero   userz
userdx  usery   userp
userdy  userh   userx
        userz   userq
        useri   userqx
        userj   userr
        userk   userz
        userl   users
        userx   usert
                usery

$ cat a.awk
#! /usr/bin/awk -f


BEGIN {
        suffix="_root.txt"
        len=length(suffix)
}
#
# print CR if first line in input file except first file
FNR==1 && NR>1 {
        printf("\n")
}
#
# print hostname
FNR==1 {
        host=substr(FILENAME, 0, length(FILENAME)-len)
        printf("%s", host)
}
#
# print users, but exclude certain users
$0 !~ /^(userx|usery|userz)$/ {
        printf(",%s", $0)
}


$ ./a.awk *.txt
host1,usera,userb,userc,userd,userdx,userdy
host2,usere,userf,userg,userh,useri,userj,userk,userl
host3,userm,usern,usero,userp,userq,userqx,userr,users,usert
host4,userw

Labels: , ,

Saturday, November 07, 2009

Finding Newer Files

Although find provides flags to locate files newer than certain days (-mtime -2), it is not fine grain enough to allow user to specify based on user-defined timestamp. Below script will touch a temporary file with specific timestamp and find will make use of it as a reference by using the "-newer" flag. FYI, this has been tested on Solaris

#! /bin/ksh

if [ $# -ne 2 ]; then
        echo "Usage: $0 directory time"
        echo "       time - a decimal number of the form: [[CC]YY]MMDDhhmm[.SS]"
        exit 1
fi
directory=$1
timestamp=$2


if [ ! -d $directory ]; then
        echo "Error. Directory $directory does not exist"
        exit 2
fi


tmpfile="/tmp/${0##*/}-$$"
touch -t $timestamp $tmpfile > /dev/null 2>&1
if [ $? -ne 0 ]; then
        echo "Error. Incorrect time format [[CC]YY]MMDDhhmm[.SS]"
        exit 2
fi


trap "rm -f $tmpfile; exit 0" EXIT


find $directory -newer $tmpfile -local -mount -type f

Labels: ,

Monday, October 12, 2009

Number of Days in a Month

If you have to loop through everyday in a month to generate daily summary, you may want to know how many days in a particular month. It may not be as straightforward as you think because you need to take into account of leap year, short months, and so on. Here is a simple trick that can help you on this. Run the cal command to display the calendar and pipe it to awk to pick up the last number from the last non-empty line.
$ cal
    October 2009
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

$ cal | awk 'NF>0{n=$NF}END{print n}'
31

$ cal 2 2012
    February 2012
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29

$ cal 2 2012 | awk 'NF>0{n=$NF}END{print n}'
29

Labels:

Saturday, September 26, 2009

Date Format, N Days Ago

In UNIX shell script, it is very difficult to manipulate date/time using standard UNIX commands. Modern programming languages such as Perl, Python, Tcl, ..., are designed to be a general programming/scripting language that can handle this type of task with ease.

Below shows shell functions that wrap around these general scripting languages to determine the date format that is N days ago.

ago_perl()
{
        # localtime return:
        #       Seconds past the minute
        #       Minutes past the hour
        #       Hours past midnight
        #       Day of the month
        #       Months past the start of the year
        #       Number of years since 1900
        #       Number of days since the start of the week (Sunday)
        #       Number of days since the start of the year
        #       Whether or not daylight savings is active
        days=${1:-1}
        perl -e "@t=localtime(time-86400*$days);\
                printf('%4d-%02d-%02d', @t[5]+1900, @t[4]+1, @t[3])"

}
ago_tcl()
{
        days=${1:-1}
        echo "puts [clock format [expr [clock seconds] - $days*86400] \
                -format {%Y-%m-%d}]" | tclsh
}
ago_python()
{
        days=${1:-1}
        python -c "import time, datetime
t=datetime.datetime.fromtimestamp(time.time()-86400*$days)
print '%4d-%02d-%02d' % (t.year,t.month,t.day)"
}

Here is how you can use any of these functions

$ ago=`ago_perl 45`

$ echo "45 days ago is $ago"
45 days ago is 2009-08-12

Labels: , , ,

Saturday, July 25, 2009

Do What You Think Is Right For The User

I have been collecting disk utilisation for every server (df -k -F ufs; df -k -F vxfs) every day since Feb this year and have them append to a file. The output has been carefully prepended with timestamp and hostname like this
2009-07-14 host1 /dev/dsk/c3t0d0s0    11098457 8391180 2596293   77%    /
2009-07-14 host1 /dev/dsk/c3t0d0s5    6050982 5175437  815036    87%    /var
2009-07-14 host1 /dev/dsk/c3t1d0s2    70573141 10437628 59429782 15%    /d2
2009-07-14 host1 /dev/dsk/c3t0d0s3    51294057 43390875 7390242  86%    /d1

I have no idea of what I am going to do with the data and the file just keep growing. My gut feel tells me that it will be of some use one of these days. Now the file is 21MB in size, 248,059 lines and we are talking about appending 1500+ lines of df output per day.

# ls -lh mon-df.txt
-rw-r--r--   1 root     root     21M  Jul 25 09:00 mon-df.txt

# wc -l mon-df.txt
  248059 mon-df.txt

# tail -1 mon-df.txt
2009-07-25 host1 /dev/dsk/c4t0d0s0  2097152   34406 1933831     2%    /some/dir

# grep -c 2009-07-25 mon-df.txt
1530

Recently when I was talking to the user, I proposed a self-help web page for them to monitor their own partition size and they just loved the idea. Initially the web page was just a text-based summary of those partitions that are above the threshold. After some thoughts, I think I can visualise all these data that I have been collecting using RRDtool. This will give them a historical trending on the growth of the partition.

My colleague advised me, based on his/her experience, not to do extra stuff for user because people will eventually ask for more. If I were to take his/her advice, all the data that I collected will be useless. I am glad that I did not take up the advice. IMO, just do what you think is right for the user and everything will fall into places.

In this exercise, I created a CGI program to 'massage' the data before feeding them to RRDtool for graphing. It takes about 1.8 seconds, which is considered a bit slow. In my CGI script, I tried to do everything from AWK (trying to be smart). Although AWK is very powerful, it is not fast enough when it comes to manipulate so much data. Also, AWK will not be able to take advantage of multiple CPUs. By doing a fast grep (fgrep), which is damn fast for fix string search, and pipe the output to AWK, AWK does not have to handle that many lines and CGI response time has been cut down to less than 0.8 second. When fgrep ... | nawk ... combine in a pipe, it will spawn off two processes to run together and will utilise 2 CPUs/Cores if available. Kind of parallel shell script programming :-)

# time nawk -v host=$host -v fs=$fs -v rrdfile=$rrdfile '
$2==host && $8==fs {
        total=$4/(1024*1024)
        used=$5/(1024*1024)
        gsub("-","",$1)
        printf("update %s %s %.2lf %.2lf\n", rrdfile, $1, total, used)
}' mon-df.txt > /dev/null

real    0m1.764s
user    0m1.668s
sys     0m0.056s

# time fgrep $host mon-df.txt | time nawk -v host=$host -v fs=$fs -v rrdfile=$rrdfile '
$2==host && $8==fs {
        total=$4/(1024*1024)
        used=$5/(1024*1024)
        gsub("-","",$1)
        printf("update %s %s %.2lf %.2lf\n", rrdfile, $1, total, used)
}' > /dev/null

real        0.7
user        0.0
sys         0.0

real    0m0.752s
user    0m0.718s
sys     0m0.056s

# psrinfo | wc -l
       2

Lesson learned.

  1. Do what you think is right for the user
  2. Use the fastest command upfront to filter the data set before processing can give you performance advantage for large data set.
  3. Having more than one commands (cmd1 | cmd2 | cmd3 ...) to work on the data can reduce run time in a multi-core/cpu system.

Labels: , , ,

Tuesday, July 21, 2009

Auto Logout Those Idle Users

The CentOS OS hardening has this tip to auto-logout those idle users. Setup a readonly TMOUT variable (works in ksh and bash) in /etc/profile so that the user cannot change it. What a noble way of using readonly variable.

Labels:

Saturday, July 18, 2009

New Trick Learned

Learned a new trick from the Shell Programming and Scripting from Unix and Linux Forum. Suppose you need to convert a single column file to multi-column with colon(:) as separator
$ cat a
one
two
three
four
five
six
seven
eight
nine
ten
eleven
twelve

$ cat a | paste -d: - - -
one:two:three
four:five:six
seven:eight:nine
ten:eleven:twelve

$ cat a | paste -d: - - - -
one:two:three:four
five:six:seven:eight
nine:ten:eleven:twelve

$ cat a | paste -d: - - - - - -
one:two:three:four:five:six
seven:eight:nine:ten:eleven:twelve

In Unix, if "-" is specify as the file input, it will take the input from the pipe. In our case, multiple "-" in the paste will consume input one line at a time. Just a recap, I blogged about paste command in Solaris has a limit of no more than 12 files

$ (cat a a a) | paste -d: - - - - - - - - - -
one:two:three:four:five:six:seven:eight:nine:ten
eleven:twelve:one:two:three:four:five:six:seven:eight
nine:ten:eleven:twelve:one:two:three:four:five:six
seven:eight:nine:ten:eleven:twelve::::

$ (cat a a a) | paste -d: - - - - - - - - - - - -
one:two:three:four:five:six:seven:eight:nine:ten:eleven:twelve
one:two:three:four:five:six:seven:eight:nine:ten:eleven:twelve
one:two:three:four:five:six:seven:eight:nine:ten:eleven:twelve

$ (cat a a a) | paste -d: - - - - - - - - - - - - - -
paste: too many files- limit 12

Labels: ,