Testing MongoDB Replica Pairs with Perl

I was just fixing this, and it’s a pain to setup/test, so I figured I’d put up what I did here, so at least I’d never have to figure it out again.  So, start two db servers and an arbiter:

$ mkdir ~/data1
$ mkdir ~/data2
$ ./mongod --pairwith localhost:27018 --arbiter localhost:27019 --dbpath ~/data1
$ ./mongod --port 27018 --pairwith localhost:27017 --arbiter localhost:27019 --dbpath ~/data2
$ ./mongod --port 27019 #arbiter

Then kick off the following Perl script:

use strict;
use warnings;
use Carp;
use Data::Dumper;

use MongoDB;

# order of left_host/right_host is unimportant
my $conn = MongoDB::Connection->new('right_host' => 'localhost', 'left_host' => 'localhost', 'left_port' => 27018);

my $db = $conn->get_database('x');
my $coll = $db->get_collection('y');


for (my $i=0; $ifind_one;

    print $@."n";

    sleep 1;

Now, you’ll start getting stuff like:


That means everything is okay. Now, kill the first mongod process that you started. (The first one you started is probably master. If you don’t see a “pair: setting master=1 was 0” on the other one after a couple seconds, restart the first one and kill the second one.) You’ll notice your output changes to:

finding...couldn't find master at /usr/local/lib/perl5/site_perl/5.10.0/i686-linux/MongoDB/Connection.pm line 177.
finding...couldn't find master at /usr/local/lib/perl5/site_perl/5.10.0/i686-linux/MongoDB/Connection.pm line 177.
finding...couldn't find master at /usr/local/lib/perl5/site_perl/5.10.0/i686-linux/MongoDB/Connection.pm line 177.

The slave hasn’t become master yet, so there’s nothing the db can use (there will probably be a 2-10 second delay before the slave becomes master). Once you see “pair: setting master=1 was 0” scroll by on your db logs, you’ll notice the Perl script’s output change back to:


You can go back and forth, killing off master dbs and restarting them.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: