Monday 1 June 2015

HOW TO SET IOTOP COMMAND AS A CRON

Recently, I got a requirement from my client, to record the iotop of a server, at every one second interval.

Normally, if we want to run anything at a particular interval, then cronjob comes to our mind. But, here cron job cannot help us because cron allows us to run a script at every one minute minimum.

Also, iotop by default prints the standard output to our screen itself. My requirement was to write the output to a file, so that, I can analyse the result after sometime.

First, few tips regarding iotop. Normally iotop output keep toggling at every 1 second interval. We can use "iotop -n <seconds>  to delay the output to the screen.

If I want to produce a five second delay in output, then use the below option:
----
iotop -d 5
----

I recommend you to use "iotop" with "-o" switch, which will give the "only"  processes that are actually causing I/O.

As a result, our command becomes more user friendly as below:
-----
iotop -d 5 -o
-----

iotop by default shows all threads. Sometimes, we may be interested only in process ids. In that case, the output can be simplified using the command below:
-------
iotop -d 5 -o -P
-------

In another scenario, suppose  you don't want to see the output on to the  screen. Instead, you want to redirect it to a file, then you can use the "-b" option:
-----
iotop -b -n 1 >> /var/log/iotop
-----

-b ---> option enables the non-interactive mode. The above command works in such a way that, the iotop result is written to the file  "/var/log/iotop" once and the command exists.

Now, if you set a cron for every one minute using the above command, the output is written to the file in every one minute.

If the requirement is to collect the result of iotop at every one second interval, then we need to take the help of while loop.

Suppose, I have a script in "/etc/iotop.sh" as below:
-----
#!/bin/bash

DATE=`date`

echo "$DATE" >> /var/log/iotop

echo "###################" >> /var/log/iotop

/usr/sbin/iotop --batch -n 1 >> /var/log/iotop

echo "##################" >> /var/log/iotop

exit
---------


If, I need to run this script every one second means, create a new script as below with while loop.
---
while sleep 1; do /etc/iotop.sh; done
----

For example, if I put the above script to a file "/var/tmp/testing.sh" and starts its execution in backgroud as below:
-----
sh /var/tmp/testing.sh &
-----

The above script will continue writing the  result of output to the file "/var/log/iotop" at every one second interval.

NOTE: The script will continue to append the result to the file until we kill the process using its PID.

There may be different other techniques, but this one worked like a charm for me.

Kool :)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.