public function Apache_Solr_Service::ping in Apache Solr Search 5
Call the /admin/ping servlet, can be used to quickly tell if a connection to the server is able to be made.
Parameters
float $timeout maximum time to wait for ping in seconds, -1 for unlimited (default is 2):
Return value
float Actual time taken to ping the server, FALSE if timeout occurs
File
- SolrPhpClient/
Apache/ Solr/ Service.php, line 520
Class
- Apache_Solr_Service
- Starting point for the Solr API. Represents a Solr server resource and has methods for pinging, adding, deleting, committing, optimizing and searching.
Code
public function ping($timeout = 2) {
$timeout = (double) $timeout;
if ($timeout <= 0) {
$timeout = -1;
}
$start = microtime(true);
//to prevent strict errors
$errno = 0;
$errstr = '';
//try to connect to the host with timeout
$fp = fsockopen($this->_host, $this->_port, $errno, $errstr, $timeout);
if ($fp) {
//If we have a timeout set, then determine the amount of time we have left
//in the request and set the stream timeout for the write operation
if ($timeout > 0) {
//do the calculation
$writeTimeout = $timeout - (microtime(true) - $start);
//check if we're out of time
if ($writeTimeout <= 0) {
fclose($fp);
return false;
}
//convert to microseconds and set the stream timeout
$writeTimeoutInMicroseconds = (int) $writeTimeout * 1000000;
stream_set_timeout($fp, 0, $writeTimeoutInMicroseconds);
}
$request = 'HEAD ' . $this->_path . self::PING_SERVLET . ' HTTP/1.1' . "\r\n" . 'host: ' . $this->_host . "\r\n" . 'Connection: close' . "\r\n" . "\r\n";
fwrite($fp, $request);
//check the stream meta data to see if we timed out during the operation
$metaData = stream_get_meta_data($fp);
if (isset($metaData['timeout']) && $metaData['timeout']) {
fclose($fp);
return false;
}
//if we have a timeout set and have made it this far, determine the amount of time
//still remaining and set the timeout appropriately before the read operation
if ($timeout > 0) {
//do the calculation
$readTimeout = $timeout - (microtime(true) - $start);
//check if we've run out of time
if ($readTimeout <= 0) {
fclose($fp);
return false;
}
//convert to microseconds and set the stream timeout
$readTimeoutInMicroseconds = $readTimeout * 1000000;
stream_set_timeout($fp, 0, $readTimeoutInMicroseconds);
}
//at the very least we should get a response header line of
//HTTP/1.1 200 OK
$response = fread($fp, 15);
//check the stream meta data to see if we timed out during the operation
$metaData = stream_get_meta_data($fp);
fclose($fp);
//we're done with the connection - ignore the rest
if (isset($metaData['timeout']) && $metaData['timeout']) {
return false;
}
//finally, check the response header line
if ($response != 'HTTP/1.1 200 OK') {
return false;
}
//we made it, return the approximate ping time
return microtime(true) - $start;
}
//we weren't able to make a connection
return false;
}