Monday, May 31, 2010

Remote failover

We have a couple of offices around. Recently a department located in HQ is moving to another location, miles away. But they still need to refer to data from HQ.

We put up a Linux server replicating some part of our MSSQL server data using PHP. Since we have multiple ISPs connected at the HQ, I was having the idea of making sure that pulling data from HQ should continue as long as 1 line is up.

In the pass, we have to mess around with the PHP code to change the server IP, or change our DNS forwarder to redirect to a working line should the main line goes off.

So I told myself there must be a way to deal with the situation.

OK, I found a solution from the Net here.

The author uses a simple trick to see if there's reply from a HTTP socket connection. If there's a reply, then the server is alive, else, the server is off.

I took the code below:


// Function to check response time
function pingDomain($domain){
$starttime = microtime(true);
$file = fsockopen ($domain, 80, $errno, $errstr, 10);
$stoptime = microtime(true);
$status = 0;

if (!$file) $status = -1; // Site is down
else {
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
return $status;
}
?>


and added the below to my main PHP code, to decide if the server is accessible via a given line.

$line1="X.X.X.X";
$line2="Y.Y.Y.Y";
$siteport=":1433";

if(pingDomain($line1))
{

$MSSQL=$line1.$siteport;
}elseif(pingDomain($line2)){

$MSSQL=$line2.$siteport;
}

echo $MSSQL;

with the above, my code is now with failover function, even if is not really polished, it does work well.


No comments:

Post a Comment