diff --git a/changes.txt b/changes.txt index 46c0959bd7..dc846403e7 100755 --- a/changes.txt +++ b/changes.txt @@ -1,5 +1,8 @@ CHANGES +2014-05-25 +- Added Guzzle transport as an alternative to the default Http transport + 2014-05-13 - Add JSON compat library; Elasticsearch JSON flags and nicer error handling diff --git a/composer.json b/composer.json index 172f296ae2..62e5d45d64 100644 --- a/composer.json +++ b/composer.json @@ -22,6 +22,7 @@ }, "suggest": { "munkie/elasticsearch-thrift-php": "Allow using thrift transport", + "guzzlehttp/guzzle": "Allow using guzzle 4.x as the http transport (requires php 5.4)", "psr/log": "for logging", "monolog/monolog": "Logging request" }, diff --git a/lib/Elastica/Exception/Connection/GuzzleException.php b/lib/Elastica/Exception/Connection/GuzzleException.php new file mode 100644 index 0000000000..645c0eff3e --- /dev/null +++ b/lib/Elastica/Exception/Connection/GuzzleException.php @@ -0,0 +1,51 @@ + + */ +class GuzzleException extends ConnectionException +{ + /** + * @var TransferException + */ + protected $_guzzleException; + + /** + * @param \GuzzleHttp\Exception\TransferException $guzzleException + * @param \Elastica\Request $request + * @param \Elastica\Response $response + */ + public function __construct(TransferException $guzzleException, Request $request = null, Response $response = null) + { + $this->_guzzleException = $guzzleException; + $message = $this->getErrorMessage($this->getGuzzleException()); + parent::__construct($message, $request, $response); + } + + /** + * @param \GuzzleHttp\Exception\TransferException $guzzleException + * @return string + */ + public function getErrorMessage(TransferException $guzzleException) + { + return $guzzleException->getMessage(); + } + + /** + * @return TransferException + */ + public function getGuzzleException() + { + return $this->_guzzleException; + } +} diff --git a/lib/Elastica/Transport/Guzzle.php b/lib/Elastica/Transport/Guzzle.php new file mode 100644 index 0000000000..38e08baee4 --- /dev/null +++ b/lib/Elastica/Transport/Guzzle.php @@ -0,0 +1,179 @@ + + */ +class Guzzle extends AbstractTransport +{ + /** + * Http scheme + * + * @var string Http scheme + */ + protected $_scheme = 'http'; + + /** + * Curl resource to reuse + * + * @var resource Guzzle resource to reuse + */ + protected static $_guzzleClientConnection = null; + + /** + * Makes calls to the elasticsearch server + * + * All calls that are made to the server are done through this function + * + * @param \Elastica\Request $request + * @param array $params Host, Port, ... + * @throws \Elastica\Exception\ConnectionException + * @throws \Elastica\Exception\ResponseException + * @throws \Elastica\Exception\Connection\HttpException + * @return \Elastica\Response Response object + */ + public function exec(Request $request, array $params) + { + $connection = $this->getConnection(); + + try { + $client = $this->_getGuzzleClient($this->_getBaseUrl($connection), $connection->isPersistent()); + + $options = array(); + if ($connection->getTimeout()) { + $options['timeout'] = $connection->getTimeout(); + } + + if ($connection->getProxy()) { + $options['proxy'] = $connection->getProxy(); + } + + $req = $client->createRequest($request->getMethod(), $this->_getActionPath($request), $options); + $req->setHeaders($connection->hasConfig('headers') ?: array()); + + $data = $request->getData(); + if (isset($data) && !empty($data)) { + + if ($req->getMethod() == Request::GET) { + $req->setMethod(Request::POST); + } + + if ($this->hasParam('postWithRequestBody') && $this->getParam('postWithRequestBody') == true) { + $request->setMethod(Request::POST); + $req->setMethod(Request::POST); + } + + if (is_array($data)) { + $content = JSON::stringify($data, 'JSON_ELASTICSEARCH'); + } else { + $content = $data; + } + $req->setBody(Stream::factory($content)); + } + + $start = microtime(true); + $res = $client->send($req); + $end = microtime(true); + + $response = new Response((string)$res->getBody(), $res->getStatusCode()); + + if (defined('DEBUG') && DEBUG) { + $response->setQueryTime($end - $start); + } + + $response->setTransferInfo( + array( + 'request_header' => $request->getMethod(), + 'http_code' => $res->getStatusCode() + ) + ); + + if ($response->hasError()) { + throw new ResponseException($request, $response); + } + + if ($response->hasFailedShards()) { + throw new PartialShardFailureException($request, $response); + } + + return $response; + + } catch (ClientException $e) { + // ignore 4xx errors + } catch (TransferException $e) { + throw new GuzzleException($e, $request, new Response($e->getMessage())); + } + + } + + /** + * Return Guzzle resource + * + * @param bool $persistent False if not persistent connection + * @return resource Connection resource + */ + protected function _getGuzzleClient($baseUrl, $persistent = true) + { + if (!$persistent || !self::$_guzzleClientConnection) { + self::$_guzzleClientConnection = new Client(array('base_url' => $baseUrl)); + } + + return self::$_guzzleClientConnection; + } + + /** + * Builds the base url for the guzzle connection + * + * @param \Elastica\Connection $connection + */ + protected function _getBaseUrl(Connection $connection) + { + // If url is set, url is taken. Otherwise port, host and path + $url = $connection->hasConfig('url') ? $connection->getConfig('url') : ''; + + if (!empty($url)) { + $baseUri = $url; + } else { + $baseUri = $this->_scheme . '://' . $connection->getHost() . ':' . $connection->getPort() . '/' . $connection->getPath(); + } + return rtrim($baseUri, '/'); + } + + /** + * Builds the action path url for each request + * + * @param \Elastica\Request $request + */ + protected function _getActionPath(Request $request) + { + $action = $request->getPath(); + if ($action) { + $action = '/'. ltrim($action, '/'); + } + $query = $request->getQuery(); + + if (!empty($query)) { + $action .= '?' . http_build_query($query); + } + + return $action; + } +} diff --git a/test/lib/Elastica/Test/Transport/GuzzleTest.php b/test/lib/Elastica/Test/Transport/GuzzleTest.php new file mode 100644 index 0000000000..b2e385bb10 --- /dev/null +++ b/test/lib/Elastica/Test/Transport/GuzzleTest.php @@ -0,0 +1,163 @@ +markTestSkipped('The DEBUG constant must be set to true for this test to run'); + } + + if (!defined('DEBUG')) { + define('DEBUG', true); + } + } + + /** + * Return transport configuration and the expected HTTP method + * + * @return array[] + */ + public function getConfig() + { + return array( + array( + array('transport' => 'Guzzle'), + 'GET' + ), + array( + array('transport' => array('type' => 'Guzzle', 'postWithRequestBody' => false)), + 'GET' + ), + array( + array('transport' => array('type' => 'Guzzle', 'postWithRequestBody' => true)), + 'POST' + ), + ); + } + + /** + * @dataProvider getConfig + */ + public function testDynamicHttpMethodBasedOnConfigParameter(array $config, $httpMethod) + { + $client = new Client($config); + + $index = $client->getIndex('dynamic_http_method_test'); + $index->create(array(), true); + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('test' => 'test'))); + $index->refresh(); + $resultSet = $index->search('test'); + $info = $resultSet->getResponse()->getTransferInfo(); + $this->assertStringStartsWith($httpMethod, $info['request_header']); + } + + /** + * @dataProvider getConfig + */ + public function testDynamicHttpMethodOnlyAffectsRequestsWithBody(array $config, $httpMethod) + { + $client = new Client($config); + + $status = $client->getStatus(); + $info = $status->getResponse()->getTransferInfo(); + $this->assertStringStartsWith('GET', $info['request_header']); + } + + public function testWithEnvironmentalProxy() + { + putenv('http_proxy=http://127.0.0.1:12345/'); + + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + $client->getConnection()->setProxy(null); // will not change anything + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + putenv('http_proxy='); + } + + public function testWithEnabledEnvironmentalProxy() + { + putenv('http_proxy=http://127.0.0.1:12346/'); + + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(403, $transferInfo['http_code']); + + $client = new \Elastica\Client(); + $client->getConnection()->setProxy(''); + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + + putenv('http_proxy='); + } + + public function testWithProxy() + { + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + $client->getConnection()->setProxy('http://127.0.0.1:12345'); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + } + + public function testWithoutProxy() + { + $client = new \Elastica\Client(array('transport' => 'Guzzle')); + $client->getConnection()->setProxy(''); + + $transferInfo = $client->request('/_nodes')->getTransferInfo(); + $this->assertEquals(200, $transferInfo['http_code']); + } + + public function testBodyReuse() + { + $client = new Client(array('transport' => 'Guzzle')); + + $index = $client->getIndex('elastica_body_reuse_test'); + + $index->create(array(), true); + + $type = $index->getType('test'); + $type->addDocument(new Document(1, array('test' => 'test'))); + + $index->refresh(); + + $resultSet = $index->search(array( + 'query' => array( + 'query_string' => array( + 'query' => 'pew pew pew', + ), + ), + )); + + $this->assertEquals(0, $resultSet->getTotalHits()); + + $response = $index->request('/_search', 'POST'); + $resultSet = new ResultSet($response, Query::create(array())); + + $this->assertEquals(1, $resultSet->getTotalHits()); + } + +}