当前位置: 首页>>代码示例>>PHP>>正文


PHP HttpRequest::setOptions方法代码示例

本文整理汇总了PHP中HttpRequest::setOptions方法的典型用法代码示例。如果您正苦于以下问题:PHP HttpRequest::setOptions方法的具体用法?PHP HttpRequest::setOptions怎么用?PHP HttpRequest::setOptions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在HttpRequest的用法示例。


在下文中一共展示了HttpRequest::setOptions方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: setupRequest

 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;
 }
开发者ID:cheeepsan,项目名称:pear-core,代码行数:10,代码来源:Simple_Feed_Aggregator.php

示例2: call

 /**
  * 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;
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:36,代码来源:Cloudyn.php

示例3: send

 /**
  * 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);
 }
开发者ID:raz0rsdge,项目名称:horde,代码行数:34,代码来源:Peclhttp.php

示例4: request

 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);
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:59,代码来源:Query.php

示例5: OnStartForking

 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();
     }
 }
开发者ID:rickb838,项目名称:scalr,代码行数:55,代码来源:class.DBQueueEventProcess.php

示例6: request

 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}");
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:54,代码来源:Connection.php

示例7: _OssMethods

    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;
    }
开发者ID:RichardPear,项目名称:todo,代码行数:48,代码来源:MfsComponent.php

示例8: Request

 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);
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:46,代码来源:class.AmazonSQS.php

示例9: getValue

 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);
 }
开发者ID:sacredwebsite,项目名称:scalr,代码行数:20,代码来源:Http.php

示例10: Login

        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());
        }
开发者ID:rchicoria,项目名称:epp-drs,代码行数:21,代码来源:class.Flickr.php

示例11: http_get_file

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
}
开发者ID:JamesLinus,项目名称:BLFS,代码行数:21,代码来源:blfs-latest.php

示例12: request

 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));
     }
 }
开发者ID:rakesh-mohanta,项目名称:scalr,代码行数:39,代码来源:UpdateClient.php

示例13: Request

 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);
     }
 }
开发者ID:jasherai,项目名称:libwebta,代码行数:37,代码来源:class.AmazonCloudFront.php

示例14: request

 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));
     }
 }
开发者ID:rickb838,项目名称:scalr,代码行数:75,代码来源:UpdateClient.php

示例15: SendMessage

 /**
  * 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'));
         }
//.........这里部分代码省略.........
开发者ID:sacredwebsite,项目名称:scalr,代码行数:101,代码来源:class.DBServer.php


注:本文中的HttpRequest::setOptions方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。