Ejemplo n.º 1
0
 protected function request($path, $args = array(), $files = array(), $envId = 0, $version = 'v1')
 {
     try {
         $httpRequest = new HttpRequest();
         $httpRequest->setMethod(HTTP_METH_POST);
         $postData = json_encode($args);
         $stringToSign = "/{$version}{$path}:" . $this->API_ACCESS_KEY . ":{$envId}:{$postData}:" . $this->API_SECRET_KEY;
         $validToken = Scalr_Util_CryptoTool::hash($stringToSign);
         $httpRequest->setHeaders(array("X_SCALR_AUTH_KEY" => $this->API_ACCESS_KEY, "X_SCALR_AUTH_TOKEN" => $validToken, "X_SCALR_ENV_ID" => $envId));
         $httpRequest->setUrl("http://scalr-trunk.localhost/{$version}{$path}");
         $httpRequest->setPostFields(array('rawPostData' => $postData));
         foreach ($files as $name => $file) {
             $httpRequest->addPostFile($name, $file);
         }
         $httpRequest->send();
         if ($this->debug) {
             print "<pre>";
             var_dump($httpRequest->getRequestMessage());
             var_dump($httpRequest->getResponseCode());
             var_dump($httpRequest->getResponseData());
         }
         $data = $httpRequest->getResponseData();
         return @json_decode($data['body']);
     } catch (Exception $e) {
         echo "<pre>";
         if ($this->debug) {
             var_dump($e);
         } else {
             var_dump($e->getMessage());
         }
     }
 }
Ejemplo n.º 2
0
 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);
     }
 }
Ejemplo n.º 3
0
 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}");
     }
 }
Ejemplo n.º 4
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);
     }
 }
Ejemplo n.º 5
0
 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));
     }
 }
Ejemplo n.º 6
0
 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);
     }
 }
Ejemplo n.º 7
0
 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));
     }
 }
Ejemplo n.º 8
0
 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));
     }
 }
Ejemplo n.º 9
0
 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;
 }
Ejemplo n.º 10
0
 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);
 }
Ejemplo n.º 11
0
 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;
 }
Ejemplo n.º 12
0
 public function request($command, $args = array())
 {
     if (empty($command)) {
         throw new CloudStackClientException(NO_COMMAND_MSG, NO_COMMAND);
     }
     if (!is_array($args)) {
         throw new CloudStackClientException(sprintf(WRONG_REQUEST_ARGS_MSG, $args), WRONG_REQUEST_ARGS);
     }
     foreach ($args as $key => $value) {
         if ($value == "") {
             unset($args[$key]);
         }
     }
     // 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));
     $httpRequest = new HttpRequest();
     $httpRequest->setMethod(HTTP_METH_POST);
     $url = $this->endpoint . "?" . $query;
     $httpRequest->setUrl($url);
     $httpRequest->send();
     $code = $httpRequest->getResponseCode();
     $data = $httpRequest->getResponseData();
     if (empty($data)) {
         throw new CloudStackClientException(NO_DATA_RECEIVED_MSG, NO_DATA_RECEIVED);
     }
     //echo $data['body'] . "\n";
     $result = @json_decode($data['body']);
     if (empty($result)) {
         throw new CloudStackClientException(NO_VALID_JSON_RECEIVED_MSG, NO_VALID_JSON_RECEIVED);
     }
     $propertyResponse = strtolower($command) . "response";
     if (!property_exists($result, $propertyResponse)) {
         if (property_exists($result, "errorresponse") && property_exists($result->errorresponse, "errortext")) {
             throw new CloudStackClientException($result->errorresponse->errortext);
         } else {
             throw new CloudStackClientException(sprintf("Unable to parse the response. Got code %d and message: %s", $code, $data['body']));
         }
     }
     $response = $result->{$propertyResponse};
     // 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;
 }
Ejemplo n.º 13
0
 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]);
         }
         if ($key == 'zoneid' && $value != '') {
             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_POST);
     $url = $this->endpoint . "?" . $query;
     $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(NO_VALID_JSON_RECEIVED_MSG, 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. Got code %d and message: %s", $code, $data['body']));
         }
     }
     $response = $result->{$propertyResponse};
     if ($code > 400) {
         throw new Exception("Request to cloudstack failed. {$response->errortext} ({$response->errorcode})");
     }
     // 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;
 }