Microsoft_SqlAzure
[ class tree: Microsoft_SqlAzure ] [ index: Microsoft_SqlAzure ] [ all elements ]

Source for file Client.php

Documentation is available at Client.php

  1. <?php
  2. /**
  3.  * Copyright (c) 2009 - 2011, RealDolmen
  4.  * All rights reserved.
  5.  *
  6.  * Redistribution and use in source and binary forms, with or without
  7.  * modification, are permitted provided that the following conditions are met:
  8.  *     * Redistributions of source code must retain the above copyright
  9.  *       notice, this list of conditions and the following disclaimer.
  10.  *     * Redistributions in binary form must reproduce the above copyright
  11.  *       notice, this list of conditions and the following disclaimer in the
  12.  *       documentation and/or other materials provided with the distribution.
  13.  *     * Neither the name of RealDolmen nor the
  14.  *       names of its contributors may be used to endorse or promote products
  15.  *       derived from this software without specific prior written permission.
  16.  *
  17.  * THIS SOFTWARE IS PROVIDED BY RealDolmen ''AS IS'' AND ANY
  18.  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20.  * DISCLAIMED. IN NO EVENT SHALL RealDolmen BE LIABLE FOR ANY
  21.  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22.  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24.  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27.  *
  28.  * @category   Microsoft
  29.  * @package    Microsoft_WindowsAzure
  30.  * @subpackage Management
  31.  * @copyright  Copyright (c) 2009 - 2011, RealDolmen (http://www.realdolmen.com)
  32.  * @license    http://phpazure.codeplex.com/license
  33.  * @version    $Id: Storage.php 51671 2010-09-30 08:33:45Z unknown $
  34.  */
  35.  
  36. /**
  37.  * @see Microsoft_AutoLoader
  38.  */
  39. require_once dirname(__FILE__'/../../AutoLoader.php';
  40.  
  41. /**
  42.  * @category   Microsoft
  43.  * @package    Microsoft_SqlAzure
  44.  * @subpackage Management
  45.  * @copyright  Copyright (c) 2009 - 2011, RealDolmen (http://www.realdolmen.com)
  46.  * @license    http://phpazure.codeplex.com/license
  47.  */
  48. {
  49.     /**
  50.      * Management service URL
  51.      */
  52.     const URL_MANAGEMENT        "https://management.database.windows.net:8443";
  53.     
  54.     /**
  55.      * Operations
  56.      */
  57.     const OP_OPERATIONS                "operations";
  58.     const OP_SERVERS                   "servers";
  59.     const OP_FIREWALLRULES             "firewallrules";
  60.  
  61.     /**
  62.      * Current API version
  63.      * 
  64.      * @var string 
  65.      */
  66.     protected $_apiVersion = '1.0';
  67.     
  68.     /**
  69.      * Subscription ID
  70.      *
  71.      * @var string 
  72.      */
  73.     protected $_subscriptionId = '';
  74.     
  75.     /**
  76.      * Management certificate path (.PEM)
  77.      *
  78.      * @var string 
  79.      */
  80.     protected $_certificatePath = '';
  81.     
  82.     /**
  83.      * Management certificate passphrase
  84.      *
  85.      * @var string 
  86.      */
  87.     protected $_certificatePassphrase = '';
  88.     
  89.     /**
  90.      * Microsoft_Http_Client channel used for communication with REST services
  91.      * 
  92.      * @var Microsoft_Http_Client 
  93.      */
  94.     protected $_httpClientChannel = null;    
  95.  
  96.     /**
  97.      * Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract instance
  98.      * 
  99.      * @var Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract 
  100.      */
  101.     protected $_retryPolicy = null;
  102.     
  103.     /**
  104.      * Returns the last request ID
  105.      * 
  106.      * @var string 
  107.      */
  108.     protected $_lastRequestId = null;
  109.     
  110.     /**
  111.      * Creates a new Microsoft_SqlAzure_Management_Client instance
  112.      * 
  113.      * @param string $subscriptionId Subscription ID
  114.      * @param string $certificatePath Management certificate path (.PEM)
  115.      * @param string $certificatePassphrase Management certificate passphrase
  116.      * @param Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
  117.      */
  118.     public function __construct(
  119.         $subscriptionId,
  120.         $certificatePath,
  121.         $certificatePassphrase,
  122.         Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy null
  123.     {
  124.         $this->_subscriptionId = $subscriptionId;
  125.         $this->_certificatePath = $certificatePath;
  126.         $this->_certificatePassphrase = $certificatePassphrase;
  127.         
  128.         $this->_retryPolicy = $retryPolicy;
  129.         if (is_null($this->_retryPolicy)) {
  130.         }
  131.         
  132.         // Setup default Microsoft_Http_Client channel
  133.         $options array(
  134.             'adapter'       => 'Microsoft_Http_Client_Adapter_Socket',
  135.             'ssltransport'  => 'ssl',
  136.             'sslcert'       => $this->_certificatePath,
  137.             'sslpassphrase' => $this->_certificatePassphrase,
  138.             'sslusecontext' => true,
  139.         );
  140.         if (function_exists('curl_init')) {
  141.             // Set cURL options if cURL is used afterwards
  142.             $options['curloptions'array(
  143.                     CURLOPT_FOLLOWLOCATION => true,
  144.                     CURLOPT_TIMEOUT => 120,
  145.             );
  146.         }
  147.         $this->_httpClientChannel = new Microsoft_Http_Client(null$options);
  148.     }
  149.     
  150.     /**
  151.      * Set the HTTP client channel to use
  152.      * 
  153.      * @param Microsoft_Http_Client_Adapter_Interface|string$adapterInstance Adapter instance or adapter class name.
  154.      */
  155.     public function setHttpClientChannel($adapterInstance 'Microsoft_Http_Client_Adapter_Socket')
  156.     {
  157.         $this->_httpClientChannel->setAdapter($adapterInstance);
  158.     }
  159.     
  160.     /**
  161.      * Retrieve HTTP client channel
  162.      * 
  163.      * @return Microsoft_Http_Client_Adapter_Interface 
  164.      */
  165.     public function getHttpClientChannel()
  166.     {
  167.         return $this->_httpClientChannel;
  168.     }
  169.     
  170.     /**
  171.      * Returns the Windows Azure subscription ID
  172.      * 
  173.      * @return string 
  174.      */
  175.     public function getSubscriptionId()
  176.     {
  177.         return $this->_subscriptionId;
  178.     }
  179.     
  180.     /**
  181.      * Returns the last request ID.
  182.      * 
  183.      * @return string 
  184.      */
  185.     public function getLastRequestId()
  186.     {
  187.         return $this->_lastRequestId;
  188.     }
  189.     
  190.     /**
  191.      * Get base URL for creating requests
  192.      *
  193.      * @return string 
  194.      */
  195.     public function getBaseUrl()
  196.     {
  197.         return self::URL_MANAGEMENT '/' $this->_subscriptionId;
  198.     }
  199.     
  200.     /**
  201.      * Perform request using Microsoft_Http_Client channel
  202.      *
  203.      * @param string $path Path
  204.      * @param array $query Query parameters
  205.      * @param string $httpVerb HTTP verb the request will use
  206.      * @param array $headers x-ms headers to add
  207.      * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
  208.      * @return Microsoft_Http_Response 
  209.      */
  210.     protected function _performRequest(
  211.         $path '/',
  212.         $query array(),
  213.         $httpVerb Microsoft_Http_Client::GET,
  214.         $headers array(),
  215.         $rawData null
  216.     {
  217.         // Clean path
  218.         if (strpos($path'/'!== 0{
  219.             $path '/' $path;
  220.         }
  221.             
  222.         // Clean headers
  223.         if (is_null($headers)) {
  224.             $headers array();
  225.         }
  226.         
  227.         // Ensure cUrl will also work correctly:
  228.         //  - disable Content-Type if required
  229.         //  - disable Expect: 100 Continue
  230.         if (!isset($headers["Content-Type"])) {
  231.             $headers["Content-Type"'';
  232.         }
  233.         //$headers["Expect"] = '';
  234.  
  235.         // Add version header
  236.         $headers['x-ms-version'$this->_apiVersion;
  237.  
  238.         // Generate URL and sign request
  239.         $requestUrl $this->getBaseUrl(rawurlencode($path);
  240.         $requestHeaders $headers;
  241.         if (count($query0{
  242.             $queryString '';
  243.             foreach ($query as $key => $value{
  244.                 $queryString .= ($queryString '&' '?'rawurlencode($key'=' rawurlencode($value);
  245.             }            
  246.             $requestUrl .= $queryString;
  247.         }
  248.  
  249.         // Prepare request 
  250.         $this->_httpClientChannel->resetParameters(true);
  251.         $this->_httpClientChannel->setUri($requestUrl);
  252.         $this->_httpClientChannel->setHeaders($requestHeaders);
  253.         $this->_httpClientChannel->setRawData($rawData);
  254.  
  255.         // Execute request
  256.         $response $this->_retryPolicy->execute(
  257.             array($this->_httpClientChannel'request'),
  258.             array($httpVerb)
  259.         );
  260.         
  261.         // Store request id
  262.         $this->_lastRequestId = $response->getHeader('x-ms-request-id');
  263.         
  264.         return $response;
  265.     }
  266.     
  267.     /** 
  268.      * Parse result from Microsoft_Http_Response
  269.      *
  270.      * @param Microsoft_Http_Response $response Response from HTTP call
  271.      * @return object 
  272.      * @throws Microsoft_WindowsAzure_Exception
  273.      */
  274.     protected function _parseResponse(Microsoft_Http_Response $response null)
  275.     {
  276.         if (is_null($response)) {
  277.             throw new Microsoft_SqlAzure_Exception('Response should not be null.');
  278.         }
  279.         
  280.         $xml @simplexml_load_string($response->getBody());
  281.         
  282.         if ($xml !== false{
  283.             // Fetch all namespaces 
  284.             $namespaces array_merge($xml->getNamespaces(true)$xml->getDocNamespaces(true))
  285.             
  286.             // Register all namespace prefixes
  287.             foreach ($namespaces as $prefix => $ns
  288.                 if ($prefix != ''{
  289.                     $xml->registerXPathNamespace($prefix$ns);
  290.                 
  291.             
  292.         }
  293.         
  294.         return $xml;
  295.     }
  296.     
  297.     /**
  298.      * Get error message from Microsoft_Http_Response
  299.      *
  300.      * @param Microsoft_Http_Response $response Repsonse
  301.      * @param string $alternativeError Alternative error message
  302.      * @return string 
  303.      */
  304.     protected function _getErrorMessage(Microsoft_Http_Response $response$alternativeError 'Unknown error.')
  305.     {
  306.         $response $this->_parseResponse($response);
  307.         if ($response && $response->Message{
  308.             return (string)$response->Message;
  309.         else {
  310.             return $alternativeError;
  311.         }
  312.     }
  313.     
  314.     /**
  315.      * The Create Server operation adds a new SQL Azure server to a subscription.
  316.      * 
  317.      * @param string $administratorLogin Administrator login.
  318.      * @param string $administratorPassword Administrator password.
  319.      * @param string $location Location of the server.
  320.      * @return Microsoft_SqlAzure_Management_ServerInstance Server information.
  321.      * @throws Microsoft_SqlAzure_Management_Exception
  322.      */
  323.     public function createServer($administratorLogin$administratorPassword$location)
  324.     {
  325.         if ($administratorLogin == '' || is_null($administratorLogin)) {
  326.             throw new Microsoft_SqlAzure_Management_Exception('Administrator login should be specified.');
  327.         }
  328.         if ($administratorPassword == '' || is_null($administratorPassword)) {
  329.             throw new Microsoft_SqlAzure_Management_Exception('Administrator password should be specified.');
  330.         }
  331.         if (is_null($location&& is_null($affinityGroup)) {
  332.             throw new Microsoft_SqlAzure_Management_Exception('Please specify a location for the server.');
  333.         }
  334.         
  335.         $response $this->_performRequest(self::OP_SERVERSarray(),
  336.             Microsoft_Http_Client::POST,
  337.             array('Content-Type' => 'application/xml; charset=utf-8'),
  338.             '<Server xmlns="http://schemas.microsoft.com/sqlazure/2010/12/"><AdministratorLogin>' $administratorLogin '</AdministratorLogin><AdministratorLoginPassword>' $administratorPassword '</AdministratorLoginPassword><Location>' $location '</Location></Server>');
  339.      
  340.         if ($response->isSuccessful()) {
  341.             $xml $this->_parseResponse($response);
  342.             
  343.             return new Microsoft_SqlAzure_Management_ServerInstance(
  344.                 (string)$xml,
  345.                 $administratorLogin,
  346.                 $location
  347.             );
  348.         else {
  349.             throw new Microsoft_SqlAzure_Management_Exception($this->_getErrorMessage($response'Resource could not be accessed.'));
  350.         }    
  351.     }
  352.     
  353.     /**
  354.      * The Get Servers operation enumerates SQL Azure servers that are provisioned for a subscription.
  355.      * 
  356.      * @return array An array of Microsoft_SqlAzure_Management_ServerInstance.
  357.      * @throws Microsoft_SqlAzure_Management_Exception
  358.      */
  359.     public function listServers()
  360.     {
  361.         $response $this->_performRequest(self::OP_SERVERS);
  362.      
  363.         if ($response->isSuccessful()) {
  364.             $xml $this->_parseResponse($response);
  365.             $xmlServices null;
  366.             
  367.             if (!$xml->Server{
  368.                 return array();
  369.             }
  370.             if (count($xml->Server1{
  371.                 $xmlServices $xml->Server;
  372.             else {
  373.                 $xmlServices array($xml->Server);
  374.             }
  375.             
  376.             $services array();
  377.             if (!is_null($xmlServices)) {                
  378.                 for ($i 0$i count($xmlServices)$i++{
  379.                     $services[new Microsoft_SqlAzure_Management_ServerInstance(
  380.                         (string)$xmlServices[$i]->Name,
  381.                         (string)$xmlServices[$i]->AdministratorLogin,
  382.                         (string)$xmlServices[$i]->Location
  383.                     );
  384.                 }
  385.             }
  386.             return $services;
  387.         else {
  388.             throw new Microsoft_SqlAzure_Management_Exception($this->_getErrorMessage($response'Resource could not be accessed.'));
  389.         }
  390.     }
  391.     
  392.     /**
  393.      * The Drop Server operation drops a SQL Azure server from a subscription.
  394.      * 
  395.      * @param string $serverName Server to drop.
  396.      * @throws Microsoft_SqlAzure_Management_Exception
  397.      */
  398.     public function dropServer($serverName)
  399.     {
  400.         if ($serverName == '' || is_null($serverName)) {
  401.             throw new Microsoft_SqlAzure_Management_Exception('Server name should be specified.');
  402.         }
  403.         
  404.         $response $this->_performRequest(self::OP_SERVERS '/' $serverNamearray()Microsoft_Http_Client::DELETE);
  405.  
  406.         if (!$response->isSuccessful()) {
  407.             throw new Microsoft_SqlAzure_Management_Exception($this->_getErrorMessage($response'Resource could not be accessed.'));
  408.         }    
  409.     }
  410.     
  411.     /**
  412.      * The Set Server Administrator Password operation sets the administrative password of a SQL Azure server for a subscription.
  413.      * 
  414.      * @param string $serverName Server to set password for.
  415.      * @param string $administratorPassword Administrator password.
  416.      * @throws Microsoft_SqlAzure_Management_Exception
  417.      */
  418.     public function setAdministratorPassword($serverName$administratorPassword)
  419.     {
  420.         if ($serverName == '' || is_null($serverName)) {
  421.             throw new Microsoft_SqlAzure_Management_Exception('Server name should be specified.');
  422.         }
  423.         if ($administratorPassword == '' || is_null($administratorPassword)) {
  424.             throw new Microsoft_SqlAzure_Management_Exception('Administrator password should be specified.');
  425.         }
  426.         
  427.         $response $this->_performRequest(self::OP_SERVERS '/' $serverNamearray('op' => 'ResetPassword'),
  428.             Microsoft_Http_Client::POST,
  429.             array('Content-Type' => 'application/xml; charset=utf-8'),
  430.             '<AdministratorLoginPassword xmlns="http://schemas.microsoft.com/sqlazure/2010/12/">' $administratorPassword '</AdministratorLoginPassword>');
  431.             
  432.         if (!$response->isSuccessful()) {
  433.             throw new Microsoft_SqlAzure_Management_Exception($this->_getErrorMessage($response'Resource could not be accessed.'));
  434.         }    
  435.     }
  436.     
  437.     /**
  438.      * The Set Server Firewall Rule operation updates an existing firewall rule or adds a new firewall rule for a SQL Azure server that belongs to a subscription.
  439.      * 
  440.      * @param string $serverName Server name.
  441.      * @param string $ruleName Firewall rule name.
  442.      * @param string $startIpAddress Start IP address.
  443.      * @param string $endIpAddress End IP address.
  444.      * @return Microsoft_SqlAzure_Management_FirewallRuleInstance 
  445.      * @throws Microsoft_SqlAzure_Management_Exception
  446.      */
  447.     public function createFirewallRule($serverName$ruleName$startIpAddress$endIpAddress)
  448.     {
  449.         if ($serverName == '' || is_null($serverName)) {
  450.             throw new Microsoft_SqlAzure_Management_Exception('Server name should be specified.');
  451.         }
  452.         if ($ruleName == '' || is_null($ruleName)) {
  453.             throw new Microsoft_SqlAzure_Management_Exception('Rule name should be specified.');
  454.         }
  455.         if ($startIpAddress == '' || is_null($startIpAddress|| !filter_var($startIpAddressFILTER_VALIDATE_IPFILTER_FLAG_IPV4)) {
  456.             throw new Microsoft_SqlAzure_Management_Exception('Start IP address should be specified.');
  457.         }
  458.         if ($endIpAddress == '' || is_null($endIpAddress|| !filter_var($endIpAddressFILTER_VALIDATE_IPFILTER_FLAG_IPV4)) {
  459.             throw new Microsoft_SqlAzure_Management_Exception('End IP address should be specified.');
  460.         }
  461.         
  462.         $response $this->_performRequest(self::OP_SERVERS '/' $serverName '/' self::OP_FIREWALLRULES '/' $ruleNamearray(),
  463.             Microsoft_Http_Client::PUT,
  464.             array('Content-Type' => 'application/xml; charset=utf-8'),
  465.             '<FirewallRule xmlns="http://schemas.microsoft.com/sqlazure/2010/12/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.microsoft.com/sqlazure/2010/12/ FirewallRule.xsd"><StartIpAddress>' $startIpAddress '</StartIpAddress><EndIpAddress>' $endIpAddress '</EndIpAddress></FirewallRule>');
  466.  
  467.         if ($response->isSuccessful()) {
  468.             return new Microsoft_SqlAzure_Management_FirewallRuleInstance(
  469.                 $ruleName,
  470.                 $startIpAddress,
  471.                 $endIpAddress
  472.             );
  473.         else {
  474.             throw new Microsoft_SqlAzure_Management_Exception($this->_getErrorMessage($response'Resource could not be accessed.'));
  475.         }
  476.     }
  477.     
  478.     /**
  479.      * The Get Server Firewall Rules operation retrieves a list of all the firewall rules for a SQL Azure server that belongs to a subscription.
  480.      * 
  481.      * @param string $serverName Server name.
  482.      * @return Array of Microsoft_SqlAzure_Management_FirewallRuleInstance.
  483.      * @throws Microsoft_SqlAzure_Management_Exception
  484.      */
  485.     public function listFirewallRules($serverName)
  486.     {
  487.         if ($serverName == '' || is_null($serverName)) {
  488.             throw new Microsoft_SqlAzure_Management_Exception('Server name should be specified.');
  489.         }
  490.         
  491.         $response $this->_performRequest(self::OP_SERVERS '/' $serverName '/' self::OP_FIREWALLRULES);
  492.      
  493.         if ($response->isSuccessful()) {
  494.             $xml $this->_parseResponse($response);
  495.             $xmlServices null;
  496.             
  497.             if (!$xml->FirewallRule{
  498.                 return array();
  499.             }
  500.             if (count($xml->FirewallRule1{
  501.                 $xmlServices $xml->FirewallRule;
  502.             else {
  503.                 $xmlServices array($xml->FirewallRule);
  504.             }
  505.             
  506.             $services array();
  507.             if (!is_null($xmlServices)) {                
  508.                 for ($i 0$i count($xmlServices)$i++{
  509.                     $services[new Microsoft_SqlAzure_Management_FirewallRuleInstance(
  510.                         (string)$xmlServices[$i]->Name,
  511.                         (string)$xmlServices[$i]->StartIpAddress,
  512.                         (string)$xmlServices[$i]->EndIpAddress
  513.                     );
  514.                 }
  515.             }
  516.             return $services;
  517.         else {
  518.             throw new Microsoft_SqlAzure_Management_Exception($this->_getErrorMessage($response'Resource could not be accessed.'));
  519.         }        
  520.     }
  521.     
  522.     /**
  523.      * The Delete Server Firewall Rule operation deletes a firewall rule from a SQL Azure server that belongs to a subscription.
  524.      * 
  525.      * @param string $serverName Server name.
  526.      * @param string $ruleName Rule name.
  527.      * @throws Microsoft_SqlAzure_Management_Exception
  528.      */
  529.     public function deleteFirewallRule($serverName$ruleName)
  530.     {
  531.         if ($serverName == '' || is_null($serverName)) {
  532.             throw new Microsoft_SqlAzure_Management_Exception('Server name should be specified.');
  533.         }
  534.         if ($ruleName == '' || is_null($ruleName)) {
  535.             throw new Microsoft_SqlAzure_Management_Exception('Rule name should be specified.');
  536.         }
  537.         
  538.         $response $this->_performRequest(self::OP_SERVERS '/' $serverName '/' self::OP_FIREWALLRULES '/' $ruleNamearray(),
  539.             Microsoft_Http_Client::DELETE);
  540.  
  541.         if (!$response->isSuccessful()) {
  542.             throw new Microsoft_SqlAzure_Management_Exception($this->_getErrorMessage($response'Resource could not be accessed.'));
  543.         }
  544.     }
  545.     
  546.     /**
  547.      * Creates a firewall rule for Microsoft Services. This is required if access to SQL Azure is required from other services like Windows Azure.
  548.      * 
  549.      * @param string $serverName Server name.
  550.      * @param boolean $allowAccess Allow access from other Microsoft Services?
  551.      * @throws Microsoft_SqlAzure_Management_Exception
  552.      */
  553.     public function createFirewallRuleForMicrosoftServices($serverName$allowAccess)
  554.     {
  555.         if ($allowAccess{
  556.             $this->createFirewallRule($serverName'MicrosoftServices''0.0.0.0''0.0.0.0');
  557.         else {
  558.             $this->deleteFirewallRule($serverName'MicrosoftServices');
  559.         }
  560.     }
  561.     
  562. }

Documentation generated on Sat, 03 Dec 2011 13:59:12 +0100 by phpDocumentor 1.4.3