public function render() { try { ob_start(); $reactor = \Amp\getReactor(); $client = new Client($reactor); $url = sprintf("http://%s/www-status?full&json", $this->domain->getCanonicalDomain()); $promise = $client->request($url); $response = \Amp\wait($promise); $headers = ["pool" => "Pool name", "process manager" => "Process manager", "start time" => "Start time", "start since" => "Uptime", "accepted conn" => "Accepted connections", "listen queue" => "Listen queue", "max listen queue" => "Max listen queue", "listen queue len" => "Listen queue length", "idle processes" => "Idle processes", "active processes" => "Active processes", "total processes" => "Total processes", "max active processes" => "Max active processes", "max children reached" => "Max children reached", "slow requests" => "Slow requests"]; $json = json_decode($response->getBody(), true); echo "<table class='table-serverSettings'>"; echo "<tr><th colspan='2'>Pool info</th></tr>"; foreach ($headers as $header => $display) { echo "<tr><td>"; echo $display; echo "</td><td>"; echo $json[$header]; echo "</td></tr>"; } echo "</table>"; echo "<div style='height: 20px;'></div>"; echo "<table class='table-serverSettings'>"; $processHeaders = ["pid", "state", "start since", "requests", "request URI", "content length", "script", "last request cpu", "last request memory"]; foreach ($processHeaders as $processHeader) { echo "<th>"; echo $processHeader; echo "</th>"; } if (isset($json['processes']) && is_array($json['processes'])) { foreach ($json['processes'] as $process) { echo "<tr>"; foreach ($processHeaders as $processHeader) { echo "<td align='right'>"; if (array_key_exists($processHeader, $process)) { $text = $process[$processHeader]; $text = str_replace(['/home/github/imagick-demos//imagick-demos', '/home/github/imagick-demos/imagick-demos'], '', $text); $text = ltrim($text, '/'); echo $text; } else { echo "-"; } echo "</td>"; } echo "</tr>"; } } echo "</table>"; echo "<br/>"; echo "<a href='http://127.0.0.1:9002'>SupervisorD</a>"; $output = ob_get_contents(); ob_end_clean(); return $output; } catch (\Exception $e) { while (ob_get_level() > 0) { ob_end_clean(); } return "Error fetch FPM status: " . $e->getMessage(); } }
public function getWebSocketUri(int $roomId) : string { $body = (new FormBody())->addField('roomid', $roomId)->addField('fkey', $this->fkeyRetriever->get('http://chat.stackoverflow.com/rooms/' . $roomId . '/php')); $request = (new Request())->setUri('http://chat.stackoverflow.com/ws-auth')->setMethod('POST')->setBody($body); $promise = $this->httpClient->request($request); $response = \Amp\wait($promise); return json_decode($response->getBody(), true)['url']; }
public function logIn() { $body = (new FormBody())->addField('email', $this->credentials->getEmailAddress())->addField('password', $this->credentials->getPassword())->addField('fkey', $this->fkeyRetriever->get(self::FKEY_URL)); $request = (new Request())->setUri(self::LOGIN_URL)->setMethod('POST')->setBody($body); $promise = $this->httpClient->request($request); $response = \Amp\wait($promise); if (!$this->verifyLogin($response->getBody())) { throw new FailedAuthenticationException(); } }
public function testLogWithExtraData() { $result = (new File(Level::DEBUG | Level::EXTRA_DATA, $this->logFile))->log(Level::DEBUG, 'foo', 'bar'); $this->assertInstanceOf(Promise::class, $result); \Amp\wait($result); $logLines = explode("\n", file_get_contents($this->logFile)); $this->assertSame(3, count($logLines)); $this->assertRegExp('~^\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\] foo$~', $logLines[0]); $this->assertRegExp('~^\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\] "bar"$~', $logLines[1]); $this->assertSame('', $logLines[2]); }
function createResponse() { ob_start(); $reactor = \Amp\getReactor(); $client = new Client($reactor); $url = "http://phpimagick.com/www-status?full&json"; $promise = $client->request($url); $response = \Amp\wait($promise); //$response = $promise->wait(); $headers = ["pool" => "Pool name", "process manager" => "Process manager", "start time" => "Start time", "start since" => "Uptime", "accepted conn" => "Accepted connections", "listen queue" => "Listen queue", "max listen queue" => "Max listen queue", "listen queue len" => "Listen queue length", "idle processes" => "Idle processes", "active processes" => "Active processes", "total processes" => "Total processes", "max active processes" => "Max active processes", "max children reached" => "Max children reached", "slow requests" => "Slow requests"]; $json = json_decode($response->getBody(), true); echo "<table>"; foreach ($headers as $header => $display) { echo "<tr><td>"; echo $display; echo "</td><td>"; echo $json[$header]; echo "</td></tr>"; } echo "</table>"; echo "<table>"; $processHeaders = ["pid", "state", "start time", "start since", "requests", "request duration", "request URI", "content length", "script", "last request cpu", "last request memory"]; foreach ($processHeaders as $processHeader) { echo "<th>"; echo $processHeader; echo "</th>"; } if (isset($json['processes']) && is_array($json['processes'])) { foreach ($json['processes'] as $process) { echo "<tr>"; foreach ($processHeaders as $processHeader) { echo "<td align='right'>"; if (array_key_exists($processHeader, $process)) { $text = $process[$processHeader]; $text = str_replace(['/home/github/imagick-demos//imagick-demos', '/home/github/imagick-demos/imagick-demos'], '', $text); $text = ltrim($text, '/'); echo $text; } else { echo "-"; } echo "</td>"; } echo "</tr>"; } } echo "</table>"; echo "<br/>"; echo "<a href='http://127.0.0.1:9002'>SupervisorD</a>"; $output = ob_get_contents(); ob_end_clean(); return new TextResponse($output); }
/** * @param $gauges Gauge[] * @param $counters Counter[] */ function send($gauges, $counters) { $client = new ArtaxClient(); $client->setAllOptions([ArtaxClient::OP_MS_CONNECT_TIMEOUT => 2000, ArtaxClient::OP_MS_TRANSFER_TIMEOUT => 3000]); $request = new Request(); $request->setUri("https://metrics-api.librato.com/v1/metrics"); $request->setProtocol('1.1'); $request->setMethod('POST'); $request->setHeader("Content-Type", "application/json"); $auth = base64_encode($this->libratoConfig->getLibratoUsername() . ':' . $this->libratoConfig->getLibratoKey()); $request->setHeader("Authorization", "Basic {$auth}"); $data = []; //working //"{"gauges":[{"name":"Queue.ImagickTaskQueue","value":0,"source":"test.phpimagick.com"}]}" if (count($gauges)) { $gaugeEntries = []; foreach ($gauges as $gauge) { $arrayed = $gauge->convertToArray(); $gaugeEntries = array_merge($gaugeEntries, $arrayed); } $data["gauges"] = $gaugeEntries; } if (count($counters)) { $counterEntries = []; foreach ($counters as $counter) { $arrayed = $counter->convertToArray(); if (is_array($arrayed) == true) { $counterEntries = array_merge($counterEntries, $arrayed); } else { $counterEntries[] = $arrayed; } } $data["counters"] = $counterEntries; } $body = json_encode($data); $request->setBody($body); var_dump($body); try { $promise = $client->request($request); /** @var $response \Amp\Artax\Response */ $response = \Amp\wait($promise); echo "Status " . $response->getStatus() . "\n"; echo $response->getBody(); } catch (SocketException $se) { echo "Artax\\SocketExeption" . $se->getMessage(); } }
public function __invoke(RequestInterface $request, array $options) { $artaxRequest = $this->convertRequest($request, $options); $artaxResponsePromise = $this->artaxClient->request($artaxRequest); $guzzleResponsePromise = new Promise(function () use($artaxResponsePromise) { \Amp\wait($artaxResponsePromise); }); $artaxResponsePromise->when(function ($error = null, Response $artaxResponse = null) use($request, $options, $guzzleResponsePromise) { if ($error) { $guzzleResponsePromise->reject($error); } else { $response = $this->convertResponse($artaxResponse, $request, $options); $guzzleResponsePromise->resolve($response); } }); return $guzzleResponsePromise; }
protected function doStart(Console $console) : \Generator { // Shutdown the whole server in case we needed to stop during startup register_shutdown_function(function () use($console) { if (!$this->server) { // ensure a clean reactor for clean shutdown $reactor = \Amp\reactor(); \Amp\reactor(\Amp\driver()); \Amp\wait((new CommandClient((string) $console->getArg("config")))->stop()); \Amp\reactor($reactor); } }); $server = (yield from $this->bootstrapper->boot($this->logger, $console)); (yield $server->start()); $this->server = $server; \Amp\onReadable($this->ipcSock, function ($watcherId) { \Amp\cancel($watcherId); yield from $this->stop(); }); }
private function performRequest($method, array $params = array(), array $headers = array()) { $headers = array_merge(array('Content-Type' => 'application/json; charset=utf-8', 'Accept-Encoding' => 'gzip, identity'), $headers); $request = (new \Amp\Artax\Request())->setUri(sprintf(self::TARGET_URI, $this->connectionClient->getProtocol(), $this->connectionClient->getHost(), $this->connectionClient->getPort()))->setAllHeaders($headers)->setMethod('POST')->setBody(json_encode(array('method' => $method, 'params' => $params, 'id' => rand()))); $response = \Amp\wait((new \Amp\Artax\Client())->request($request)); if ($response->getStatus() === 200) { $body = $response->getBody(); if (json_decode($body, true) !== null) { $responseBody = json_decode($body, true); if (!is_array($responseBody['error'])) { return $response; } else { throw new DelugeException(sprintf('"%s": Error intercepted during request: #%s %s', $method, $responseBody['error']['code'], $responseBody['error']['message'])); } } else { throw new DelugeException(sprintf('"%s": Invalid response received. Expecting JSON, "%s" given', $method, print_r($response->getBody(), true))); } } else { throw new DelugeException(sprintf('"%s": Incorrect HTTP status received. Expecting 200, "%s" given. Reason: "%s"', $method, $response->getStatus(), $response->getReason())); } }
/** * execute * * Sends a request to the API synchronously * * @param $request \Amp\Artax\Request The request to send. * @param $operation \ArtaxServiceBuilder\Operation The response that is called the * execute. * @return \Amp\Artax\Response The response from Artax */ public function execute(\Amp\Artax\Request $request, \ArtaxServiceBuilder\Operation $operation) { $originalRequest = clone $request; $cachingHeaders = $this->responseCache->getCachingHeaders($request); $request->setAllHeaders($cachingHeaders); $promise = $this->client->request($request); $response = \Amp\wait($promise, $this->reactor); if ($response) { $operation->setResponse($response); $operation->setOriginalResponse($response); } if ($operation->shouldResponseBeCached($response)) { $this->responseCache->storeResponse($originalRequest, $response); } if ($operation->shouldUseCachedResponse($response)) { $cachedResponse = $this->responseCache->getResponse($originalRequest); if ($cachedResponse) { $response = $cachedResponse; $operation->setResponse($response); } //@TODO This code should only be reached if the cache entry was deleted //so throw an exception? Or just leave the 304 to error? } $exception = $operation->translateResponseToException($response); if ($exception) { throw $exception; } return $response; }
private function registerShutdownHandler() { register_shutdown_function(function () { if (!($err = \error_get_last())) { return; } switch ($err["type"]) { case E_ERROR: case E_PARSE: case E_USER_ERROR: case E_CORE_ERROR: case E_CORE_WARNING: case E_COMPILE_ERROR: case E_COMPILE_WARNING: case E_RECOVERABLE_ERROR: break; default: return; } $this->exitCode = 1; $msg = "{$err["message"]} in {$err["file"]} on line {$err["line"]}"; $gen = function ($msg) { (yield $this->logger->critical($msg)); yield from $this->stop(); }; $promise = resolve($gen($msg)); \Amp\wait($promise); }); }
* * All successful responses are modeled as an Amp\Artax\Response and this result is used to resolve * the promise result. Status codes are accessible via the standard Amp\Artax\Response::getStatus() * method. These should be consulted to determine the success or failure of completed responses. */ $badUri = "this isn't even a real URI!"; $client = new Amp\Artax\Client(); // Yielding a promise that fails will result in an exception // being thrown back into your generator. Amp\run(function () use($client, $badUri) { try { $response = (yield $client->request($badUri)); } catch (Exception $e) { echo $e->getMessage(), "\n"; } }); // Synchronously waiting on a promise that fails will throw. try { $response = Amp\wait($client->request($badUri)); } catch (Exception $e) { echo $e->getMessage(), "\n"; } // Amp\Promise::when() will never throw; errors are passed to // the error-first callback. Amp\run(function () use($client, $badUri) { $client->request($badUri)->when(function ($error, $result) { assert($error instanceof Exception); assert(is_null($result)); echo $error->getMessage(), "\n"; }); });
<?php require __DIR__ . '/../vendor/autoload.php'; try { // Instantiate the HTTP client $client = new Amp\Artax\Client(); // Make an asynchronous HTTP request $promise = $client->request('http://httpbin.org/user-agent'); // Client::request() is asynchronous! It doesn't return a response. Instead, it // returns a promise to resolve the response at some point in the future when // it's finished. Here we use the Amp concurrency framework to synchronously wait // for the eventual promise result. $response = \Amp\wait($promise); // Output the results printf("\nHTTP/%s %d %s\n", $response->getProtocol(), $response->getStatus(), $response->getReason()); } catch (Amp\Artax\ClientException $error) { // If something goes wrong the Promise::wait() call will throw the relevant // exception. The Client::request() method itself will never throw. echo $error; }
public function testMultipartBodyRequest() { $uri = 'http://httpbin.org/post'; $client = new Client(); $field1 = 'test val'; $file1 = __DIR__ . '/fixture/lorem.txt'; $file2 = __DIR__ . '/fixture/answer.txt'; $boundary = 'AaB03x'; $body = new FormBody($boundary); $body->addField('field1', $field1); $body->addFile('file1', $file1); $body->addFile('file2', $file2); $request = (new Request())->setBody($body)->setUri('http://httpbin.org/post')->setMethod('POST'); $promise = $client->request($request); $response = \Amp\wait($promise); $this->assertEquals(200, $response->getStatus()); $result = json_decode($response->getBody(), true); $this->assertEquals($field1, $result['form']['field1']); $this->assertEquals(file_get_contents($file1), $result['files']['file1']); $this->assertEquals(file_get_contents($file2), $result['files']['file2']); $this->assertEquals('multipart/form-data; boundary=' . $boundary, $result['headers']['Content-Type']); }
/** * @param string $name * @return mixed * @throws \Throwable */ public function revoke($name = '') { return \Amp\wait(\Amp\resolve($this->doRevoke($name))); }
<?php require __DIR__ . '/../vendor/autoload.php'; /** * Note that Client::requestMulti() is nothing more than a convenience wrapper * to prevent us from having to call Client::request() several times and store * the resulting promises in an array ourselves. Doing so would have the exact * same effect and all requests would be executed in parallel either way. */ $promises = (new Amp\Artax\Client())->requestMulti(['google' => 'http://www.google.com', 'news' => 'http://news.google.com', 'bing' => 'http://www.bing.com', 'yahoo' => 'https://www.yahoo.com']); // Tolerate errors in some of the requests. If any one of the promises in our array // succeeds then the result is a two-item array of errors and successes. If *none* // of our response promises succeed then this line will throw. $comboPromise = Amp\some($promises); list($errors, $responses) = Amp\wait($comboPromise); // Alternatively we could use the following line to require all of our responses to succeed. If // any one of the response promises resolves as a failure then this line will throw: $comboPromise = Amp\all($promises); $responses = Amp\wait($comboPromise); // Now, let's iterate over the responses to demonstrate that they retain the same keys from // our original call to Amp\Artax\Client::request(): foreach ($responses as $key => $response) { printf("%s | HTTP/%s %d %s\n", $key, $response->getProtocol(), $response->getStatus(), $response->getReason()); }
/** * @param $email * @return Registration * @throws \Throwable */ public function setup($email) { return \Amp\wait(\Amp\resolve($this->doSetup($email))); }
/** * @return mixed * @throws \Throwable */ public function info() { return \Amp\wait(\Amp\resolve($this->doInfo())); }
/** * @param array $domains * @return mixed * @throws \Throwable */ public function issue($domains = []) { return \Amp\wait(\Amp\resolve($this->doIssue($domains))); }
public function get(string $url) : string { $promise = $this->httpClient->request($url); $response = \Amp\wait($promise); return $this->getFromHtml($response->getBody()); }
public function testMethodNotAllowedResponseOnUriMatchWithUnroutableMethod() { $uri = self::$baseUri . '/test-function-target'; $request = new Request(); $request->setUri($uri)->setMethod('POST'); $response = \Amp\wait(self::$client->request($request)); $this->assertEquals(405, $response->getStatus()); }