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: , ,

Thursday, May 28, 2009

How to Implement Restricted Shell

If you want to limit your users from running wild in your system, you may want to consider providing them with restricted shell such as /usr/lib/rsh or /bin/rksh.

According to man page of /usr/lib/rsh, the actions of rsh are identical to those of sh, except that the following are disallowed:

  • changing directory
  • setting the value of $PATH
  • specifying path or command names containing /
  • redirecting output (> and >>)

According to man page of /bin/rksh, the actions of rksh are identical to those of ksh, except that the following are disallowed:

  • changing directory
  • setting the value of SHELL, ENV, or PATH
  • specifying path or command names containing /
  • redirecting output (>, >|, <>, and >>)
  • changing group

Let's start to see how restrictive it can be:

# PATH=/some/dir/do/not/exist /bin/rksh

# ls
/bin/rksh: ls:  not found

# cd /
/bin/rksh: cd: restricted

# /usr/bin/ls
/bin/rksh: /usr/bin/ls: restricted

# echo $PATH
/some/dir/do/not/exist

# ../../../usr/bin/ls
/bin/rksh: ../../../usr/bin/ls: restricted

# pwd
/

# echo abc
abc
As you can see, your search PATH does not exist and therefore you have no access to any of the binaries. Also, you really cannot run anything with absolute or relative path. The only commands you can run are the builtin commands like echo and pwd. That's far too restrictive. In order to really limit the users to run only a subset of commands, we create a /rbin directory and copy (or hard link) binaries that are absolutely required. In this demo, I only provide ls, vi, more and grep.
# mkdir /rbin

# for i in ls vi more grep
do
ln /usr/bin/$i /rbin/.
done

# PATH=/rbin /bin/rksh

# ls /var/adm
acct        log         messages.2  sm.bin      utmpx
aculog      messages    messages.3  spellhist   vold.log
exacct      messages.0  pool        streams     wtmpx
lastlog     messages.1  sa          sulog

# more /etc/release
                        Solaris 10 1/06 s10x_u1wos_19a X86
           Copyright 2005 Sun Microsystems, Inc.  All Rights Reserved.
                        Use is subject to license terms.
                           Assembled 07 December 2005

# grep Solaris /etc/release
                        Solaris 10 1/06 s10x_u1wos_19a X86

# date
/bin/rksh: date:  not found

I am sure you feel pretty convinced that you are really in control of what your users can and cannot run. Now all you have to do is to set their login shell and ensure /etc/profile set the corresponding PATH to the restricted directory (/rbin).

Labels: ,

Friday, April 10, 2009

paste: too many files- limit 12, in Solaris

When you collect performance data from system, very often you would want to prepend with timestamp (HH:MM:SS). Suppose you collect similar data across a number of servers, you would want to put them together and have them imported in your favourite spreadsheet software for further analysis.

In UNIX, you can paste them together. Below I will create 20 files (host*.txt) with some random data prepended with timestamp

$ for i in `perl -e '$,=" ";print 1..20'`
do
        for j in 1 2 3 4 5 6 7 8 9
        do
                ((v=RANDOM%100))
                echo "0$j:00:00 $v"
        done > host$i.txt
done

$ paste host1.txt host2.txt host3.txt host4.txt
01:00:00 56     01:00:00 61     01:00:00 83     01:00:00 50
02:00:00 59     02:00:00 1      02:00:00 96     02:00:00 72
03:00:00 31     03:00:00 33     03:00:00 71     03:00:00 60
04:00:00 54     04:00:00 29     04:00:00 61     04:00:00 36
05:00:00 62     05:00:00 69     05:00:00 25     05:00:00 36
06:00:00 2      06:00:00 72     06:00:00 76     06:00:00 8
07:00:00 69     07:00:00 59     07:00:00 91     07:00:00 89
08:00:00 51     08:00:00 75     08:00:00 80     08:00:00 61
09:00:00 17     09:00:00 12     09:00:00 59     09:00:00 83

Looks promising. Now, I need to get rid of the redundant timestamp. With AWK, we just have to take the even field values.

$ paste host1.txt host2.txt host3.txt host4.txt | awk '
{
        printf("%s\t%d", $1, $2)
        for ( i=4 ; i<=NF ; i+=2 ) {
                printf("\t%d",$i)
        }
        printf("\n")
}'
01:00:00        56      61      83      50
02:00:00        59      1       96      72
03:00:00        31      33      71      60
04:00:00        54      29      61      36
05:00:00        62      69      25      36
06:00:00        2       72      76      8
07:00:00        69      59      91      89
08:00:00        51      75      80      61
09:00:00        17      12      59      83

So far so good. Now I want to do that for all the hosts (host*.txt). You can use Bash brace expansion to supply the arguments to paste

$ paste host{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}.txt
paste: too many files- limit 12

Ouch! paste cannot take more than 12 files. Stuck ? What we can do is to do one file at a time within a loop. Since I want the output to be imported to spreadsheet, I will output that as comma separated values (CSV) file (all_hosts.csv)

$ tmpfile=".tmp-$$"

$ cp /dev/null all_hosts.csv

$ for i in `perl -e '$,=" ";print 1..20'`
do
        f="host$i.txt"
        paste all_hosts.csv $f > $tmpfile
        mv $tmpfile all_hosts.csv
done

Now we have all the hosts data in one file. The final step is to remove the redundant timestamp.

$ awk '
{
        printf("%s,%d", $1, $2)
        for ( i=4 ; i<=NF ; i+=2 ) {
                printf(",%d",$i)
        }
        printf("\n")
}' all_hosts.csv
01:00:00,56,61,83,50,22,6,83,10,6,88,75,61,46,24,33,8,82,90,29,90
02:00:00,59,1,96,72,80,63,5,61,42,90,7,24,78,58,5,85,35,79,0,46
03:00:00,31,33,71,60,99,41,61,92,34,84,61,46,8,1,52,10,21,82,84,69
04:00:00,54,29,61,36,7,85,69,2,26,42,56,82,17,14,93,95,45,76,3,37
05:00:00,62,69,25,36,54,42,81,8,2,94,44,10,44,28,64,68,96,22,9,45
06:00:00,2,72,76,8,96,21,85,35,89,92,93,98,31,99,67,25,77,43,73,9
07:00:00,69,59,91,89,39,72,11,45,90,9,28,15,22,3,66,64,83,46,60,40
08:00:00,51,75,80,61,22,60,61,12,37,66,24,34,92,21,63,99,27,45,40,35
09:00:00,17,12,59,83,32,44,78,91,16,89,97,52,81,52,51,59,78,14,85,49

Labels: , , ,

Tuesday, February 24, 2009

Sed is Slow for Very Long Stream in Solaris

Today, I realised that my customer is running sed for more than an hour and the strange thing is that the input file is no more than a few MB. Also the pattern in sed is pretty straightforward doing global substitution. BTW, it is running on Solaris 10

Is this the natural of the problem that takes sed to run that long or sed is inefficient in certain circumstances?

In this exercise, I created a file with 2000 lines. The first line has 12 characters and all subsequent lines are having an increment of 12 characters with the last line of 24000 characters.

sed 's/\\\\/@/g;s/\\/@/g' took 35+ minutes on my Sun Fire V440. That's really inefficient. Okay, sed is definitely not the right tool for his job. Let's take a look at the other alternative.

Perl has this "-p" flag that allow your in-line code to be wrap around a
while (<>) { ... # your script } loop so that you can write a one-liner. Guess what, Perl took only 5 seconds to finish that substitution. Hey, that's a lot of CPU cycles saved!

Here is the code and the run time info:

$ cat run.sh
#! /bin/bash

comma()
{
        perl -e 'print "c:\\\\a\\\\b\\\\c,"x'${1:-1}
        echo ""
}

n=1
while [ $n -le $1 ]
do
        comma $n
        ((++n))
done


$ ./run.sh 2000 > run2000.txt


$ wc run2000.txt
    2000    2000 24014000 run2000.txt


$ time sed 's/\\\\/@/g;s/\\/@/g' run2000.txt > run1.txt

real    35m6.692s
user    35m5.559s
sys     0m0.430s



$ time perl -pe 's/\\\\/@/g;s/\\/@/g' run2000.txt > run2.txt

real    0m4.948s
user    0m4.491s
sys     0m0.145s


$ digest -a md5 run1.txt run2.txt
(run1.txt) = 8820c914e0e038cec9da6f0883b6d964
(run2.txt) = 8820c914e0e038cec9da6f0883b6d964


$ uname -a
SunOS chihung 5.10 Generic_118822-11 sun4u sparc SUNW,Sun-Fire-V440


$ psrinfo -v
Status of virtual processor 0 as of: 02/25/2009 00:14:28
  on-line since 12/13/2008 00:37:43.
  The sparcv9 processor operates at 1281 MHz,
        and has a sparcv9 floating point processor.
Status of virtual processor 1 as of: 02/25/2009 00:14:28
  on-line since 12/13/2008 00:37:43.
  The sparcv9 processor operates at 1281 MHz,
        and has a sparcv9 floating point processor.
Status of virtual processor 2 as of: 02/25/2009 00:14:28
  on-line since 12/13/2008 00:37:43.
  The sparcv9 processor operates at 1281 MHz,
        and has a sparcv9 floating point processor.
Status of virtual processor 3 as of: 02/25/2009 00:14:28
  on-line since 12/13/2008 00:37:41.
  The sparcv9 processor operates at 1281 MHz,
        and has a sparcv9 floating point processor.

Labels: , ,

Wednesday, February 11, 2009

How to Remove Files ?

You may have files created with non-printable characters in the file name and have hard time removing them. Although ls has the flag -q to help you to display non-graphic characters as ?, the question mark is not the actual character. It is only a representation of the non-printable character. In order to find out the character, you can use od (octal dump) to dump them out in ASCII characters or backslash escapes format. Simply run ls -1 (minus one) and pipe the output to od -c

To remove these type of files, you can get ls -li to list out all the inode number and use the inode number (inum) in find to locate the file for removal.

# ls -li
123848 -rw-r--r-- 1 user staff 0 Feb 11 21:13 some funny file

# find . -inum 123848 -exec rm -i {} \;
rm: remove regular file `./some funny file'? y

Alternatively, you can do a rm -i ./* and say no to all except the file you want to remove. That may sound a bit dangerous.

Labels:

Friday, January 16, 2009

Shell Script Performance

In UNIX, creating a separate process is considered very expensive. In order to proof this point, I created an empty shell script and I am going to run truss on it to see how many system calls are needed to a barebone shell.

$ cat empty.sh
#! /bin/sh

$ truss -c ./empty.sh

syscall               seconds   calls  errors
_exit                    .000       1
read                     .000       2
open                     .000       8       1
close                    .000       9
time                     .000       1
brk                      .001      17
getpid                   .000       4
mount                    .000       1       1
getuid                   .000       2
getgid                   .000       2
sysi86                   .000       1
ioctl                    .000       5       1
execve                   .000       1
umask                    .000       2
fcntl                    .000       2
fcntl                    .000       2
readlink                 .000       1       1
sigaction                .000       1
getcontext               .000       1
setustack                .000       1
mmap                     .003      34
munmap                   .000      10
xstat                    .001      11       3
getrlimit                .000       1
memcntl                  .000       7
sysconfig                .000      10
lwp_sigmask              .000       1
lwp_private              .000       1
llseek                   .000       3
schedctl                 .000       1
resolvepath              .000       9
stat64                   .000       3
fstat64                  .000      11
open64                   .000       1
                     --------  ------   ----
sys totals:              .016     167      7
usr time:                .006
elapsed:                 .130

Although it took only 0.13 seconds to run, a total of 173 system calls were invoked. Imagine you need to 'daisy-chain' a few commands together and run that 100 times in a loop. Your total run time will be quite substantial.

Below example clearly illustrates this point. Suppose you do a few invert-match (-v) grep on the output from ps -ef and we try to run that 100 times. I am providing you 3 different solutions:

  1. Daisy chain a number of grep commands
  2. Daisy chain a number of fgrep (fast grep - Interpret PATTERN as a list of fixed strings) commands
  3. Use egrep (Interpret PATTERN as an extended regular expression) command
$ cat ex-grep.sh; time ./ex-grep.sh
#! /bin/sh

for i in `perl -e '$,=" ";print 1..100'`
do
 ps -ef | grep -v root | grep -v daemon | grep -v nothing | grep -v oralce | grep -v weblogic > /dev/null 2>&1
done

real 0m14.696s
user 0m4.081s
sys 0m8.142s

$ cat ex-fgrep.sh; time ./ex-fgrep.sh
#! /bin/sh

for i in `perl -e '$,=" ";print 1..100'`
do
 ps -ef | fgrep -v root | fgrep -v daemon | fgrep -v nothing | fgrep -v oralce | fgrep -v weblogic > /dev/null 2>&1
done

real 0m14.392s
user 0m4.085s
sys 0m7.936s

$ cat ex-egrep.sh; time ./ex-egrep.sh
#! /bin/sh

for i in `perl -e '$,=" ";print 1..100'`
do
 ps -ef | egrep -v 'root|daemon|nothing|oralce|weblogic' > /dev/null 2>&1
done

real 0m8.527s
user 0m2.705s
sys 0m3.884s

As you can see, fgrep gives us only a slight improvement even it is based on fixed string matching. This is because "ex-fgrep.sh script" is still forking out as many processes as the "ex-grep.sh", in other words they are having similar overhead. However, the "ex-egrep.sh" has the least overhead because the regular expression matching can group all the OR cases together in one command and therefore avoided all the unnecessary process forking.

$ truss -c ./ex-grep.sh 2>&1 | tail -5
open64                   .013     107       5
                     --------  ------   ----
sys totals:             1.125   11216   1273
usr time:                .366
elapsed:               19.250

$ truss -c ./ex-fgrep.sh 2>&1 | tail -5
open64                   .014     107       5
                     --------  ------   ----
sys totals:             1.128   11241   1279
usr time:                .369
elapsed:               19.340

$ truss -c ./ex-egrep.sh 2>&1 | tail -5
open64                   .013     107       5
                     --------  ------   ----
sys totals:              .593    6819    869
usr time:                .193
elapsed:               11.490

In order to achieve better performance in UNIX shell scripting, we should use the most appropriate tool for the job and explore fully on all the available options. BTW, do you know what is the UNIX philospphy ?

Write programs that do one thing and do it well.

If you are running the above in a multiple CPUs box, you may not see much different because all the forked processes are running on different CPUs. I tested this out in my office's SunFire X4600 with 16 CPUs and there isn't any significance difference.

FYI, the above benchmark result is obtained in OpenSolaris 2008.11 under VirtualBox environment with 1 CPU assigned on my Intel Centrino Duo notebook

Labels: , ,

Monday, December 15, 2008

Find the Last Day of the Previous Month

If you need to generate monthly report for the previous month and you want to get cron to help you to automate the scheduling, you will need this script to determine exactly how many days in the previous month. For example, in sar (system activity report), by default the data are kept only for a month and they will be overwritten. Suppose you need to dump out the CPU utilisation for the entire previous month, you will need to schedule cron to run on the 1st day of the month to find out all the SAR files using
find /var/adm/sa -type f -mtime -30 -name "sa*"
if previous month has 30 days.

Here is short Python script that can do the job:

$ date
Mon Dec 15 21:00:08 MPST 2008

$ cat lastmth.py
#! /usr/bin/python

import datetime, time

mth_this_now   = datetime.date.today()
mth_this_start = datetime.date(mth_this_now.year, mth_this_now.month, 1)
mth_last_end   = mth_this_start - datetime.timedelta(days=1)
print mth_last_end.year, mth_last_end.month, mth_last_end.day

$ ./lastmth.py
2008 11 30

Labels: ,

Saturday, November 01, 2008

Utility to Add/Del/Mod Configuration File

In UNIX, root (or administrator) can delegrate some of the commands to non-privilege users to carry out system administrative tasks by using sudo or RBAC (available only in Solaris

Configuation files like /etc/passwd and /etc/group have equivalent utilities (useradd, usermod, userdel, groupadd, groupmod, groupdel) to handle them properly. However, other configuration files have to rely on vi to do the editing. If someone is given the sudo to vi any file, he/she can sudo vi /etc/sudoers to temporarily include him/her to run any command.

Below script is a 'proof-of-concept' script that you may be able to allow sudo to run to add/del/mod entry in any ascii configuration file. Therefore, no need to allow vi in the sudo. BTW, only pre-defined files can be modified.

#! /bin/sh


usage()
{
        echo "Usage: $0 <config-file> add <line#> <new-data>"
        echo "       if line# > total # of lines, append new-data to end of file"
        echo "Usage: $0 <config-file> del <line#>"
        echo "Usage: $0 <config-file> mod <line#> <new-data>"
}


if [ $# -lt 3 -o $# -gt 4 ]; then
        usage
        exit 1
fi
config="$1"
action="$2"
lineno="$3"


if [ ! -f $config ]; then
        echo "Error. \"$config\" does not exist"
        exit 2
fi


#
# only allow to edit the following files in the list
#
allow="hosts defaultrouter services"
found=0
for cfg in $allow
do
        if [ `basename $config` = "$cfg" ]; then
                found=1
                break
        fi
done
if [ $found -eq 0 ]; then
        echo "Error. You can only edit \"$allow\" files"
        exit 2
fi


#
# lineno <= total
#
total=`wc -l $config | awk '{print $1}'`
if [ $lineno -gt $total ]; then
        lineno=$total
fi


#
# case - add/del/mod
#
case $action in
add)
        newdata="$4"
ex -s "$config" << EOF
${lineno}a
$newdata
.
wq!
EOF
        ;;

del)
ex -s "$config" << EOF
${lineno}d
wq!
EOF
        ;;

mod)
        newdata="$4"
ex -s "$config" << EOF
${lineno}c
$newdata
.
wq!
EOF
        ;;

*)
        usage
        exit 1
        ;;
esac

In order to accomplish the above task, we need to work with primitive command like ex. It may not be easy to find out what are the commands to feed to "ex". In UNIX Power Tool 3rd Ed Chapter 20, it showed that you can use diff -e to find out all the "ex" commands. Here is an illustration. Suppose you want to add 10.0.11.3 monitor to line 5 in the 'hosts' file, all you have to do is to a diff between the new and original file.

$ cat /etc/hosts
127.0.0.1      localhost
10.0.1.11      master loghost
10.0.11.1      gateway
10.0.11.2      storage
10.0.11.12     peter
10.0.11.13     bruce
10.0.11.14     elvis
10.0.11.15     alan
10.0.11.16     chris
10.0.11.17     andy
10.0.11.18     tony
10.0.11.19     cliff
10.0.11.20     richard

$ cat /tmp/hosts.modified
127.0.0.1      localhost
10.0.1.11      master loghost
10.0.11.1      gateway
10.0.11.2      storage
10.0.11.3      monitor
10.0.11.12     peter
10.0.11.13     bruce
10.0.11.14     elvis
10.0.11.15     alan
10.0.11.16     chris
10.0.11.17     andy
10.0.11.18     tony
10.0.11.19     cliff
10.0.11.20     richard

$ diff -e /etc/hosts /tmp/hosts.modified
5a
10.0.11.3      monitor
.
In this example, all you need to program in your script to include 10.0.11.3 monitor using ex will be:
ex -s /etc/hosts << EOF
5a
10.9.8.7   mon
.
wq!
EOF

You may want to program in the script to backup the configuration file before any modification.

Labels: , ,

Thursday, September 18, 2008

Beauty of UNIX Sub-Shell

UNIX sub-shell "(...)" is extremely useful in a couple of situations:
  1. group the output of a few commands and have it to be processed by another command
    (cat /etc/hosts; uname -a; df -k) | wc -l
  2. execute a command in a different directory without having to 'cd' back to your original directory
    (cd /some/other/directory; ./run-a-command > output.txt)
  3. run a group of commands in background
    (run1.sh; run2.sh; run3.sh) &

By applying some of these principles, you can do quite a few amusing things. Do you know that you can combine sub-shell and 'tar' to copy directory recursively:

$ (cd /usr/local; tar cpf - .) | (cd $HOME/local; tar xpf -)

Suppose you need to 'talk SMTP' protocol with the mail server directly:

$ telnet mail.some.mail.server.com 25
Trying 1.2.3.4...
Connected to mail.some.mail.server.com.
Escape character is '^]'.
220-mailsrv.some.mail.server.com -- Server ESMTP (SomeServer Mail Service)
220 Authorised Use Only
HELO chihungchan.blogspot.com
250 mailsrv.some.mail.server.com OK, [203.166.139.133].
MAIL FROM: chihung@some.mail.server.com
250 2.5.0 Address Ok.
RCPT TO: chihung@some.mail.server.com
250 2.1.5 chihung@some.mail.server.com OK.
DATA
354 Please start mail input.
From: chihung@some.mail.server.com
To: chihung@some.mail.server.com
Subject: sub shell

testing sub shell
.
250 Mail queued for delivery.
QUIT
221 Closing connection. Good bye.
Connection closed by foreign host.

You may think that by 'echo' all these input commands and have it piped to the remote smtp port will work, think again. When you echo something, the system immediate output the text to the standard output and finish off the command. However, telnet to some.mail.server.com may take a while. First it requires to resolve the hostname to IP address, follow by the establishing TCP connection to the remote server. All these may take more than a second depending on how busy is your DNS server, how far is the remote host and how busy is the network. So by the time some.mail.server.com is available to talk SMTP, the data is gone. To avoid such situation, you can echo the SMTP commands and sleep for a while in a sub-shell while telnet is trying to establish the connection.

Below will NOT be able to send email because of the above reason:

$ echo "HELO chihungchan.blogspot.com
MAIL FROM: chihung@some.mail.server.com
RCPT TO: chihung@some.mail.server.com
DATA
From: chihung@some.mail.server.com
To: chihung@some.mail.server.com
Subject: sub shell

testing sub shell
.
QUIT" | telnet mail.some.mail.server.com 25
Trying 1.2.3.4...
Connected to mail.some.mail.server.com.
Escape character is '^]'.
Connection closed by foreign host.

This will work by applying the sub-shell trick:

$ (echo "HELO chihungchan.blogspot.com
MAIL FROM: chihung@some.mail.server.com
RCPT TO: chihung@some.mail.server.com
DATA
From: chihung@some.mail.server.com
To: chihung@some.mail.server.com
Subject: sub shell

testing sub shell
.
QUIT"; sleep 5) | telnet mail.some.mail.server.com 25
Trying 1.2.3.4...
Connected to mail.some.mail.server.com.
Escape character is '^]'.
220-mailsrv.some.mail.server.com -- Server ESMTP (SomeServer Mail Service)
220 Authorised Use Only
250 mailsrv.some.mail.server.com OK, [1.2.3.4].
250 2.5.0 Address Ok.
250 2.1.5 chihung@some.mail.server.com OK.
354 Please start mail input.
250 Mail queued for delivery.
221 Closing connection. Good bye.
Connection closed by foreign host.

You can do the same trick for HTTP protocol.

$ (echo "GET / HTTP/1.1
Host: chihungchan.blogspot.com
"; sleep 5) | telnet chihungchan.blogspot.com 80 > /tmp/aa 2>&1

$ head /tmp/aa
Trying 209.85.133.191...
Connected to chihungchan.blogspot.com.
Escape character is '^]'.
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Last-Modified: Mon, 15 Sep 2008 02:19:49 GMT
Cache-Control: max-age=0 private
ETag: "05983cb0-d1a4-47e0-bce1-37b9f2e233db"
Transfer-Encoding: chunked
Date: Thu, 18 Sep 2008 09:23:29 GMT
Server: GFE/1.3

58a
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/x
html1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Chi Hung Chan</title>

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">

If you are running Linux, you can explore the use of nc command. Doing the 'nc' way as suggested in the man page does not work on my office mail server. It gives "220 Authorised Use Only" error message. If you know why, appreciate if you can leave me a comment. BTW, Solaris does not have nc command installed.

Labels: ,

Monday, July 07, 2008

Three Hundred Thousand Files In A Single Directory

A colleague of mine is managing a set of Redhat Enterprise Linux servers. One of web servers the / partition is running low in disk space. The obvious way to find out which directory is the culprit is to run
find / -mount -type d -exec du -sk {} \; | sort -n -k 1
This will show you which directory occupies the most disk space

My colleague managed to locate the /var/spool/mqueue directory and this is the directory to store all the temporary file for sendmail. Apparently it contains 314,000+ files in that single directory. These are the mails that cannot be delivered for some reason and got stuck in the temp directory. If you were to do a "ls -l", you will have to wait for ages to get the directory listing. (See this blog to understand how to minimise the amount of system calls in directory listing).

By reading one of the 314,000+ files, we understand that the content of the file is actually generated from the rsync command in the crontab. The rsync is supposed to syncronise the web content between two servers and it is carried out every minute. The crontab entry looks like this
* * * * * rsync ....
Since the rsync command does not redirect standard output and error, cron will automatically help user to send that via email. Since the sendmail is not running, the mail has to be queued in the system (/var/spool/mqueue/*). For rsync to run every minute, you are talking about having 1440 mails (24*60) in the queue every day. If the server is up for 218 days, you will have 314,000+ files in /var/spool/mqueue.

By appending >/dev/null 2>1& in the rsync entry in crontab, it will simply get ride of all the output from the rsync command. Therefore, no mail will be sent out from cron.

If you intend to clean up all the files in the /var/spool/mqueue, you may want to follow what my colleague did by removing the directory /var/spool/mqueue and re-create the directory. If you were to remove the files using wild card (*), you will get "-bash: /bin/ls: Argument list too long" error.

BTW, do you think Windows can function proper with 314K files in a single directory ?

Labels:

Wednesday, June 25, 2008

Trimming Large Log File

If you have a very large web access log and you cannot afford to shutdown the web server in order to cleanup or rotate the log file, you may want to use this trick. Copy the content to a separate file, if the content is worth saving. Once that is done, copy the /dev/null to overwrite the existing web access log. Don't worry, your web server is still having the same file handler to the existing web access log.

I tested it out by writing a simple Tcl program to append line to a file every 0.1 seconds to simulate the log generation. In a separate terminal, I overwrite the file with /dev/null. The file got trimmed and the Tcl program still keep on appending to the file. The Tcl program looks like this:

$ tclsh
% set fp [open access.log a]
% fconfigure $fp -buffering line
% set n 0
% while 1 {
 puts $fp "[incr n] appending line to log file ..."
 after 100
}

You may loose some records but at least you do not have to worry about the large log file filling up your file system.

Labels: ,

Saturday, November 17, 2007

find, An Interview Question

A colleague of mine was one of the job interviewers and he posted the following question to the interviewee: "Can you tell me how you can remove files that have not been modified for more than 30 days?"

Sad to say that the interviewee was not able to provide the exact command. Sometime it is just not possible to remember those cryptic syntax of UNIX commands. What if the interviewee is able to answer the question, does it mean that he/she know 'find' command well enough ? Also, is the interviewee capable of doing other system administrative jobs? If I were the interviewer, I would follow up with more questions:

  1. Can you tell me how you can remove files that have not been modified for more than 30 days? (original question)
  2. Can you tell me how to find those files that was modified between the last 30 and 60 days?
  3. Can you locate those files that are more than 200 days old, but last modified on the weekends?
  4. Can you locate those files that was last modified on 4 July 2007 ?

Let's create tonnes of files (365 of them) for our experiment using this Tcl script

set now [clock seconds]
for { set i 1 } { $i <= 365 } { incr i } {
    set time [clock format [expr {$now-86400*$i}] -format {%Y%m%d%H%M}]
    exec touch -t $time day-$i
}

    My answers to the above questions:
  1. find . -type f -mtime +30 -exec rm -i {} \; In this case, I include -i in 'rm' to let the system to prompt me before I delete the files. If you are dealing with a lot of files, you may want to use 'rm -f'. Make sure you are deleting the files that you are suppose to delete.
  2. find . -type f \( -mtime +30 -a -mtime -60 \) -ls
  3. find . -type f -mtime +200 | ./wk 'wk' is a simple Tcl script to determine whether the file is last modified on weekend
    while { [gets stdin line] >= 0 } {
          file stat $line fstat
          set wk [clock format $fstat(mtime) -format %a]
          if { [string equal $wk Sun] || [string equal $wk Sat] } {
                  puts $line
          }
    }
    
  4. You may think that 'ls -lR | grep "4 July"' is the solution. However, this may not be fool proof 'cos if the file is more than 180 days old, 'ls -l' will show the "4 July 2007" time format. If not, it will show "4 July 17:11" time format. That means, you may have more than one occurrence of "4 July" in the 'ls -lR'. Worse still, you can pick up files modified on "14 July" or "24 July"

    What you need is a program to calculate the number of days old and use the output as the input to find. A sample Tcl program (dayold) like this will do the job

    set t [clock scan [lindex $argv 0]]
    set now [clock seconds]
    set days [expr ($now-$t)/86400]
    puts $days
    
    Below shows you how it can be combined with find
    $ ./etime 2007-07-04
    136
    
    $ find . -mtime `./etime 2007-07-04`
    ./day-136
    
    $ ls -l ./day-136
    -rw-------   1 chihung  gdz            0 Jul  4 17:11 ./day-136
    

If I were the interviewer, I would expect the interviewee (if he/she is apply for a system admin job) to be able to program in scripting language. It really does not matter what language as long as he/she can master that language well.

Labels: ,

Tuesday, September 11, 2007

How to Delete "Dot Dot Backslash" Files

How to remove files like this '..\logs\access-2007-09-01' in a UNIX environment. They looked like files residing inside a directory if you are living in Windows environment. In UNIX, any files that starts with a dot (.) is considered a hidden file. You need to 'ls -a' to list them out 'cos they won't show up in 'ls'. It is definitely a challenge to get rid of them.

Let's create some of these files to try things out.

$ for i in 01 02 03 04 05 06 07 08 09 10 11 12
do
  touch '..\logs\access-2007-09-'$i
done

$ ls

$ ls -a
.                          ..\logs\access-2007-09-06
..                         ..\logs\access-2007-09-07
..\logs\access-2007-09-01  ..\logs\access-2007-09-08
..\logs\access-2007-09-02  ..\logs\access-2007-09-09
..\logs\access-2007-09-03  ..\logs\access-2007-09-10
..\logs\access-2007-09-04  ..\logs\access-2007-09-11
..\logs\access-2007-09-05  ..\logs\access-2007-09-12

$ rm ..\logs*
..logs*: No such file or directory

You will realise that you are not able to remove them using 'rm' command. However, you can remove them based on their corresponding i-node number. In 'find', you can specify the i-node number with '-inum'. To remove it, simply include '-exec rm' in 'find'. The down side is you need to do it one at a time, or feed the i-node in a loop.

$ ls -ai1
     41286 .
        25 ..
     41287 ..\logs\access-2007-09-01
     41288 ..\logs\access-2007-09-02
     41289 ..\logs\access-2007-09-03
     41290 ..\logs\access-2007-09-04
     41291 ..\logs\access-2007-09-05
     41292 ..\logs\access-2007-09-06
     41293 ..\logs\access-2007-09-07
     41294 ..\logs\access-2007-09-08
     41295 ..\logs\access-2007-09-09
     41296 ..\logs\access-2007-09-10
     41297 ..\logs\access-2007-09-11
     41298 ..\logs\access-2007-09-12

$ find . -inum 41287 -exec /bin/rm -i {} \;
rm: remove ./..\logs\access-2007-09-01 (yes/no)?

$ for i in `ls -ai1 | awk '/logs/ {print $1}'`
do
  find . -inum $i -exec rm -i {} \;
done

So, can we use 'find' to locate these files and have them removed in a one-liner? The trick is to be able to pass the pattern (\\, two backslashes) to 'find' so that the escape meaning of a '\\' will be interpreted as '\'. If you use doube quote (") syntax in 'find', you will have to have four backslashes to represent a backslash inside. If you are using single quote syntax, you will need two backslashes. Make sure you include '-i' in 'rm' to prompt you before removal, unless you are sure what are doing.

$ find . -name "..\logs\*"

$ find . -name "..\\logs\\*"

$ find . -name "..\\\\logs\\\\*"
./..\logs\access-2007-09-01
./..\logs\access-2007-09-02
./..\logs\access-2007-09-03
./..\logs\access-2007-09-04
./..\logs\access-2007-09-05
./..\logs\access-2007-09-06
./..\logs\access-2007-09-07
./..\logs\access-2007-09-08
./..\logs\access-2007-09-09
./..\logs\access-2007-09-10
./..\logs\access-2007-09-11
./..\logs\access-2007-09-12

$ find . -name '..\\logs\\*'
./..\logs\access-2007-09-01
./..\logs\access-2007-09-02
./..\logs\access-2007-09-03
./..\logs\access-2007-09-04
./..\logs\access-2007-09-05
./..\logs\access-2007-09-06
./..\logs\access-2007-09-07
./..\logs\access-2007-09-08
./..\logs\access-2007-09-09
./..\logs\access-2007-09-10
./..\logs\access-2007-09-11
./..\logs\access-2007-09-12


$ find . -name '..\\logs\\*' -exec /bin/rm -i {} \;
rm: remove ./..\logs\access-2007-09-01 (yes/no)?
rm: remove ./..\logs\access-2007-09-02 (yes/no)?
rm: remove ./..\logs\access-2007-09-03 (yes/no)?
rm: remove ./..\logs\access-2007-09-04 (yes/no)?
rm: remove ./..\logs\access-2007-09-05 (yes/no)?
rm: remove ./..\logs\access-2007-09-06 (yes/no)?
rm: remove ./..\logs\access-2007-09-07 (yes/no)?
rm: remove ./..\logs\access-2007-09-08 (yes/no)?
rm: remove ./..\logs\access-2007-09-09 (yes/no)?
rm: remove ./..\logs\access-2007-09-10 (yes/no)?
rm: remove ./..\logs\access-2007-09-11 (yes/no)?
rm: remove ./..\logs\access-2007-09-12 (yes/no)?

Labels:

Wednesday, August 01, 2007

Shell Programming

With regard to yesterday's blog, you may want to put that in a script so that you do not have to re-type commands all the time.

So you first cut may be like this:

egrep '^ch' /etc/passwd | cut -f7 -d: | grep -c /bin/ksh

However, this script is not very flexible. First you did not tell the script what shell you want to run with. Second, you assume user has all the search path to be the same as your environment. Thirdly, you have the search string hard coded. OK, lots of room for improvement. Let's give this script a make-over then, we call this script "fshell.sh:

#! /bin/sh

if [ $# -ne 2 ]; then
   echo "Usage: $0 &lgt;pattern> <shell>"
   exit 1
fi
pattern=$1
shell=$2

# set up search path
PATH=/usr/bin
export PATH

egrep "^$pattern" /etc/passwd | cut -f7 -d: | grep -c "$shell"

Now you have a very generic script that can handle different pattern and shell. Let run it:

$ ./fshell.sh
Usage: ./a.sh <pattern> <shell>

$ ./fshell.sh ch /bin/ksh
4

$ ./fshell.sh ch /bin/sh
1
Let me provide you with some explanation. Line 1: Tell the system that this script (fshell.sh) is written in Bourne Shell (/bin/sh) syntax Line 3-8: Check if you supply with 2 arguments, namely the pattern and shell. If not, exit with status 1, else set the variables pattern and shell accordingly Line 10-11: Set up the search path environment variable. We do not want to use user's search path Line 13: The commands, this return the number of match.

Not too difficult to digest, isn't it. Next time when you want to write a simple script, do follow this approach.

Labels: ,

Tuesday, July 31, 2007

UNIX Shell is Old Fashion ?

Is UNIX shell an old fashion stuff ?

UNIX has been with us for more 3.5 decades ( Unix History) and shell is the glue for UNIX commands to work together as well as interact with the system. Most of the commands are designed to do one thing and do it extremely well. Also, it is designed to work with other commands via the standard input, standard output and error. Output from one command can be the input to the next commands, the same concept can be extended to allow a chain of commands to achieve a specific goal.

Example, you may want to find out how many users with name starting "ch" that are using Korn shell (/bin/ksh)

$ egrep '^ch' /etc/passwd | cut -f7 -d: | grep -c /bin/ksh
4
Using regular expression "egrep" to find those starting with 'ch' in the password file, the output will be served as input to the "cut" command which output the 7th field based on colon (:) as the field separator. The output will be fed into "grep" command to count (-c) the number of lines

Here we can show you step by step to achieve our goal

$ cat /etc/passwd
root:x:0:0:Super-User:/:/sbin/sh
daemon:x:1:1::/:
bin:x:2:2::/usr/bin:
sys:x:3:3::/:
adm:x:4:4:Admin:/var/adm:
lp:x:71:8:Line Printer Admin:/usr/spool/lp:
uucp:x:5:5:uucp Admin:/usr/lib/uucp:
nuucp:x:9:9:uucp Admin:/var/spool/uucppublic:/usr/lib/uucp/uucico
smmsp:x:25:25:SendMail Message Submission Program:/:
listen:x:37:4:Network Admin:/usr/net/nls:
gdm:x:50:50:GDM Reserved UID:/:
webservd:x:80:80:WebServer Reserved UID:/:
nobody:x:60001:60001:NFS Anonymous Access User:/:
noaccess:x:60002:60002:No Access User:/:
nobody4:x:65534:65534:SunOS 4.x NFS Anonymous Access User:/:
chchan:x:1001:1000::/users/chchan:/bin/sh
hung:x:1002:1000::/users/hung:/bin/bash
chihung:x:1003:1000::/users/chihung:/bin/ksh
chi:x:1004:1000::/users/chi:/bin/ksh
manu:x:1005:1000::/users/manu:/bin/bash
chikeung:x:1006:1000::/users/chikeung:/bin/ksh
choo:x:1007:1000::/users/choo:/bin/ksh

$ egrep 'ch' /etc/passwd
chchan:x:1001:1000::/users/chchan:/bin/sh
chihung:x:1003:1000::/users/chihung:/bin/ksh
chi:x:1004:1000::/users/chi:/bin/ksh
chikeung:x:1006:1000::/users/chikeung:/bin/ksh
choo:x:1007:1000::/users/choo:/bin/ksh

$ egrep 'ch' /etc/passwd | cut -f7 -d:
/bin/sh
/bin/ksh
/bin/ksh
/bin/ksh
/bin/ksh

$ egrep 'ch' /etc/passwd | cut -f7 -d: | grep -c /bin/ksh
4

In fact, if you are an advanced user, you can do all that by using just "egrep" along.

$ egrep -c '^ch.*:/bin/ksh$' /etc/passwd
4
Powerful, isn't it. With regular expression, you can tell "egrep" that any line that starts with "ch" (anchor ^ - beginning of a line) followed by zero or more of any character. At the end of the line (anchor $ - end of a line), you need to match ":/bin/ksh". With "-c" option in "egrep", it will return the number of occurrence.

So, the answer to the question is - Unix is old, but not old-fashion, IMO. We should use whatever is approach to the task instead of reinventing the wheel.

Labels: ,

Friday, June 01, 2007

Maths Olympics

Recently my daugther attended the Mathematics Olympics for Secondary 2. The questions are very tough if you have not been exposed to the type of questions before. One of the questions is pretty interesting.

Find the latest integer n so that n6021 < 20072007.

Not many people know how big is 20072007. If you use bc (arbitrary precision arithmetic language) to calculate it, it is a 6629 digit number.

So how can we approach this problem without having to deal with 6000+ digits.
6021 is 3 times of 2007, so we can express
n6021 as
n32007
Using the trail and error method, we can tabulate the result as:
n=10, n3=1000 < 2007
n=11, n3=1331 < 2007
n=12, n3=1728 < 2007
n=13, n3=2197 > 2007

So, the answer is 12

$ echo 2007^2007 | bc
16314605714687673100219161988221590518292210898740437841876506892750\
32306039423940369656182671626918374428665007728310641726207038681918\
23136702404167821902979921698186677089033622516321277953102421415380\
52881817063065329725414186570424721165880384220836219727730342712190\
37547038078493298854228413412450765335802752810679631982070064711707\
56994904826360657191473471275712342626409252812000487654952457462581\
25202397471862500575253203957986559953029179221497185241787894245109\
51506284252195025848010707100693306754335210537773553923807001377973\
58190841023173651478340362529204455978523734694649333587437048551880\
84344987860972778473042539830626220900910030243133077748096636794353\
16457852288885788183704321212603620156876288242227673033902489461859\
80807205983674431470103187228509985963442849376025881515659139204354\
57334048169514769124351395926915548900005107939870885748926502983652\
48220739239828923170534565961757683913268494073903341978940401041341\
24158904437217633744227156627420692310366588876904474906119640656336\
00909055629673774341172101831114453521702586164711667890001015971356\
60276401463142043929976624709724328792829957422043087537178795758647\
72185461767393859241999232092091753999161030318269214754924571963159\
35520624812251694955876845371629366273520636698693605424704420404631\
75277434551058391143650208928358475502339174967420269679902664658114\
23441325364666899042860424269755985756717730999047598611204004019487\
05037492513989337593522479668752257755675941902099185237554143748651\
76084285432698562312888918263670859517256741096260219051804661166619\
77156782563640767810527747055628531062056538632420611318856864435605\
98573568085436649055893711511908754786711917259735123805058932226875\
09020048745112007771764955307557550322001919379536452269156637570639\
67686895988403526418230539376546037003876670242151992373967447858965\
32371190719225599092102935960432876642206996867191908197903254065184\
66772118566829478154758078361829805339842140536877388530591895758845\
74615755305866464237994838787908227762252835497894144677604759903050\
56214887675010008762806122865755121275564759677904950783893207351021\
21793547077526595680554400368459226450944178849240467865779814317007\
96876505317193541397691960050013423154588306446442511274723228366073\
99740758368268646735204080379101950673539512645517752083915627087436\
66342779749004724047925157702126529475456581827940549061219833542771\
72666791641130825385603816826728793107694318470910676883660956902086\
59579147945702522853473552635534140382309303777950425443446724647072\
84039885465320015844579846408011500806127198942953456479287429126124\
58187025149566132957578262005878966556171671947012422179587596926224\
48413221909265362849341101538896719374297181506945626681830899361082\
17588258048154216467741811634089431627204908200906712352236452851164\
60870051555430826004956456747145900922832888740550701604291930516794\
53804271088240995714495287536761378107585304471702025690381237435699\
62867717292953981124669065011683502890758991080085205157633970212891\
98777309368701179857410923501969865110478773653903699197912297908533\
71149722723292678177205635678230292598408904569266566529096965940687\
19800187410667900893753388917161120090709121225671327994837556358866\
13795364895358454179682944936819599409259644069296990066176672218326\
10569446092009445906651399279429326070744029719496103157306940293382\
08652605749532755522690122699195850782355410608547470555886945614660\
28849763565012828241503887371454415825187174123047124428965559186350\
65661067953888197801888330944283778895151118014938632162825657485422\
26873379147497009487850977528543889031689799484755702907033188341688\
57086162026884996378694574719417715017198218671864779969442373083947\
84224584936854774880083798459580587181441861962025043001696668942099\
98369361531152251402670787887047071049415711093008135194582239773277\
57730018467737893821357739016393737981517063929164948629278989863490\
66462204249411800881288288291970583303627128619570872408141516094456\
83837112137017595507346794006856000647005501898922929846153939218796\
28234593579234420657377664780055273852674449396670561737910057331770\
53405452811154572480773839659370346376909955589954534463995402397547\
55090554901741064115038670213867607618630149352412903118245252687275\
28109561678498436676798923797165313359732911821400623859409924152069\
06300260638828041177167702847188712306493492372142866618404908913176\
54030952366549559176082480786655059388809520507182637615683247714988\
05191492633132029599544921486661970299947588786678189871088966477407\
52512996563850623228109536022666509972476172556459154412193755524859\
28452331588277656632220424016664113248809498813370962561820162791582\
64121448823383689967724103592671517706815568744426523608840138911714\
53958944518234290650299585576981492919941107102609478933946462619302\
48865632368726622732906937659050660925986430541337820914319653668221\
87349651540078364469161738550494782857953599406614823850511779698786\
91838865273359122035277482634624991021675924624312254360293884842917\
65838307747253780974059548132381415125202990686958323920598730920623\
83252041705054542282692895103797418414876506955754092950593171511526\
03651256685226830058555083998194070710847307757088197896172035753443\
57325024752384875269065693702994828638438768496534182574105672247872\
16889073273120095695064749134557169837596440817787277202590296656949\
48573652672557136771335615479698964295228224311865290533314649278929\
66378562879105977303922021842036171103420525191259589291180958162828\
53849025184090592088836475653212594663891594930011800278301810320167\
71271739342026383819163505909340986688942636949341034442899607560777\
48743959210409197647213006839217933959866202483201890809519278801288\
89774489640070710220962719764159839606000869526896455498122625138520\
03473593771023384202960841337266822055244894318115626747268831051684\
93368590796032830924999538553468389382057082607007101680887865179417\
56230281766141812283600778826785130821021267795745725254521386017285\
26298885351305296325067178476137349370135741313308883039679816779268\
89819182812687810885966489071842746337245202749132624149354170939165\
16259303899012457012515608202326844412337496478945032118391923014778\
60791546940874717049537071793531373218290246791145310292221059372892\
64816915738818462542773732790559090793017150142535888474230492964601\
87531820919736515493904236213757675608136303680989586717189185046309\
78276773061725084597786832034498958720078262844355265962017842479132\
62269519023741579612330789171572662737099118044136909873639373744006\
57859538070736932317321882339952581950548422144343493289702293960474\
93455994166543113414231137214737093262742407103151085798658468378983\
026266371632383860581109563509543
To count how many digit there, we need to get rid of the backslash and the newline
$ echo 2007^2007 | bc | sed -e 's/\\//' | awk '{printf("%s",$1)}' | wc -c
6629

Labels: ,

Tuesday, May 29, 2007

Delete Old Files

Wanna to delete those old files with a certain extension in some directory, there you go...
#! /bin/sh

if [ $# -ne 3 ]; then
        echo "Usage: $0 <directory> <days old> <extension>"
        exit 1
fi


PATH=/usr/bin:/bin
export PATH


dir="$1"
old="$2"
ext="$3"


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


find "$dir" -type f -name "*.$ext" -mtime "+$old" -exec rm -i {} \;

If you plan to run that in a cron environment, you will need to remove the "-i" option and discard all the standard output and error to avoid cron from sending you an email. I also include checking to ensure the "old" is an integer greater than 0. The modified script will look like this.

#! /bin/sh

if [ $# -ne 3 ]; then
        echo "Usage: $0 <directory> <days old> <extension>"
        exit 1
fi


PATH=/usr/bin:/bin
export PATH


dir="$1"
old="$2"
ext="$3"



if [ ! -d "$dir" ]; then
        echo "Error. $dir does not exist"
        exit 2
fi
expr $old / 1 > /dev/null 2>&1 && [ $old -gt 0 ]
if [ $? -ne 0 ]; then
        echo "Error. $old is not a number > 0"
        exit 3
fi
 


find "$dir" -type f -name "*.$ext" -mtime "+$old" -exec rm {} \; > /dev/null 2>&1

In Linux, you can specify "-maxdepth" to control descend at most levels. In our case, we need to have an equivalent of "-maxdepth 1" in Solaris. In this blog, it mentioned using "-prune" to simulate this effect. However, I cannot get it working for me.

Alternatively, you can use egrep and xargs to achieve this:

find "$dir" -type f -name "*.$ext" -mtime "+$old" | egrep "^$dir/[^/]+$" | xargs rm

Labels: , ,

Saturday, April 14, 2007

mkdir, the limit

A friend of mine hit the limit of having no more than 32765 sub-directories. In Solaris 8, it has been documented: "Too many links cause an attempt was made to create more than the maximum number of hard links (LINK_MAX, by default 32767) to a file. Because each subdirectory is a link to its parent directory, the same error results from trying to create too many subdirectories"

So the question is: Is there anything we can do. I don't think so because this is a built in limit in Solaris. What one can do is to ask ourself why we need that many sub-directories and can we change that flat directory structure to a hierarchical. It is pretty obvious that too many files/directories in folder will have a performance issue when an application interacts with it.

Let do an experiment just to convince ourself that indeed there is a limit:

$ uname -a
SunOS myhost 5.9 Generic_118558-11 sun4u sparc SUNW,Sun-Fire-V240

$ psrinfo -v
Status of processor 0 as of: 04/14/2007 12:16:12
  Processor has been on-line since 10/16/2006 09:10:39.
  The sparcv9 processor operates at 1002 MHz,
        and has a sparcv9 floating point processor.
Status of processor 1 as of: 04/14/2007 12:16:12
  Processor has been on-line since 10/16/2006 09:10:38.
  The sparcv9 processor operates at 1002 MHz,
        and has a sparcv9 floating point processor.

$ mkdir test1

$ cd test1

$ time for i in `perl -e '$,=" ";print 1..32768'`
 do
 mkdir $i
 done
mkdir: Failed to make directory "32766"; Too many links
mkdir: Failed to make directory "32767"; Too many links
mkdir: Failed to make directory "32768"; Too many links

real    2m52.716s
user    0m40.830s
sys     2m7.210s

$ cd ..

$ perl
$dir="test1";
($x,$x,$x,$nlink)=stat($dir);
print $nlink,"\n";
 
32767

As we can see, the maximum number of sub-directories one can create will be 32765. The total links is 32767 because for every directory we create, it creates two links, one for itself (.) and the other one is the parent directory (..)

Let sidetrack a little bit and take a look from the performance angle. It seems to take almost 3 minutes to create 32765 sub-directories. Can it be faster? Let see what interpreted languages like Tcl and Perl can offer.

The perl way:

$ perl -v

This is perl, v5.6.1 built for sun4-solaris-64int
(with 48 registered patches, see perl -V for more detail)

Copyright 1987-2001, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using `man perl' or `perldoc perl'.  If you have access to the
Internet, point your browser at http://www.perl.com/, the Perl Home Page.

$ mkdir test2

$ cd test2

$ time $ perl
$|=1;
$start=1;
$end=32768;
for ($i=$start; $i<=$end; $i++) {
    mkdir($i);
}
 
real    0m21.098s
user    0m0.180s
sys     0m7.740s
Wow, we are talking about 8 times speed up. How about my favourite Tcl. The Tcl way:
$ cat a.tcl
#! /usr/sfw/bin/tclsh8.3

for { set i 1 } { $i <= 32768 } { incr i } {
        file mkdir $i
}

$ mkdir test3

$ cd test3

$ time ../a.tcl
can't create directory "32766": too many links
    while executing
"file mkdir $i"
    ("for" body line 2)
    invoked from within
"for { set i 1 } { $i <= 32768 } { incr i } {
        file mkdir $i
}
"
    (file "../a.tcl" line 3)

real    0m20.796s
user    0m0.900s
sys     0m8.040s
Wow, I am impressed that Tcl 8.3 (latest is 8.4) is as good as Perl 5.6.1 (latest is 5.8.8)

BTW, to remove that many sub-directories (under test1, test2, test3) 3x32767, it took

$ time /bin/rm -rf test1 test2 test3

real    0m35.425s
user    0m1.210s
sys     0m19.740s
Why perl and Tcl can perform better than the shell script ? Obviously, there is no fork or exec of processes in Perl and Tcl because they have the "mkdir" function call built-in into their interpreter. So how much overhead we are talking about, let's do another experiement.
$ truss mkdir newdir 2>&1 | wc -l
      48

$ truss mkdir u
execve("/usr/bin/mkdir", 0xFFBFFCF4, 0xFFBFFD00)  argc = 2
resolvepath("/usr/lib/ld.so.1", "/usr/lib/ld.so.1", 1023) = 16
resolvepath("/usr/bin/mkdir", "/usr/bin/mkdir", 1023) = 14
stat("/usr/bin/mkdir", 0xFFBFFAC8)              = 0
open("/var/ld/ld.config", O_RDONLY)             Err#2 ENOENT
stat("/usr/lib/libgen.so.1", 0xFFBFF5D0)        = 0
resolvepath("/usr/lib/libgen.so.1", "/usr/lib/libgen.so.1", 1023) = 20
open("/usr/lib/libgen.so.1", O_RDONLY)          = 3
mmap(0x00010000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_ALIGN, 3, 0) = 0xFF3A0000
mmap(0x00010000, 98304, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE|MAP_ANON|MAP_ALIGN, -1, 0) = 0xFF380000
mmap(0xFF380000, 22677, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0xFF380000
mmap(0xFF396000, 2343, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 24576) = 0xFF396000
munmap(0xFF386000, 65536)                       = 0
memcntl(0xFF380000, 6304, MC_ADVISE, MADV_WILLNEED, 0, 0) = 0
close(3)                                        = 0
stat("/usr/lib/libc.so.1", 0xFFBFF5D0)          = 0
resolvepath("/usr/lib/libc.so.1", "/usr/lib/libc.so.1", 1023) = 18
open("/usr/lib/libc.so.1", O_RDONLY)            = 3
mmap(0xFF3A0000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0xFF3A0000
mmap(0x00010000, 802816, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE|MAP_ANON|MAP_ALIGN, -1, 0) = 0xFF280000
mmap(0xFF280000, 701788, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0xFF280000
mmap(0xFF33C000, 24664, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 704512) = 0xFF33C000
munmap(0xFF32C000, 65536)                       = 0
memcntl(0xFF280000, 117372, MC_ADVISE, MADV_WILLNEED, 0, 0) = 0
close(3)                                        = 0
stat("/usr/lib/libdl.so.1", 0xFFBFF5D0)         = 0
resolvepath("/usr/lib/libdl.so.1", "/usr/lib/libdl.so.1", 1023) = 19
open("/usr/lib/libdl.so.1", O_RDONLY)           = 3
mmap(0xFF3A0000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0xFF3A0000
mmap(0x00002000, 8192, PROT_NONE, MAP_PRIVATE|MAP_NORESERVE|MAP_ANON|MAP_ALIGN, -1, 0) = 0xFF3FA000
mmap(0xFF3FA000, 1894, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0xFF3FA000
close(3)                                        = 0
mmap(0x00000000, 8192, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0) = 0xFF370000
stat("/usr/platform/SUNW,Sun-Fire-V240/lib/libc_psr.so.1", 0xFFBFF2E0) = 0
resolvepath("/usr/platform/SUNW,Sun-Fire-V240/lib/libc_psr.so.1", "/usr/platform/sun4u-us3/lib/libc_psr.so.1", 1023) = 41
open("/usr/platform/SUNW,Sun-Fire-V240/lib/libc_psr.so.1", O_RDONLY) = 3
mmap(0xFF3A0000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0xFF3A0000
close(3)                                        = 0
getustack(0xFFBFF914)
getrlimit(RLIMIT_STACK, 0xFFBFF90C)             = 0
getcontext(0xFFBFF748)
setustack(0xFF343A5C)
brk(0x000245E8)                                 = 0
brk(0x000265E8)                                 = 0
umask(0)                                        = 077
umask(077)                                      = 0
mkdir("u", 0777)                                = 0
_exit(0)

Ok, we now know that for every 'mkdir', it calls 48 system functions. So there will be 32,765 x 48 = 1,572,720 system calls in order to create that many directories. In Tcl/Perl, it only takes 6 system calls to create a single directory and that is 8 times less system calls. This tally with our initial speed up calculation.

9364/1:         read(0, " f i l e   m k d i r   t".., 4096)     = 13
9364/1:         stat("t", 0xFFBFE910)                           Err#2 ENOENT
9364/1:         umask(0)                                        = 077
9364/1:         umask(077)                                      = 0
9364/1:         mkdir("t", 0700)                                = 0
9364/1:         write(1, " %  ", 2)                             = 2

Labels: , , , ,

Thursday, April 05, 2007

Java does not honour TMPDIR

My colleague encountered a wierd behaviour in deploying his SunONE application server in Solaris. He realised that when the / partition is near full, he will have problem in starting the daemon.

I understand that most utilities in UNIX honour the TMPDIR environment variable to be the temporary directory. So, the question is, does Java honours TMPDIR ?

Found this with the help of Google. Too bad, Java DOESN'T honour TMPDIR variable. To proof the point, I wrote my very first Java program (FYI, I do not like programming languages start with letter J :-), almost the first except Hello World.

$ cat a.java
import java.io.*;

public class a {
        public static void main(String[] args) {
                String tmpdir=System.getProperty("java.io.tmpdir");
                System.out.println("Dir: " + tmpdir + "\n");
        }
}

$ uname -a
SunOS chihung 5.10 Generic_118833-36 sun4u sparc SUNW,UltraSPARC-IIi-cEngine

$ java -version
java version "1.5.0_07"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_07-b03)
Java HotSpot(TM) Client VM (build 1.5.0_07-b03, mixed mode, sharing)

$ cat a.java
import java.io.*;

public class a {
        public static void main(String[] args) {
                String tmpdir=System.getProperty("java.io.tmpdir");
                System.out.println("Dir: " + tmpdir);
        }
}

$ javac a.java

$ TMPDIR=/a/b/c java a
Dir: /var/tmp/

$ java a
Dir: /var/tmp/

$ java -Djava.io.tmpdir="/a/b/c" a
Dir: /a/b/c

Labels: ,

Monday, April 02, 2007

Loop

Some of the systems monitoring commands with built-in looping functionality, commands such as vmstat, iostat, .... Very often we would like to repeat the same command to monitor certain activities like file size, disk usage.

This shell function does exactly this:

loop()
{
    sec=$1
    shift
    cmd=$*
    while :
    do
    eval $cmd
    sleep $sec
    done
}

Now you just have to provide the interval and the command you like to loop, just like this:

$ loop 5 df -h /
Filesystem             size   used  avail capacity  Mounted on
/dev/md/dsk/d30        5.9G   4.9G   931M    85%    /
Filesystem             size   used  avail capacity  Mounted on
/dev/md/dsk/d30        5.9G   4.9G   931M    85%    /
Filesystem             size   used  avail capacity  Mounted on
/dev/md/dsk/d30        5.9G   4.9G   931M    85%    /
^C

Labels: ,