protected function setupRequest($url) { $r = new HttpRequest($url); $r->setOptions(array('redirect' => true)); $file = $this->url2name($url); if (isset($this->feeds[$file])) { $r->setOptions(array('lastmodified' => $this->feeds[$file])); } return $r; }
/** * Makes api request * * @param string $qid The id of the query. * @param array $options optional Query options for the request. * @param string $path optional Uri path for the request (/user by default) * @param string $method optional Http method (GET by default) * @return object Returns object that is an response data. * @throws CloudynException */ public function call($qid, array $options = array(), $path = '/user', $method = 'GET') { $options['qid'] = (string) $qid; $options['out'] = self::OUT_JSON; if (!isset($options['rqid'])) { $options['rqid'] = $this->getRequestId(); } if (!isset($options['apiversion'])) { $options['apiversion'] = '0.4'; } $this->request = $this->createNewRequest(); $this->request->setUrl($this->getUrl() . $path); $this->request->setMethod(constant('HTTP_METH_' . strtoupper($method))); $this->request->setOptions(array('redirect' => 10, 'useragent' => 'Scalr Client (http://scalr.com)')); $this->request->addQueryData($options); //This line is very necessary or HttpResponce will add stored cookies $this->request->resetCookies(); $this->message = $this->tryCall($this->request); $json = $this->message->getBody(); $json = preg_replace('#^[^\\{\\[]+|[^\\}\\]]+$#', '', trim($json)); $obj = json_decode($json); if (isset($obj->status) && $obj->status != 'ok' && isset($obj->message)) { throw new CloudynException('Cloudyn error. ' . $obj->message); } return $obj; }
/** * Send this HTTP request * * @throws Horde_Http_Exception * @return Horde_Http_Response_Base */ public function send() { if (!defined('HTTP_METH_' . $this->method)) { throw new Horde_Http_Exception('Method ' . $this->method . ' not supported.'); } $httpRequest = new HttpRequest((string) $this->uri, constant('HTTP_METH_' . $this->method)); $data = $this->data; if (is_array($data)) { $httpRequest->setPostFields($data); } else { if ($this->method == 'PUT') { $httpRequest->setPutData($data); } else { $httpRequest->setBody($data); } } $httpRequest->setOptions($this->_httpOptions()); try { $httpResponse = $httpRequest->send(); } catch (HttpException $e) { if (isset($e->innerException)) { throw new Horde_Http_Exception($e->innerException); } else { throw new Horde_Http_Exception($e); } } return new Horde_Http_Response_Peclhttp((string) $this->uri, $httpResponse); }
protected function request($method, $uri, $args) { $parsedUrl = parse_url($this->ec2Url); $uri = "{$parsedUrl['path']}{$uri}"; $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)")); $args['Version'] = $this->apiVersion; $args['SignatureVersion'] = 2; $args['SignatureMethod'] = "HmacSHA256"; $args['Timestamp'] = $this->getTimestamp(); $args['AWSAccessKeyId'] = $this->accessKeyId; ksort($args); foreach ($args as $k => $v) { $CanonicalizedQueryString .= "&{$k}=" . rawurlencode($v); } $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&"); $url = $parsedUrl['port'] ? "{$parsedUrl['host']}:{$parsedUrl['port']}" : "{$parsedUrl['host']}"; $args['Signature'] = $this->getSignature(array($method, $url, $uri, $CanonicalizedQueryString)); $HttpRequest->setUrl("{$parsedUrl['scheme']}://{$url}{$uri}"); $HttpRequest->setMethod(constant("HTTP_METH_{$method}")); if ($args) { if ($method == 'POST') { $HttpRequest->setPostFields($args); $HttpRequest->setHeaders(array('Content-Type' => 'application/x-www-form-urlencoded')); } else { $HttpRequest->addQueryData($args); } } try { $HttpRequest->send(); $data = $HttpRequest->getResponseData(); if ($HttpRequest->getResponseCode() == 200) { $response = simplexml_load_string($data['body']); if ($this->responseFormat == 'Object') { $json = @json_encode($response); $response = @json_decode($json); } if ($response->Errors) { throw new Exception($response->Errors->Error->Message); } else { return $response; } } else { $response = @simplexml_load_string($data['body']); if ($response) { throw new Exception($response->Error->Message); } throw new Exception(trim($data['body'])); } $this->LastResponseHeaders = $data['headers']; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception($message); } }
public function OnStartForking() { $db = \Scalr::getDb(); // Get pid of running daemon $pid = @file_get_contents(CACHEPATH . "/" . __CLASS__ . ".Daemon.pid"); $this->Logger->info("Current daemon process PID: {$pid}"); // Check is daemon already running or not if ($pid) { $Shell = new Scalr_System_Shell(); // Set terminal width putenv("COLUMNS=400"); // Execute command $ps = $Shell->queryRaw("ps ax -o pid,ppid,command | grep ' 1' | grep {$pid} | grep -v 'ps x' | grep DBQueueEvent"); $this->Logger->info("Shell->queryRaw(): {$ps}"); if ($ps) { // daemon already running $this->Logger->info("Daemon running. All ok!"); return true; } } $rows = $db->Execute("SELECT history_id FROM webhook_history WHERE status='0'"); while ($row = $rows->FetchRow()) { $history = WebhookHistory::findPk(bin2hex($row['history_id'])); if (!$history) { continue; } $endpoint = WebhookEndpoint::findPk($history->endpointId); $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); if ($endpoint->url == 'SCALR_MAIL_SERVICE') { $request->setUrl('https://my.scalr.com/webhook_mail.php'); } else { $request->setUrl($endpoint->url); } $request->setOptions(array('timeout' => 3, 'connecttimeout' => 3)); $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D, d M Y H:i:s e"); $canonical_string = $history->payload . $timestamp; $signature = hash_hmac('SHA1', $canonical_string, $endpoint->securityKey); $request->addHeaders(array('Date' => $timestamp, 'X-Signature' => $signature, 'X-Scalr-Webhook-Id' => $history->historyId, 'Content-type' => 'application/json')); $request->setBody($history->payload); try { $request->send(); $history->responseCode = $request->getResponseCode(); if ($request->getResponseCode() <= 205) { $history->status = WebhookHistory::STATUS_COMPLETE; } else { $history->status = WebhookHistory::STATUS_FAILED; } } catch (Exception $e) { $history->status = WebhookHistory::STATUS_FAILED; } $history->save(); } }
protected function request($uri, $method, $data) { $httpRequest = new HttpRequest(); $httpRequest->setOptions(array("useragent" => "Scalr (https://scalr.net)")); $httpRequest->setUrl("{$this->apiUrl}{$uri}"); $httpRequest->setMethod($method); $httpRequest->resetCookies(); $httpRequest->addHeaders(array('Cookie' => $this->sessionCookie, 'Content-Type' => 'application/nimbula-v1+json')); switch ($method) { case HTTP_METH_POST: $httpRequest->setRawPostData(json_encode($data)); $httpRequest->addHeaders(array('Content-Type' => 'application/nimbula-v1+json')); break; } try { $httpRequest->send(); $data = $httpRequest->getResponseData(); $result = @json_decode($data['body']); if ($httpRequest->getResponseCode() > 204) { $message = $result->message; if ($message) { if ($message instanceof stdClass) { $r = (array) $message; $msg = ''; foreach ($r as $k => $v) { $msg .= "{$k}: {$v} "; } throw new Exception(trim($msg)); } else { throw new Exception($message); } } throw new Exception($data['body']); } $headers = $httpRequest->getResponseHeader('Set-Cookie'); if ($headers) { if (!is_array($headers)) { if (stristr($headers, "nimbula")) { $this->sessionCookie = $headers; } } else { } } $this->LastResponseHeaders = $data['headers']; return $result; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception("Nimbula error: {$message}"); } }
private function _OssMethods($action, $key, $files = false) { if (!$key || !$action) return; if ($action != 'DELETE' && $action != 'PUT') return; $options = array( 'useragent' => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YINUOINFO API; Alexa Toolbar)", 'connecttimeout' => 120, 'timeout' => 120, 'redirect' => 10, ); if ($action == 'DELETE') { $r = new HttpRequest(self::OssBaseURL . 'delete.php?key=' . $key, HTTP_METH_GET); $r->setOptions($options); $r->addHeaders(array('Authorization' => 'Basic ' . base64_encode(self::US_UP_AUTHORIZATION))); try { $ret = $r->send()->getBody(); if ($ret == 'success') return 1; } catch (HttpException $e) { return 0; } } if ($action == 'PUT') { if (self::UseLocalFile && !APP_DEV){ $r = new HttpRequest(self::LocalOssBaseURL . 'local_upload.php', HTTP_METH_POST); $r->setPostFields(array('key' => $key,'localfile' => $files)); }else { $r = new HttpRequest(self::OssBaseURL . 'upload.php', HTTP_METH_POST); $r->setPostFields(array('key' => $key)); $r->addPostFile('file', $files, 'image/jpeg'); } $r->setOptions($options); $r->addHeaders(array('Authorization' => 'Basic ' . base64_encode(self::US_UP_AUTHORIZATION))); try { $ret = $r->send()->getBody(); if (preg_match("/OK/i", $ret)) return 1; } catch (HttpException $e) { return 0; } } return 0; }
private function Request($method, $uri, $args) { $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)")); $timestamp = $this->GetTimestamp(); $URL = "queue.amazonaws.com"; if ($this->Region != 'us-east-1') { $URL = "{$this->Region}.queue.amazonaws.com"; } //EU URL: eu-west-1.queue.amazonaws.com $args['Version'] = self::API_VERSION; $args['SignatureVersion'] = 2; $args['SignatureMethod'] = "HmacSHA1"; $args['Expires'] = $timestamp; $args['AWSAccessKeyId'] = $this->AWSAccessKeyId; ksort($args); foreach ($args as $k => $v) { $CanonicalizedQueryString .= "&{$k}=" . urlencode($v); } $CanonicalizedQueryString = trim($CanonicalizedQueryString, "&"); $args['Signature'] = $this->GetRESTSignature(array($method, $URL, $uri, $CanonicalizedQueryString)); $HttpRequest->setUrl("https://{$URL}{$uri}"); $HttpRequest->setMethod(constant("HTTP_METH_{$method}")); if ($args) { $HttpRequest->addQueryData($args); } try { $HttpRequest->send(); //$info = $HttpRequest->getResponseInfo(); $data = $HttpRequest->getResponseData(); $this->LastResponseHeaders = $data['headers']; $response = simplexml_load_string($data['body']); if ($response->Error) { throw new Exception($response->Error->Message); } else { return $response; } } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception($message); } }
public function getValue(DBFarmRole $dbFarmRole, Scalr_Scaling_FarmRoleMetric $farmRoleMetric) { $start_time = microtime(true); $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "Scalr (http://scalr.net) HTTPResponseTime Scaling Sensor", "connecttimeout" => 10)); $HttpRequest->setUrl($farmRoleMetric->getSetting(self::SETTING_URL)); $HttpRequest->setMethod(constant("HTTP_METH_GET")); try { $HttpRequest->send(); } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception("HTTPResponseTime Scaling Sensor cannot get value: {$message}"); } $retval = round(microtime(true) - $start_time, 2); return array($retval); }
public function Login() { $signature = $this->SignMessage("frob", $this->Frob, "perms", "delete"); $query = "api_key={$this->ApiKey}&perms=delete&frob={$this->Frob}&api_sig={$signature}"; $request = new HttpRequest("http://flickr.com/services/auth/", HTTP_METH_GET); $request->setQueryData($query); $request->enableCookies(); $request->setOptions(array( "redirect" => 10, "useragent" => "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" ) ); $request->send(); var_dump($request->getResponseCode()); print_r($request->getResponseBody()); var_dump($request->getResponseStatus()); }
function http_get_file($url) { $r = new HttpRequest($url, HttpRequest::METH_GET); $r->setOptions(array('redirect' => 5)); try { $r->send(); if ($r->getResponseCode() == 200) { $dir = $r->getResponseBody(); } else { echo "Respose code " . $r->getResponseCode() . "({$url})\n"; echo $r->getResponseBody() . "({$url})\n"; return "-2"; } } catch (HttpException $ex) { echo $ex; return "-3"; } $dir = strip_tags($dir); return explode("\n", $dir); // An array of lines from the url }
private function request($method, Object $params = null) { $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = $params; $jsonRequest = json_encode($requestObj); $timestamp = date("D d M Y H:i:s T"); $dt = new DateTime($timestamp, new DateTimeZone("CDT")); $timestamp = Scalr_Util_DateTime::convertDateTime($dt, new DateTimeZone("UTC"), new DateTimeZone("CDT"))->format("D d M Y H:i:s"); $timestamp .= " UTC"; $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1)); $request = new HttpRequest("http://{$this->dbServer->remoteIp}:{$this->port}/", HTTP_METH_POST); $request->setOptions(array('timeout' => 5, 'connecttimeout' => 5)); $request->setHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setRawPostData($jsonRequest); try { // Send request $request->send(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $jResponse = @json_decode($response['body']); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}"); } return $jResponse; } else { throw new Exception(sprintf("Unable to perform request to update client: %s", $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } throw new Exception(sprintf("Unable to perform request to update client: %s", $msg)); } }
private function Request($method, $uri, $request_body, $query_args, $headers = array()) { $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)")); $timestamp = $this->GetTimestamp(); $signature = $this->GetRESTSignature($timestamp); $HttpRequest->setUrl("https://cloudfront.amazonaws.com/" . self::API_VERSION . $uri); $HttpRequest->setMethod($method); if ($query_args) { $HttpRequest->addQueryData($query_args); } if ($request_body) { if ($method == constant("HTTP_METH_POST")) { $HttpRequest->setRawPostData(trim($request_body)); } else { $HttpRequest->setPutData(trim($request_body)); } $headers["Content-type"] = "text/xml"; } $headers["Date"] = $timestamp; $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}"; $HttpRequest->addHeaders($headers); try { $HttpRequest->send(); //$info = $HttpRequest->getResponseInfo(); $data = $HttpRequest->getResponseData(); $this->LastResponseHeaders = $data['headers']; return $data['body']; } catch (Exception $e) { if ($e->innerException) { $message = $e->innerException->getMessage(); } else { $message = $e->getMessage(); } throw new Exception($message); } }
private function request($method, $params = null) { $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = $params; $jsonRequest = json_encode($requestObj); $newEncryptionProtocol = false; //TODO: if ($this->dbServer->farmRoleId) { if ($this->dbServer->IsSupported('2.7.7')) { $newEncryptionProtocol = true; } } $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D d M Y H:i:s e"); if ($newEncryptionProtocol) { $jsonRequest = $this->cryptoTool->encrypt($jsonRequest, $this->dbServer->GetKey(true)); $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1)); } else { $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetProperty(SERVER_PROPERTIES::SZR_KEY), 1)); } $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}"; if ($this->isVPC) { $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->dbServer->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port)); // There is public IP, can use it } else { $requestHost = "{$this->dbServer->remoteIp}:{$this->port}"; } } } $request->setUrl($requestHost); $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => $this->timeout)); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setBody($jsonRequest); try { // Send request $request->send(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $body = $response['body']; if ($newEncryptionProtocol) { $body = $this->cryptoTool->decrypt($body, $this->dbServer->GetKey(true)); } $jResponse = @json_decode($body); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data} ({$response['body']})"); } return $jResponse; } else { throw new Exception(sprintf("Unable to perform request to update client: %s", $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } throw new Exception(sprintf("Unable to perform request to update client: %s", $msg)); } }
/** * Send message to instance * @param Scalr_Messaging_Msg $message * @return Scalr_Messaging_Msg */ public function SendMessage(Scalr_Messaging_Msg $message, $isEventNotice = false, $delayed = false) { $startTime = microtime(true); if ($this->farmId && $message->getName() != 'BeforeHostTerminate') { if ($this->GetFarmObject()->Status == FARM_STATUS::TERMINATED) { $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::FAILED, $message->messageId)); return; } } // // To avoid message flood if server cannot respond // Protection from DDOS // Log only right now /* $pendingMessagesCount = $this->Db->GetOne("SELECT COUNT(*) FROM messages WHERE status = '0' OR server_id = ?", array( $this->serverId )); if ($pendingMessagesCount > 50) { if ($message->serverId != $this->serverId) { $this->SetProperty('tmp.flood-alert', 1); } } */ // Ignore OLD messages (ami-scripts) if (!$this->IsSupported("0.5")) { return; } // Put access data and reserialize message $pl = PlatformFactory::NewPlatform($this->platform); $pl->PutAccessData($this, $message); $logger = Logger::getLogger('DBServer'); $serializer = Scalr_Messaging_XmlSerializer::getInstance(); $cryptoTool = \Scalr::getContainer()->srzcrypto($this->GetKey(true)); if ($this->GetProperty(\SERVER_PROPERTIES::SZR_MESSAGE_FORMAT) == 'json') { $serializer = Scalr_Messaging_JsonSerializer::getInstance(); $rawMessage = $serializer->serialize($message); $messageType = 'json'; } else { $rawMessage = $serializer->serialize($message); $messageType = 'xml'; } //$rawJsonMessage = @json_encode($message); $time = microtime(true) - $startTime; if (!$this->Db->GetOne("SELECT COUNT(*) FROM `messages` WHERE `messageid` = ? AND `server_id` = ?", [$message->messageId, $this->serverId])) { // Add message to database $this->Db->Execute("INSERT INTO messages SET\n `messageid` = ?,\n `processing_time` = ?,\n `server_id` = ?,\n `event_server_id` = ?,\n `message` = ?,\n `type` = 'out',\n `message_name` = ?,\n `handle_attempts` = ?,\n `message_version` = ?,\n `dtlasthandleattempt` = NOW(),\n `dtadded` = NOW(),\n `message_format` = ?,\n `event_id` = ?\n ON DUPLICATE KEY UPDATE handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW()\n ", array($message->messageId, $time, $this->serverId, $message->serverId, $rawMessage, $message->getName(), $delayed ? '0' : '1', 2, $messageType, isset($message->eventId) ? $message->eventId : '')); } else { $this->Db->Execute("UPDATE messages SET handle_attempts = handle_attempts+1, dtlasthandleattempt = NOW() WHERE messageid = ? AND server_id = ?", array($message->messageId, $this->serverId)); } if ($delayed) { return $message; } $isVPC = false; if ($this->farmId) { if (DBFarm::LoadByID($this->farmId)->GetSetting(DBFarm::SETTING_EC2_VPC_ID)) { $isVPC = true; } } if (!$this->remoteIp && !$this->localIp && !$isVPC) { return; } $cryptoTool->setCryptoKey($this->GetKey(true)); $encMessage = $cryptoTool->encrypt($rawMessage); $timestamp = date("c", time()); $signature = $cryptoTool->sign($encMessage, null, $timestamp); try { $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); $ctrlPort = $this->getPort(self::PORT_CTRL); $requestHost = $this->getSzrHost() . ":{$ctrlPort}"; if ($isVPC) { $routerFarmRoleId = $this->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->localIp, "X-Receiver-Port" => $ctrlPort)); // There is public IP, can use it } else { $requestHost = "{$this->remoteIp}:{$ctrlPort}"; } } } //Prepare request $request->setUrl("http://{$requestHost}/control"); $request->setOptions(array('timeout' => \Scalr::config('scalr.system.instances_connection_timeout'), 'connecttimeout' => \Scalr::config('scalr.system.instances_connection_timeout'))); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, 'X-Server-Id' => $this->serverId)); if ($messageType == 'json') { $request->addHeaders(array('Content-type' => 'application/json')); } $request->setBody($encMessage); // Send request $request->send(); // Process response if ($request->getResponseCode() == 201) { $logger->info(sprintf("[FarmID: %s] Sending message '%s' via REST to server '%s' (server_id: %s) completed", $this->farmId, $message->getName(), $this->remoteIp, $this->serverId)); if (in_array($message->getName(), array('ExecScript'))) { $this->Db->Execute("DELETE FROM messages WHERE messageid = ?", array($message->messageId)); } else { if ($messageType != 'json') { $this->Db->Execute("UPDATE messages SET status = ?, message = '' WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId)); } else { $this->Db->Execute("UPDATE messages SET status = ? WHERE messageid = ?", array(MESSAGE_STATUS::HANDLED, $message->messageId)); } if (!empty($message->eventId)) { $this->Db->Execute("UPDATE events SET msg_sent = msg_sent + 1 WHERE event_id = ?", array($message->eventId)); } } } else { $logger->warn(sprintf("[FarmID: %s] Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $this->farmId, $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $request->getResponseStatus())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } if ($this->farmId) { $logger->warn(new FarmLogMessage($this->farmId, sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg), $this->serverId)); } else { $logger->fatal(sprintf("Cannot deliver message '%s' (message_id: %s) via REST" . " to server '%s' (server_id: %s). Error: %s %s", $message->getName(), $message->messageId, $this->remoteIp, $this->serverId, $request->getResponseCode(), $msg)); } return false; } return $message; }
/** * Validates url * * @return boolean Returns true if url endpoint passes validation. * It saves updated properties itself on success * @throws \Scalr\Exception\ScalrException */ public function validateUrl() { if (!$this->isValid && $this->endpointId) { $q = new \HttpRequest($this->url, HTTP_METH_GET); $q->addHeaders(array('X-Scalr-Webhook-Enpoint-Id' => $this->endpointId, 'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Date' => gmdate('r'))); $q->setOptions(array('redirect' => 10, 'useragent' => sprintf('Scalr client (http://scalr.com) PHP/%s pecl_http/%s', phpversion(), phpversion('http')), 'verifypeer' => false, 'verifyhost' => false, 'timeout' => 10, 'connecttimeout' => 10)); try { $message = $q->send(); if ($message->getResponseCode() == 200) { $code = trim($q->getResponseBody()); $h = $message->getHeader('X-Validation-Token'); $this->isValid = $code == $this->validationToken || $h == $this->validationToken; if ($this->isValid) { $this->save(); } } else { throw new ScalrException(sprintf("Validation failed. Endpoint '%s' returned http code %s", strip_tags($this->url), $message->getResponseCode())); } } catch (\HttpException $e) { throw new ScalrException(sprintf("Validation failed. Cannot connect to '%s'.", strip_tags($this->url))); } } return $this->isValid; }
/** * Create new object on S3 Bucket * * @param string $object_path * @param string $bucket_name * @param string $filename * @param string $object_content_type * @param string $object_permissions * @return bool */ public function CreateObject($object_path, $bucket_name, $filename, $object_content_type, $object_permissions = "public-read") { if (!file_exists($filename)) { Core::RaiseWarning("{$filename} - no such file."); return false; } $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array( "redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)" ) ); $timestamp = $this->GetTimestamp(true); $data_to_sign = array("PUT", "", $object_content_type, $timestamp, "x-amz-acl:{$object_permissions}","/{$bucket_name}/{$object_path}"); $signature = $this->GetRESTSignature($data_to_sign); $HttpRequest->setUrl("http://{$bucket_name}.s3.amazonaws.com/{$object_path}"); $HttpRequest->setMethod(constant("HTTP_METH_PUT")); $headers["Content-type"] = $object_content_type; $headers["x-amz-acl"] = $object_permissions; $headers["Date"] = $timestamp; $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}"; $HttpRequest->addHeaders($headers); $HttpRequest->setPutFile($filename); try { $HttpRequest->send(); $info = $HttpRequest->getResponseInfo(); if ($info['response_code'] == 200) return true; else { $xml = @simplexml_load_string($HttpRequest->getResponseBody()); return $xml->Message; } } catch (HttpException $e) { Core::RaiseWarning($e->__toString(), E_ERROR); return false; } }
<?php $r = new HttpRequest('http://www.google.com/search'); // store Googles cookies in a dedicated file touch('google.txt'); $r->setOptions(array('cookiestore' => 'google.txt')); $r->setQueryData(array('q' => '+"pecl_http" -msg -cvs -list', 'hl' => 'de')); // HttpRequest::send() returns an HttpMessage object // of type HttpMessage::RESPONSE or throws an exception try { print $r->send()->getBody(); } catch (HttpException $e) { print $e; }
/** * Creates a new HttpRequest object. * * @return \HttpRequest Returns a new HttpRequest object. */ public function createRequest() { $q = new \HttpRequest(); //HttpRequest has a pitfall which persists cookies between different requests. //IMPORTANT! This line causes error with old version of curl //$q->resetCookies(); $q->setOptions(array('redirect' => 10, 'useragent' => $this->useragent, 'verifypeer' => false, 'verifyhost' => false, 'timeout' => 30, 'connecttimeout' => 30)); $proxySettings = $this->getAws()->getProxy(); if ($proxySettings !== false) { $q->setOptions(array('proxyhost' => $proxySettings['host'], 'proxyport' => $proxySettings['port'], 'proxytype' => $proxySettings['type'])); if ($proxySettings['user']) { $q->setOptions(array('proxyauth' => "{$proxySettings['user']}:{$proxySettings['pass']}", 'proxyauthtype' => HTTP_AUTH_BASIC)); } } return $q; }
/** * Remove the specified resource * @return [type] [description] */ function destroy($id) { $where = "id = '{$id}'"; if ($this->model->delete($where)) { $r = new HttpRequest(URL . ':' . USER_CLASS_MICS_PORT . 'delete', HttpRequest::METH_POST); $r->setOptions(array('cookies' => array('lang' => 'en'))); $r->addPostFields(array('data' => '{"class_id":' . $id . '}')); try { echo $r->send()->getBody(); } catch (HttpException $ex) { echo $ex; } } }
/** * * adapt Request to HttpRequest * * {@link http://us.php.net/manual/en/http.constants.php * HTTP Predefined Constant} * * {@link http://us.php.net/manual/en/http.request.options.php * HttpRequest options} * * @throws InvalidArgumentException * @param Request $request * @param Endpoint $endpoint * @param HttpRequest * @return \HttpRequest */ public function toHttpRequest($request, $endpoint) { $url = $endpoint->getBaseUri() . $request->getUri(); $httpRequest = new \HttpRequest($url); $headers = array(); foreach ($request->getHeaders() as $headerLine) { list($header, $value) = explode(':', $headerLine); if ($header = trim($header)) { $headers[$header] = trim($value); } } // Try endpoint authentication first, fallback to request for backwards compatibility $authData = $endpoint->getAuthentication(); if (empty($authData['username'])) { $authData = $request->getAuthentication(); } if (!empty($authData['username']) && !empty($authData['password'])) { $headers['Authorization'] = 'Basic ' . base64_encode($authData['username'] . ':' . $authData['password']); } switch ($request->getMethod()) { case Request::METHOD_GET: $method = HTTP_METH_GET; break; case Request::METHOD_POST: $method = HTTP_METH_POST; if ($request->getFileUpload()) { $httpRequest->addPostFile('content', $request->getFileUpload(), 'application/octet-stream; charset=binary'); } else { $httpRequest->setBody($request->getRawData()); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/xml; charset=utf-8'; } } break; case Request::METHOD_HEAD: $method = HTTP_METH_HEAD; break; default: throw new InvalidArgumentException('Unsupported method: ' . $request->getMethod()); } $httpRequest->setMethod($method); $httpRequest->setOptions(array('timeout' => $endpoint->getTimeout(), 'connecttimeout' => $endpoint->getTimeout(), 'dns_cache_timeout' => $endpoint->getTimeout())); $httpRequest->setHeaders($headers); return $httpRequest; }
public function request($method, stdClass $params = null, $namespace = null) { if (!$namespace) { $namespace = $this->namespace; } $requestObj = new stdClass(); $requestObj->id = microtime(true); $requestObj->method = $method; $requestObj->params = new stdClass(); $this->walkSerialize($params, $requestObj->params, 'underScope'); $jsonRequest = $this->cryptoTool->encrypt(json_encode($requestObj), $this->dbServer->GetKey(true)); $dt = new DateTime('now', new DateTimeZone("UTC")); $timestamp = $dt->format("D d M Y H:i:s e"); $canonical_string = $jsonRequest . $timestamp; $signature = base64_encode(hash_hmac('SHA1', $canonical_string, $this->dbServer->GetKey(true), 1)); $request = new HttpRequest(); $request->setMethod(HTTP_METH_POST); // If no VPC router communicating via local inteface (Scalr should be setup within the esame network) $requestHost = $this->dbServer->getSzrHost() . ":{$this->port}"; if ($this->isVPC) { $routerFarmRoleId = $this->dbServer->GetFarmRoleObject()->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_SCALR_ROUTER_ID); if ($routerFarmRoleId) { $routerRole = DBFarmRole::LoadByID($routerFarmRoleId); } else { $routerRole = $this->dbServer->GetFarmObject()->GetFarmRoleByBehavior(ROLE_BEHAVIORS::VPC_ROUTER); } if ($routerRole) { // No public IP need to use proxy if (!$this->dbServer->remoteIp) { $requestHost = $routerRole->GetSetting(Scalr_Role_Behavior_Router::ROLE_VPC_IP) . ":80"; $request->addHeaders(array("X-Receiver-Host" => $this->dbServer->localIp, "X-Receiver-Port" => $this->port)); // There is public IP, can use it } else { $requestHost = "{$this->dbServer->remoteIp}:{$this->port}"; } } } $request->setUrl("http://{$requestHost}/{$namespace}"); $request->setOptions(array('timeout' => $this->timeout, 'connecttimeout' => 10)); $request->addHeaders(array("Date" => $timestamp, "X-Signature" => $signature, "X-Server-Id" => $this->dbServer->serverId)); $request->setBody($jsonRequest); try { // Send request $request->send(); $this->debug['responseCode'] = $request->getResponseCode(); $this->debug['fullResponse'] = $request->getRawResponseMessage(); if ($request->getResponseCode() == 200) { $response = $request->getResponseData(); $body = $this->cryptoTool->decrypt($response['body'], $this->dbServer->GetKey(true)); $jResponse = @json_decode($body); if ($jResponse->error) { throw new Exception("{$jResponse->error->message} ({$jResponse->error->code}): {$jResponse->error->data}"); } return $jResponse; } else { $response = $request->getResponseData(); throw new Exception(sprintf("Unable to perform request to scalarizr: %s (%s)", $response['body'], $request->getResponseCode())); } } catch (HttpException $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } if (stristr($msg, "Namespace not found")) { $msg = "Feature not supported by installed version of scalarizr. Please update it to the latest version and try again."; } throw new Exception(sprintf("Unable to perform request to scalarizr: %s", $msg)); } }
private function request($path, $method, $data = "") { $data = trim($data); $httpRequest = new HttpRequest(); $httpRequest->setOptions(array("useragent" => "Scalr (http://scalr.com)")); $fullUrl = "{$this->chefServerUrl}{$path}"; $chunks = parse_url($fullUrl); if ($method == 'POST' && $data) { if (is_array($data)) { $httpRequest->setPostFields($data); } else { $httpRequest->setBody($data); } } if ($method == 'PUT' && $data) { $httpRequest->setPutData($data); } $httpRequest->setUrl($fullUrl); $httpRequest->setMethod(constant("HTTP_METH_{$method}")); $tz = @date_default_timezone_get(); date_default_timezone_set("UTC"); $timestamp = date("Y-m-d\\TH:i:s\\Z"); date_default_timezone_set($tz); $chunks['path'] = str_replace('//', '/', $chunks['path']); $hashedPath = base64_encode(sha1($chunks['path'], true)); $hashedBody = base64_encode(sha1($data, true)); $userId = $this->username; $str = "Method:{$method}\n" . "Hashed Path:{$hashedPath}\n" . "X-Ops-Content-Hash:{$hashedBody}\n" . "X-Ops-Timestamp:{$timestamp}\n" . "X-Ops-UserId:{$userId}"; $headers = array('x-ops-sign' => "algorithm=sha1;version=1.0", 'x-chef-version' => "0.10.8", 'x-ops-userid' => $userId, 'x-ops-timestamp' => $timestamp, 'x-ops-content-hash' => $hashedBody, 'content-type' => 'application/json', 'accept' => 'application/json'); $r = array_merge($headers, $this->sign($str)); $httpRequest->addHeaders($r); $httpRequest->send(); if ($httpRequest->getResponseCode() == 401) { throw new Exception("Failed to authenticate as {$userId}. Ensure that your node_name and client key are correct."); } if ($httpRequest->getResponseCode() == 404) { throw new Exception("Client not found or parameters are not valid"); } else { if ($httpRequest->getResponseCode() <= 205) { $data = $httpRequest->getResponseData(); $retval = $data['body'] ? json_decode($data['body']) : true; } else { if ($httpRequest->getResponseCode() > 400) { $data = $httpRequest->getResponseData(); $msg = $data['body'] ? json_decode($data['body']) : ""; if (is_array($msg->error)) { $msg = $msg->error[0]; } elseif ($msg->error) { $msg = $msg->error; } else { $msg = "Unknown error. Error code: {$httpRequest->getResponseCode()}"; } throw new Exception("Request to chef server failed with error: {$msg} ({$method} {$path})"); } else { throw new Exception("Unexpected situation. Response code {$httpRequest->getResponseCode()}"); } } } return $retval; }
<?php $r = new HttpRequest('http://dev.iworks.at/.print_request.php', HTTP_METH_POST); // if redirects is set to true, a single redirect is allowed; // one can set any reasonable count of allowed redirects $r->setOptions(array('cookies' => array('MyCookie' => 'has a value'), 'redirect' => true)); // common form data $r->setPostFields(array('name' => 'Mike', 'mail' => '*****@*****.**')); // add the file to post (form name, file name, file type) $r->addPostFile('image', 'profile.jpg', 'image/jpeg'); try { print $r->send()->getBody(); } catch (HttpException $e) { print $e; }
/** * The CreateBucket operation creates a bucket. Not every string is an acceptable bucket name. * * @param string $bucket_name * @return string */ public function CreateBucket($bucket_name, $region = 'us-east-1') { $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array("redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)")); $timestamp = $this->GetTimestamp(true); switch ($region) { case "us-east-1": $request = ""; break; case "us-west-1": $request = "<CreateBucketConfiguration><LocationConstraint>us-west-1</LocationConstraint></CreateBucketConfiguration>"; break; case "eu-west-1": $request = "<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>"; break; } $data_to_sign = array("PUT", "", "", $timestamp, "/{$bucket_name}/"); $signature = $this->GetRESTSignature($data_to_sign); $HttpRequest->setUrl("https://{$bucket_name}.s3.amazonaws.com/"); $HttpRequest->setMethod(constant("HTTP_METH_PUT")); $headers = array("Content-length" => strlen($request), "Date" => $timestamp, "Authorization" => "AWS {$this->AWSAccessKeyId}:{$signature}"); $HttpRequest->addHeaders($headers); if ($request != '') { $HttpRequest->setPutData($request); } try { $HttpRequest->send(); $info = $HttpRequest->getResponseInfo(); if ($info['response_code'] == 200) { return true; } else { if ($HttpRequest->getResponseBody()) { $xml = @simplexml_load_string($HttpRequest->getResponseBody()); throw new Exception((string) $xml->Message); } else { throw new Exception(_("Cannot create S3 bucket at this time. Please try again later.")); } } } catch (HttpException $e) { throw new Exception($e->__toString()); } }
/** * * adapt Solarium_Client_Request to HttpRequest * * {@link http://us.php.net/manual/en/http.constants.php * HTTP Predefined Constant} * * @param Solarium_Client_Request $request * @param HttpRequest */ public function toHttpRequest($request) { $url = $this->getBaseUri() . $request->getUri(); $httpRequest = new HttpRequest($url); $headers = array(); foreach ($request->getHeaders() as $headerLine) { list($header, $value) = explode(':', $headerLine); if ($header = trim($header)) { $headers[$header] = trim($value); } } switch ($request->getMethod()) { case Solarium_Client_Request::METHOD_GET: $method = HTTP_METH_GET; break; case Solarium_Client_Request::METHOD_POST: $method = HTTP_METH_POST; $httpRequest->setBody($request->getRawData()); if (!isset($headers['Content-Type'])) { $headers['Content-Type'] = 'text/xml; charset=utf-8'; } break; case Solarium_Client_Request::METHOD_HEAD: $method = HTTP_METH_HEAD; break; default: throw new Solarium_Exception('Unsupported method: ' . $request->getMethod()); } $httpRequest->setMethod($method); $httpRequest->setOptions(array('timeout' => $this->getTimeout())); $httpRequest->setHeaders($headers); return $httpRequest; }
protected function sendRequest($uri, $method, $data = null) { try { $request = new HttpRequest("https://{$this->domain}.chargify.com{$uri}"); $request->setHeaders(array('Content-Type' => 'application/json', 'Authorization' => 'Basic ' . base64_encode("{$this->apiKey}:x"))); $request->setOptions(array('httpauth' => "{$this->apiKey}:x", 'timeout' => 45, 'connecttimeout' => 45, 'ssl' => array('version' => 1))); $request->setMethod(constant("HTTP_METH_{$method}")); if ($method == 'POST' && $data) { $request->setBody($data); } if ($method == 'PUT') { $request->addPutData($data); } } catch (Exception $e) { //TODO: throw $e; } $request->send(); if ($request->getResponseCode() == 500) { throw new Exception("Unable to proceed your request at the moment. Please try again later."); } if ($request->getResponseCode() == 404) { throw new Exception("Unable to proceed your request. Please contact billing@scalr.net to get help."); } return $request; }
public function statusAction() { $moduleParams['rabbitmq']['status'] = ''; $moduleParams['rabbitmq']['showSetup'] = false; $moduleParams['rabbitmq']['showStatusLabel'] = true; $dbFarmRole = $this->getFarmRole(); if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_URL)) { $serverId = $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_SERVER_ID); try { $dbServer = DBServer::LoadByID($serverId); if ($dbServer->status == SERVER_STATUS::RUNNING) { $moduleParams['rabbitmq']['username'] = '******'; $moduleParams['rabbitmq']['password'] = $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD); $moduleParams['rabbitmq']['url'] = "http://{$dbServer->remoteIp}:55672/mgmt/"; $url = str_replace('/mgmt/', '/api/overview', $moduleParams['rabbitmq']['url']); $httpRequest = new HttpRequest(); $httpRequest->setUrl($url); $httpRequest->setOptions(array('redirect' => 5, 'timeout' => 30, 'connecttimeout' => 10)); $httpRequest->setHeaders(array('Authorization' => 'Basic ' . base64_encode($moduleParams['rabbitmq']['username'] . ':' . $moduleParams['rabbitmq']['password']))); $httpRequest->send(); $data = $httpRequest->getResponseData(); $result = json_decode($data['body'], true); if ($result) { $moduleParams['rabbitmq']['overview'] = $result; } } else { throw new \Scalr\Exception\ServerNotFoundException(); } } catch (\Scalr\Exception\ServerNotFoundException $e) { $moduleParams['rabbitmq']['status'] = 'Control panel was installed, but server not found'; $moduleParams['rabbitmq']['showSetup'] = true; $dbFarmRole->ClearSettings('rabbitmq.cp'); } catch (Exception $e) { if (isset($e->innerException)) { $msg = $e->innerException->getMessage(); } else { $msg = $e->getMessage(); } $moduleParams['rabbitmq']['status'] = "Error retrieving information about control panel: \"{$msg}\""; } } else { if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUESTED) == '1') { if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_ERROR_MSG)) { $moduleParams['rabbitmq']['showSetup'] = true; $moduleParams['rabbitmq']['status'] = "Server return error: \"{$dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_ERROR_MSG)}\""; } else { if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME) > time() - self::REQUEST_TIMEOUT) { $moduleParams['rabbitmq']['status'] = "Request was sent at " . Scalr_Util_DateTime::convertTz((int) $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME)) . ". Please wait..."; } else { $moduleParams['rabbitmq']['showSetup'] = true; $moduleParams['rabbitmq']['status'] = "Request timeout exceeded. Request was sent at " . Scalr_Util_DateTime::convertTz((int) $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_CP_REQUEST_TIME)); } } } else { if ($dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD)) { $moduleParams['rabbitmq']['showSetup'] = true; } else { $moduleParams['rabbitmq']['status'] = 'Rabbitmq cluster not initialized yet. Please wait ...'; $moduleParams['rabbitmq']['showStatusLabel'] = false; } } } $moduleParams['farmId'] = $dbFarmRole->FarmID; $moduleParams['rabbitmq']['password'] = $dbFarmRole->GetSetting(Scalr_Role_Behavior_RabbitMQ::ROLE_PASSWORD); $this->response->page('ui/services/rabbitmq/status.js', $moduleParams); }
/** * Send a synchronous request to the server. * This function manages timeout then will not block if one of the server is down * * @param url The url to get * @param response_code The response code * * @return The body of the response or "" in case of error * @access private */ function Swekey_HttpGet($url, &$response_code) { global $gSwekeyLastError; $gSwekeyLastError = 0; global $gSwekeyLastResult; $gSwekeyLastResult = "<not set>"; // use curl if available if (function_exists('curl_init')) { $sess = curl_init($url); if (substr($url, 0, 8) == "https://") { global $gSwekeyCA; if (!empty($gSwekeyCA)) { if (file_exists($gSwekeyCA)) { if (!curl_setopt($sess, CURLOPT_CAINFO, $gSwekeyCA)) { error_log("SWEKEY_ERROR:Could not set CA file : " . curl_error($sess)); } else { $caFileOk = true; } } else { error_log("SWEKEY_ERROR:Could not find CA file {$gSwekeyCA} getting {$url}"); } } curl_setopt($sess, CURLOPT_SSL_VERIFYHOST, '2'); curl_setopt($sess, CURLOPT_SSL_VERIFYPEER, '2'); curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '20'); curl_setopt($sess, CURLOPT_TIMEOUT, '20'); } else { curl_setopt($sess, CURLOPT_CONNECTTIMEOUT, '3'); curl_setopt($sess, CURLOPT_TIMEOUT, '5'); } curl_setopt($sess, CURLOPT_RETURNTRANSFER, '1'); $res = curl_exec($sess); $response_code = curl_getinfo($sess, CURLINFO_HTTP_CODE); $curlerr = curl_error($sess); curl_close($sess); if ($response_code == 200) { $gSwekeyLastResult = $res; return $res; } if (!empty($response_code)) { $gSwekeyLastError = $response_code; error_log("SWEKEY_ERROR:Error {$gSwekeyLastError} ({$curlerr}) getting {$url}"); return ""; } $response_code = 408; // Request Timeout $gSwekeyLastError = $response_code; error_log("SWEKEY_ERROR:Error {$curlerr} getting {$url}"); return ""; } // use pecl_http if available if (class_exists('HttpRequest')) { // retry if one of the server is down for ($num = 1; $num <= 3; $num++) { $r = new HttpRequest($url); $options = array('timeout' => '3'); if (substr($url, 0, 6) == "https:") { $sslOptions = array(); $sslOptions['verifypeer'] = true; $sslOptions['verifyhost'] = true; $capath = __FILE__; $name = strrchr($capath, '/'); // windows if (empty($name)) { $name = strrchr($capath, '\\'); } $capath = substr($capath, 0, strlen($capath) - strlen($name) + 1) . 'musbe-ca.crt'; if (!empty($gSwekeyCA)) { $sslOptions['cainfo'] = $gSwekeyCA; } $options['ssl'] = $sslOptions; } $r->setOptions($options); $reply = $r->send(); $res = $reply->getBody(); $info = $r->getResponseInfo(); $response_code = $info['response_code']; if ($response_code != 200) { $gSwekeyLastError = $response_code; error_log("SWEKEY_ERROR:Error " . $gSwekeyLastError . " getting " . $url); return ""; } $gSwekeyLastResult = $res; return $res; // catch (HttpException $e) // { // error_log("SWEKEY_WARNING:HttpException ".$e." getting ".$url); // } } $response_code = 408; // Request Timeout $gSwekeyLastError = $response_code; error_log("SWEKEY_ERROR:Error " . $gSwekeyLastError . " getting " . $url); return ""; } global $http_response_header; $res = @file_get_contents($url); $response_code = substr($http_response_header[0], 9, 3); //HTTP/1.0 if ($response_code == 200) { $gSwekeyLastResult = $res; return $res; } $gSwekeyLastError = $response_code; error_log("SWEKEY_ERROR:Error " . $response_code . " getting " . $url); return ""; }
public function request($command, $args = array(), $responseCmd = null) { if (empty($command)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(NO_COMMAND_MSG, NO_COMMAND); } if (!is_array($args)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(sprintf(WRONG_REQUEST_ARGS_MSG, $args), WRONG_REQUEST_ARGS); } foreach ($args as $key => $value) { if ($value == "") { unset($args[$key]); } // Workaround for zones. Doesn't work in uCLoud becuase listZones not supported if ($key == 'zoneid' && $value != '' && $this->platformName != 'ucloud') { if (!$this->zonesCache) { foreach ($this->listZones() as $zone) { $this->zonesCache[$zone->name] = $zone->id; } } if ($this->zonesCache[$value]) { $args[$key] = $this->zonesCache[$value]; } else { throw new Scalr_Service_Cloud_Cloudstack_Exception("Availability zone '{$value}' no longer supported"); } } } // Building the query $args['apikey'] = $this->apiKey; $args['command'] = $command; $args['response'] = "json"; ksort($args); $query = http_build_query($args); $query = str_replace("+", "%20", $query); $query .= "&signature=" . $this->getSignature(strtolower($query)); // var_dump($query); $httpRequest = new HttpRequest(); $httpRequest->setMethod(HTTP_METH_GET); $url = $this->endpoint . "?" . $query; $httpRequest->setOptions(array("redirect" => 2, "useragent" => "Scalr", 'timeout' => 10, 'connecttimeout' => 10)); $httpRequest->setUrl($url); $httpRequest->send(); $code = $httpRequest->getResponseCode(); $data = $httpRequest->getResponseData(); if (empty($data)) { throw new Scalr_Service_Cloud_Cloudstack_Exception(NO_DATA_RECEIVED_MSG, NO_DATA_RECEIVED); } //echo $data['body'] . "\n"; $result = @json_decode($data['body']); if (empty($result)) { throw new Scalr_Service_Cloud_Cloudstack_Exception("The server did not issue a json response ({$code}): {$data['body']}", NO_VALID_JSON_RECEIVED); } if (!$responseCmd) { $responseCmd = strtolower($command); } $propertyResponse = "{$responseCmd}response"; if (!property_exists($result, $propertyResponse)) { if (property_exists($result, "errorresponse") && property_exists($result->errorresponse, "errortext")) { throw new Scalr_Service_Cloud_Cloudstack_Exception($result->errorresponse->errortext); } else { throw new Scalr_Service_Cloud_Cloudstack_Exception(sprintf("Unable to parse the response ({$command}). Got code %d and message: %s", $code, $data['body'])); } } $response = $result->{$propertyResponse}; if ($code > 400) { /* * Request to cloudstack failed. general error (503) ( * apikey=very-secret-key& * command=deployVirtualMachine& * group=base-ubuntu1004-devel& * response=json& * serviceofferingid=85& * templateid=1670& * userdata=ZmFybWlkPTc2NDQ7cm9sZT1iYXNlLGNoZWY7ZXZlbnRoYW5kbGVydXJsPW15LnNjYWxyLm5ldDtoYXNoPTRjNGNmY2MxZWQ1NjlhO3JlYWxyb2xlbmFtZT1iYXNlLXVidW50dTEwMDQtZGV2ZWw7aHR0cHByb3RvPWh0dHBzO3JlZ2lvbj0yO3N6cl9rZXk9cDM2b2pXRGt0KytvK1RjSm1adXY0cmJMQWV3RUlPQ1hVM1lVWEtoMUFGdGtER1ZWYzVDV0lRPT07c2VydmVyaWQ9ZDM2YTBjOWUtZDJhMS00NTg0LTlkNjctN2E4YmE1NDMwMTM5O3AycF9wcm9kdWNlcl9lbmRwb2ludD1odHRwczovL215LnNjYWxyLm5ldC9tZXNzYWdpbmc7cXVlcnllbnZfdXJsPWh0dHBzOi8vbXkuc2NhbHIubmV0L3F1ZXJ5LWVudjtiZWhhdmlvcnM9YmFzZSxjaGVmO2Zhcm1fcm9sZWlkPTM2NzIzO3JvbGVpZD0zNjM3MTtlbnZfaWQ9MzQxNDtvd25lcl9lbWFpbD0%3D& * zoneid=2& * signature=PV02IqoAjmPlkAwd9TYCuAG4kp4%3D * ) */ throw new Exception("Request to cloudstack failed. {$response->errortext} ({$response->errorcode}) ({$query})"); } // list handling : most of lists are on the same pattern as listVirtualMachines : // { "listvirtualmachinesresponse" : { "virtualmachine" : [ ... ] } } preg_match('/list(\\w+)s/', strtolower($command), $listMatches); if (!empty($listMatches)) { $objectName = $listMatches[1]; if (property_exists($response, $objectName)) { $resultArray = $response->{$objectName}; if (is_array($resultArray)) { return $resultArray; } } else { // sometimes, the 's' is kept, as in : // { "listasyncjobsresponse" : { "asyncjobs" : [ ... ] } } $objectName = $listMatches[1] . "s"; if (property_exists($response, $objectName)) { $resultArray = $response->{$objectName}; if (is_array($resultArray)) { return $resultArray; } } } } return $response; }