Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Tuesday, 27 July 2010

Varnish and the Linux IO bottleneck

There are 2 main ways Varnish caches your data:
  1. to memory (with the malloc storage config)
  2. to disk (with the file storage config)
As Kristian explains in a best practices post, you get better performance with #1 if your cache size fits in RAM. With either method the most accessed objects end-up in RAM. While the malloc method puts everything in RAM and the kernel swaps it out to disk, the file storage method puts everything in disk and the kernel caches it in memory.

We have been using the file storage for a little more than 3 months on servers with 16GB of RAM and a file storage of 30GB. Recently, because of an application configuration error, the size of the cache grew from its usual maximum of 6GB to 20GB+.

Since the system only has 16GB, the kernel now needs to choose which pages to keep in RAM. When a dirty mmap'ed page needs to be released the kernel will write the changes to disk before doing so. More than that, the linux kernel will proactively write dirty mmap'ed pages to disk.

On a Varnish server with this setup or any other application that uses mmap() for large files, the situation translates to constant disk activity.

At some point the varnish worker process will be blocked by a kernel IO call. The Varnish manager process, with no way to tell what's happening to the child, believes it has stopped responding and kills it. The log entries below are typical:

00:30:10.395590 varnishd[22919]: Child (22920) not responding to ping, killing it.
00:30:10.395622 varnishd[22919]: Child (22920) not responding to ping, killing it.
00:30:10.417309 varnishd[22919]: Child (22920) died signal=3

At this point you lose your cached data and the system goes back to normal. After some time, the size of the cache will grow to be larger than your server's RAM again, repeating the kill-restart cycle.

You could choose to give the client more time to respond to the manager process' ping requests. This is done by increasing the default value of cli_timeout from 10 seconds (e.g. varnish -p cli_timeout=20) but this is merely masking the issue. The real issue is that the Linux kernel is busy writing dirty pages to disk.

There are parameters you can use to control how much time the kernel spends writing dirty mmap pages to disk. I have spent some time fine-tuning the parameters below with little results:

/proc/sys/vm/dirty_writeback_centisecs
/proc/sys/vm/dirty_ratio
/proc/sys/vm/dirty_background_ratio

In RHEL 5.x kernels you can completely disable committing changes to mmap'ed files:

echo 0 > /proc/sys/vm/flush_mmap_pages

Short of reducing the file storage size to fit in RAM, this is the best solution I found so far. Be aware that using this with the upcoming persistent storage in Varnish is a really bad idea as you risk serving corrupt and/or stale data. This is only acceptable because the mmap'ed data, in this setup, is superfluous: varnish throws away the cache on restart and it can always fetch the object from the backend.

I have asked Red Hat if they plan to keep the flush_mmap_pages setting in RHEL 6 but haven't received a response yet.  They did, however, confirm that msync() calls are honoured and dirty pages being evicted from RAM are committed to disk.

Monday, 22 June 2009

Disk IO spikes caused by mod_proxy.c in Apache 1.3

We have been using Apache 1.3 with mod_proxy as a reverse proxy for some of our applications. The configuration is pretty simple:

CacheRoot /var/adm/apache/cache
CacheSize 4096000
CacheGcInterval 4
CacheMaxExpire 48
CacheDefaultExpire 2

The above tells Apache to inspect the cache directory every 4 hours, keep up to 4GB worth of data, validate objects every 48 hours (no matter what the origin server set the expiry to) and expire them, by default, in 2 hours.

The typical content of the cache directory for our sites is 4.5GB in about 180,000 directories and 310,000 files.

Shortly after deploying this to production we started seeing the pattern below for the load on all web servers:
Because this was happening in regular intervals it was easy to inspect one of the servers during the load spike. The sar data had already told us the load was caused by disk IO:

$sar -b
(...)
tps rtps wtps bread/s bwrtn/s
11:30:01 AM 94.53 1.89 92.63 27.68 1275.66
11:40:01 AM 1289.34 57.63 1231.71 555.35 20566.36
11:50:01 AM 79.16 1.23 77.93 21.88 1084.00
12:00:02 PM 94.21 1.77 92.44 39.52 1274.74
12:10:01 PM 84.18 1.64 82.54 35.54 1116.60
12:20:01 PM 117.43 2.62 114.81 44.68 1550.87
12:30:01 PM 150.65 3.30 147.35 82.21 1986.41
12:40:01 PM 1228.90 1.53 1227.37 33.04 20592.15
12:50:01 PM 70.46 2.65 67.80 100.57 917.25
When the load spiked I checked which processes were high on "wa" (waiting for IO) time and listed their open files with lsof.

Sure enough I could see httpd processes with changing files open in /var/adm/apache/cache. This is expected since the cache garbage collector needs to inspect cached objects and decide what to delete in order to stay under the CacheSize limit.

What surprised me is how amazingly expensive this operation is on ext3 filesystems.

To alleviate the problem I have changed some of the filesystem parameters. In /etc/fstab I told the OS to not update access times on files and directories under /var:
/dev/VolGroup00/LogVol04    /var   ext3    defaults,noatime,nodiratime        1 2
Without noatime and nodiratime every file and directory read meant a disk write to update the access time. Since we don't have a use for access times in /var I did away with them.

With tune2fs I change the data option from the default (ordered) to writeback:
# tune2fs -o journal_data_writeback /dev/mapper/VolGroup00-LogVol04
The writeback mode can cause file corruption on unclean shutdowns but the benefits outweights the risk for us. Our web content in /var is replicated from a master server so we would only be looking into losing non-critical data such as some state files and access log entries.

After these changes the GC is barely noticed. If you pay attention to the graph above you will see that there is no load spike for 13:00 onwards.

Thursday, 23 April 2009

QEMU/KVM mouse not working?

This guy knows the answer:

$ export SDL_VIDEO_X11_DGAMOUSE=0
For me, because I use a physical device for a disk and didn't want to give myself permission on the device:
$ sudo SDL_VIDEO_X11_DGAMOUSE=0 qemu-launcher
My mouse stopped working after I configured Xinerama and display rotation on X (I had alsoi upgraded to Ubuntu 9.04 but I didn't test my VM before fiddling with xorg.conf).

Thursday, 11 December 2008

How to avoid overlapping rsync instances

Running rsync as a cron job is probably as popular as sliced bread. For small intervals, however, you risk having a second instance start before the first one has finished, beginning a downward spiral of bandwidth and processes.

To avoid multiple instances getting in each other's way there's a simple solution using flock. Example without lock (may cause overlapping instances):
*/5 * * * * /usr/bin/rsync --delete -a source_server:/source/path/ /dst/path/
Example using flock:
*/5 * * * * flock -xn /tmp/example.lock -c '/usr/bin/rsync --delete -a source_server:/source/path/ /dst/path/'
In the second example, if a rsync instance runs for more than 5 minutes, flock will fail and thus not execute a second rsync process.

This can be used for pretty much any shell problem where locking helps. Have a read on the flock man page for other examples.

Friday, 18 April 2008

Nagios checks for LSI RAID with MegaCli

I am pretty sure there is a SNMP object in Dell's DRAC 5/PERC to inform about the status of your RAID volumes and physical disks. I'm not too fond of using SNMP with Nagios so I wrote a check script that uses the MegaCli linux i386 binary (from the LSI web site) to report the status of the RAID on our Dell/Red Hat Linux servers.

Here's what you need:
  • perl interpreter in /usr/bin/perl
  • nagios' utils.pm in /usr/local/nagios/libexec/
  • perl module Time::HiRes (cpan; install Time::HiRes)
  • sudo in /usr/bin/
  • MegaCli in /opt/MegaRAID/MegaCli/MegaCli64
You'll also need the check_dellperc in /usr/local/nagios/libexec. Change the paths as you see fit.


#!/usr/bin/perl -wT
#
# CHECK DELL/MegaRAID DISK ARRAYS ON LINUX
# $Id: check_dellperc 142 2008-03-17 22:25:46Z thiago $
#

BEGIN {
$ENV{'PATH'} = '/usr/bin';
$ENV{'ENV'} = '';
$ENV{'BASH_ENV'} = '';
$ENV{'IFS'} = ' ' if ( defined($ENV{'IFS'}) ) ;
}

use strict;
use lib "/usr/local/nagios/libexec";
use utils qw($TIMEOUT %ERRORS &print_revision &support &usage);

use Getopt::Long;

use Time::HiRes qw ( tv_interval gettimeofday );

use vars qw($opt_h $help $opt_V $version);
use vars qw($PROGNAME $SUDO $MEGACLI);

$PROGNAME = "check_dellperc";
$SUDO = "/usr/bin/sudo";
$MEGACLI = "/opt/MegaRAID/MegaCli/MegaCli64";

my $t_start = [gettimeofday];

Getopt::Long::Configure('bundling');
GetOptions
("V" => \$opt_V, "version" => \$opt_V,
"h" => \$opt_h, "help" => \$opt_h,
);


if ( $opt_V ) { print_revision($PROGNAME, '$Id: check_dellperc 142 2008-03-17 22:25:46Z thiago $');
exit $ERRORS{'OK'};

} elsif ( $opt_h ) {
print_help();
exit $ERRORS{'OK'};
}

my $TIMEOUT = $utils::TIMEOUT;
my $start_time = time();
# TODO: add timeout option#if ( $opt_t && $opt_t =~ /^([0-9]+)$/ ) {
# $TIMEOUT = $1;
#}


# Check state of Logical Devices
my $status = "PERC OK";
my $perfdata = "";
my $errors = $ERRORS{'OK'};
my $vd = "";
my $vds = "";

open(MROUT, "$SUDO $MEGACLI -LDInfo -Lall -aALL -NoLog|");
if (!<MROUT>) {
print("Can't run $MEGACLI\n");
exit $ERRORS{'UNKNOWN'};
}

while (<MROUT>) {
my $line = $_;
chomp($line);

if ($line =~ /^Virtual Disk: (\d+)/) {
$vd = $1;
next;
}

if ($vd =~ /^[0-9]+$/) {
if ($line =~ /^State: (\w+)/) {
$vds = $1; #TODO: verbose print("State for VD #$vd is $vds\n");
$perfdata = $perfdata." VD$vd=$vds";
if ($vds !~ /^Optimal$/) {
$errors = $ERRORS{'CRITICAL'};
$status = "RAID ERROR";
#TODO: verbose print("Error found: $status. Skipping remaining Virtual Drive tests.\n");
last;
} else {
$vd = ""; $vds = "";
}
}
}
}
close(MROUT);

# Check state of Physical Drives
my $count_type;my $pd = "";
my $pds = "";

open(MROUT, "$SUDO $MEGACLI -PDList -aALL -NoLog|");
if (!<MROUT>) {
print("Can't run $MEGACLI\n");
exit $ERRORS{'UNKNOWN'};
}

while (<MROUT>) {
my $line = $_;
chomp($line);

if ($line =~ /^Device Id: (\d+)/) {
$pd = $1;
next;
}

if ($pd =~ /^[0-9]+$/) {
if ($line =~ /^(Media Error|Other Error|Predictive Failure) Count: (\w+)/) {
$count_type = $1;
$pds = $2; #TODO: verbose print("$count_type count for device id #$pd is $pds\n");
$perfdata = $perfdata." PD$pd=$count_type;$pds";
if ($pds != 0) {
if ($errors == $ERRORS{'OK'}) {
$status = "DISK ERROR";
$errors = $ERRORS{'WARNING'};
}
}
}
}
}
close(MROUT);

# Got here OK
#
my $t_end = [gettimeofday];
print "$status| time=" . (tv_interval $t_start, $t_end) . "$perfdata\n";
exit $errors;


sub print_usage
{
print "Usage: $PROGNAME\n";
}


sub print_help
{
print_revision($PROGNAME, '$Revision: 142 $ ');
print "Copyright (C) 2007 Westfield Ltd\n\n";
print "Check Dell/MegaRaid Disk Array plugin for Nagios\n\n";

print_usage();
print <<USAGE
-V, --version
Print program version information
-h, --help
This help screen


Example:
$PROGNAME

USAGE
;

}

After installing the script above and changing the paths to match your system, edit your sudoers file (sudo /usr/sbin/visudo) and comment the following line:

# Defaults requiretty

If you are doing NRPE checks, the line above will prevent the script from running sudo because there is no TTY associated with it. There is probably a way around it that doesn't involve disabling this security feature - if you find out please tell me.

While in the sudoers file, also add the following two lines:

nagios ALL=(ALL) NOPASSWD: /opt/MegaRAID/MegaCli/MegaCli64 -PDList -aALL -NoLog
nagios ALL=(ALL) NOPASSWD: /opt/MegaRAID/MegaCli/MegaCli64 -LDInfo -Lall -aALL –NoLog

If you run NRPE with a user different than "nagios", change the lines above to match it.

That is it, basically. Before adding it to your NRPE checks, give it a try:

$ sudo -u nagios /usr/local/nagios/libexec/check_dellperc
PERC OK| time=0.189185 VD0=Optimal VD1=Optimal PD0=Media Error;0 PD0=Other Error;0 PD0=Predictive Failure;0 PD1=Media Error;0 PD1=Other Error;0 PD1=Predictive Failure;0 PD2=Media Error;0 PD2=Other Error;0 PD2=Predictive Failure;0 PD3=Media Error;0 PD3=Other Error;0 PD3=Predictive Failure;0 PD4=Media Error;0 PD4=Other Error;0 PD4=Predictive Failure;0 PD5=Media Error;0 PD5=Other Error;0 PD5=Predictive Failure;0

It should return a status of zero (unless, of course, your RAID is b0rken):
$ echo $?
0

Monday, 7 January 2008

Broadcom 4311 on Linux

The Dell Inspiron 1501 I bought after seeing the ad on TV nearly a year ago is a good bang for your buck, except when it comes to the wireless card shipped with this notebook.

Because of the efforts of the ndiswrapper and bcm43xx developers I managed to use the wi-fi card until I started using the AMD64 binaries for Debian Etch.

If you are buying a notebook and plan to use Linux in it, stay away from the Broadcom wireless cards or any other cards that require loading a firmware at run-time.

I got tired of struggling and I'm now waiting for my Intel 2915ABG mini-pci card to arrive in the mail. Hardware is too cheap nowadays to justify wasting my time getting a vendor to work.

Saturday, 21 July 2007

Recording TV programs

With my new nVidia card installed I can now actually watch the videos I record. Capturing DVB-T streams is as easy as reading from /dev/dvb/adapter0/dvr0, at least with my CX23880 DVB card (cx88_dvb kernel module).

My next obstacle was finding a good scheduler. I tried DVR (Ubuntu's Feisty binary core dumps every time) and MythTV (can't get it to scan channels). Out of frustration I wrote an ugly hack to schedule and record some programs. I call it tive.sh ("tive" is a pun on Tivo, but only works in Portuguese):
#!/bin/bash

function usage() {
echo Missing parameters.
echo Usage:
echo $0 '"starting date/time" "seconds to record" "channel name"'
}

WHEN="$1"
DURATION="$2"
CHAN="$3"
DVB="/dev/dvb/adapter0/dvr0"
TZAP='tzap -r'

if [ -z "$WHEN" ]; then
usage
exit
fi

at $WHEN >> __EOP__
# Sometimes /dev/dvb/adapter0/dvr0 "locks-up". Uncommenting the lines
# below will force the driver to be reloaded, thus ensuring that the
# device can be read.
#sudo /sbin/rmmod cx88-dvb cx8802 cx88xx cx88_vp3054_i2c
#sudo /sbin/modprobe cx88-dvb

$TZAP "$CHAN" > /dev/null 2>&1 &
PIDTZAP="\$!"

echo tzap running under pid $PIDTZAP
cat $DVB > "$CHAN$WHEN.mpeg" &
PIDCAT="\$!"
echo Channel $CHAN being recorded under pid \$PIDCAT
echo Sleeping for $DURATION seconds
sleep $DURATION
echo Stopping recording
kill \$PIDCAT
echo Stopping tzap
kill \$PIDTZAP
echo Finished
__EOP__

Say I want to record The Simpsons. I run tive.sh:

$ ./tive.sh "18:00 30.07.07" 2000 "TEN Digital"
warning: commands will be executed using /bin/sh
job 26 at Mon Jul 30 18:00:00 2007

The first parameter, "18:00 30.07.07", will be passed to at directly. The second, 2000, is how long to record for, around 33 minutes (probably not enough for TEN's crappy time-keeping). Finally, "TEN Digital" is the name of the channel, as expected by tzap and listed in ~/.tzap/channels.conf.

Some programs, The Simpsons included, are on 3:4 format, however the DVB-T stream is on 16:9 format (I don't know if this is always true). This causes the video to be captured with a pair of black bars on its side, which is annoying because it wastes space on your screen and hard-disk. One solution is to use mencoder to crop the video; I've put the (long) command in crop34.sh:
#!/bin/bash

if [ -z "$1" ]; then
echo Usage
echo $0 INPUT_FILE
echo File Cropped-INPUT_FILE will be created in the same path.
exit
fi

# Uncomment to preview cropped video
#mplayer -vf rectangle=530:576:95:0 "$1"

mencoder -msglevel all=4 -of mpeg -mpegopts format=dvd \
-srate 48000 -ofps 25 -ovc lavc -oac lavc -lavcopts \
vcodec=mpeg2video:aspect=4/3:acodec=ac3:abitrate=192:\
vrc_buf_size=1835:vrc_maxrate=9800:vbitrate=4900:\
keyint=15 -vf crop=530:576:95:0 "$1" -o Cropped-"$1"

Only one task remains: ad removal. I was hoping to use MythTV's commercials remover but at this point I was already quite frustrated with it so I went around looking for a video editing tool. And boy, did I try a lot of them - Lives seemed to be able to do what I wanted but it was unbearably slow for the big (~2-3Gb) mpeg files.

It took me a lot of time to finally find GOPDIT which, by the way, has Ubuntu binaries, works fine and fast. It is a bit hard to reach the right cut position because the scroller skips too much and the "go back frame" button stops working after a few clicks. However, given this was the only app I could find that did what I wanted, I was more than happy to donate some money to the author.

Friday, 20 July 2007

ATI driver (fglrx) on Ubuntu Linux

It was a fruitless 3-day battle: I could not get the ATI RV370 (Radeon X300) on my desktop Dell to work with Xorg. I tried the pre-packaged fglrx driver, I tried rebuilding it with modules-assistant, I tried installing the latest version from ATI's support site.

The kernel module would load fine but X would core dump after initialising the driver, DRI could not be enabled or X would freeze whenever any OpenGL application was run. I went through heaps of support forums and saw many users having similar problems.

In the end I got myself a nVidia 7300LE and, let me tell you, it was the best $AU70 I have ever spent. I simply wanted to be able to watch DVB-T on my computer, so this low-end card was more than enough.

The installation was effortless and it worked on the first try, even with "Composite" enabled; it's true that it didn't update the device description on xorg.conf but I did that manually just to be neat.

I should have given up on ATI years ago after my all-in-wonder died on me shortly after a year.