PageRenderTime 3ms CodeModel.GetById 50ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/Zend/Service/SqlAzure/Management/Client.php

http://grupal.googlecode.com/
PHP | 609 lines | 316 code | 69 blank | 224 comment | 75 complexity | 5d0e541a4802e6c03955c3bb7295335b MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Service_WindowsAzure
 17 * @subpackage Management
 18 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 19 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 20 * @version    $Id$
 21 */
 22
 23/**
 24 * @see Zend_Http_Client
 25 */
 26 require_once 'Zend/Http/Client.php';
 27 
 28 /**
 29 * @see Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract
 30 */
 31 require_once 'Zend/Service/WindowsAzure/RetryPolicy/RetryPolicyAbstract.php';
 32 
 33 /**
 34 * @see Zend_Service_SqlAzure_Management_ServerInstance
 35 */
 36 require_once 'Zend/Service/SqlAzure/Management/ServerInstance.php';
 37 
 38 /**
 39 * @see Zend_Service_SqlAzure_Management_FirewallRuleInstance
 40 */
 41 require_once 'Zend/Service/SqlAzure/Management/FirewallRuleInstance.php';
 42 
 43/**
 44 * @category   Zend
 45 * @package    Zend_Service_SqlAzure
 46 * @subpackage Management
 47 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 48 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 49 */
 50class Zend_Service_SqlAzure_Management_Client
 51{
 52	/**
 53	 * Management service URL
 54	 */
 55	const URL_MANAGEMENT        = "https://management.database.windows.net:8443";
 56	
 57	/**
 58	 * Operations
 59	 */
 60	const OP_OPERATIONS                = "operations";
 61	const OP_SERVERS                   = "servers";
 62	const OP_FIREWALLRULES             = "firewallrules";
 63
 64	/**
 65	 * Current API version
 66	 * 
 67	 * @var string
 68	 */
 69	protected $_apiVersion = '1.0';
 70	
 71	/**
 72	 * Subscription ID
 73	 *
 74	 * @var string
 75	 */
 76	protected $_subscriptionId = '';
 77	
 78	/**
 79	 * Management certificate path (.PEM)
 80	 *
 81	 * @var string
 82	 */
 83	protected $_certificatePath = '';
 84	
 85	/**
 86	 * Management certificate passphrase
 87	 *
 88	 * @var string
 89	 */
 90	protected $_certificatePassphrase = '';
 91	
 92	/**
 93	 * Zend_Http_Client channel used for communication with REST services
 94	 * 
 95	 * @var Zend_Http_Client
 96	 */
 97	protected $_httpClientChannel = null;	
 98
 99	/**
100	 * Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract instance
101	 * 
102	 * @var Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract
103	 */
104	protected $_retryPolicy = null;
105	
106	/**
107	 * Returns the last request ID
108	 * 
109	 * @var string
110	 */
111	protected $_lastRequestId = null;
112	
113	/**
114	 * Creates a new Zend_Service_SqlAzure_Management instance
115	 * 
116	 * @param string $subscriptionId Subscription ID
117	 * @param string $certificatePath Management certificate path (.PEM)
118	 * @param string $certificatePassphrase Management certificate passphrase
119     * @param Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
120	 */
121	public function __construct(
122		$subscriptionId,
123		$certificatePath,
124		$certificatePassphrase,
125		Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null
126	) {
127		$this->_subscriptionId = $subscriptionId;
128		$this->_certificatePath = $certificatePath;
129		$this->_certificatePassphrase = $certificatePassphrase;
130		
131		$this->_retryPolicy = $retryPolicy;
132		if (is_null($this->_retryPolicy)) {
133		    $this->_retryPolicy = Zend_Service_WindowsAzure_RetryPolicy_RetryPolicyAbstract::noRetry();
134		}
135		
136		// Setup default Zend_Http_Client channel
137		$options = array(
138		    'adapter'       => 'Zend_Http_Client_Adapter_Socket',
139		    'ssltransport'  => 'ssl',
140			'sslcert'       => $this->_certificatePath,
141			'sslpassphrase' => $this->_certificatePassphrase,
142			'sslusecontext' => true,
143		);
144		if (function_exists('curl_init')) {
145			// Set cURL options if cURL is used afterwards
146			$options['curloptions'] = array(
147					CURLOPT_FOLLOWLOCATION => true,
148					CURLOPT_TIMEOUT => 120,
149			);
150		}
151		$this->_httpClientChannel = new Zend_Http_Client(null, $options);
152	}
153	
154	/**
155	 * Set the HTTP client channel to use
156	 * 
157	 * @param Zend_Http_Client_Adapter_Interface|string $adapterInstance Adapter instance or adapter class name.
158	 */
159	public function setHttpClientChannel($adapterInstance = 'Zend_Http_Client_Adapter_Socket')
160	{
161		$this->_httpClientChannel->setAdapter($adapterInstance);
162	}
163	
164    /**
165     * Retrieve HTTP client channel
166     * 
167     * @return Zend_Http_Client_Adapter_Interface
168     */
169    public function getHttpClientChannel()
170    {
171        return $this->_httpClientChannel;
172    }
173	
174	/**
175	 * Returns the Windows Azure subscription ID
176	 * 
177	 * @return string
178	 */
179	public function getSubscriptionId()
180	{
181		return $this->_subscriptionId;
182	}
183	
184	/**
185	 * Returns the last request ID.
186	 * 
187	 * @return string
188	 */
189	public function getLastRequestId()
190	{
191		return $this->_lastRequestId;
192	}
193	
194	/**
195	 * Get base URL for creating requests
196	 *
197	 * @return string
198	 */
199	public function getBaseUrl()
200	{
201		return self::URL_MANAGEMENT . '/' . $this->_subscriptionId;
202	}
203	
204	/**
205	 * Perform request using Zend_Http_Client channel
206	 *
207	 * @param string $path Path
208	 * @param string $queryString Query string
209	 * @param string $httpVerb HTTP verb the request will use
210	 * @param array $headers x-ms headers to add
211	 * @param mixed $rawData Optional RAW HTTP data to be sent over the wire
212	 * @return Zend_Http_Response
213	 */
214	protected function _performRequest(
215		$path = '/',
216		$queryString = '',
217		$httpVerb = Zend_Http_Client::GET,
218		$headers = array(),
219		$rawData = null
220	) {
221	    // Clean path
222		if (strpos($path, '/') !== 0) {
223			$path = '/' . $path;
224		}
225			
226		// Clean headers
227		if (is_null($headers)) {
228		    $headers = array();
229		}
230		
231		// Ensure cUrl will also work correctly:
232		//  - disable Content-Type if required
233		//  - disable Expect: 100 Continue
234		if (!isset($headers["Content-Type"])) {
235			$headers["Content-Type"] = '';
236		}
237		//$headers["Expect"] = '';
238
239		// Add version header
240		$headers['x-ms-version'] = $this->_apiVersion;
241		    
242		// URL encoding
243		$path           = self::urlencode($path);
244		$queryString    = self::urlencode($queryString);
245
246		// Generate URL and sign request
247		$requestUrl     = $this->getBaseUrl() . $path . $queryString;
248		$requestHeaders = $headers;
249
250		// Prepare request 
251		$this->_httpClientChannel->resetParameters(true);
252		$this->_httpClientChannel->setUri($requestUrl);
253		$this->_httpClientChannel->setHeaders($requestHeaders);
254		$this->_httpClientChannel->setRawData($rawData);
255
256		// Execute request
257		$response = $this->_retryPolicy->execute(
258		    array($this->_httpClientChannel, 'request'),
259		    array($httpVerb)
260		);
261		
262		// Store request id
263		$this->_lastRequestId = $response->getHeader('x-ms-request-id');
264		
265		return $response;
266	}
267	
268	/** 
269	 * Parse result from Zend_Http_Response
270	 *
271	 * @param Zend_Http_Response $response Response from HTTP call
272	 * @return object
273	 * @throws Zend_Service_WindowsAzure_Exception
274	 */
275	protected function _parseResponse(Zend_Http_Response $response = null)
276	{
277		if (is_null($response)) {
278			require_once 'Zend/Service/SqlAzure/Exception.php';
279			throw new Zend_Service_SqlAzure_Exception('Response should not be null.');
280		}
281		
282        $xml = @simplexml_load_string($response->getBody());
283        
284        if ($xml !== false) {
285            // Fetch all namespaces 
286            $namespaces = array_merge($xml->getNamespaces(true), $xml->getDocNamespaces(true)); 
287            
288            // Register all namespace prefixes
289            foreach ($namespaces as $prefix => $ns) { 
290                if ($prefix != '') {
291                    $xml->registerXPathNamespace($prefix, $ns);
292                } 
293            } 
294        }
295        
296        return $xml;
297	}
298	
299	/**
300	 * URL encode function
301	 * 
302	 * @param  string $value Value to encode
303	 * @return string        Encoded value
304	 */
305	public static function urlencode($value)
306	{
307	    return str_replace(' ', '%20', $value);
308	}
309	
310    /**
311     * Builds a query string from an array of elements
312     * 
313     * @param array     Array of elements
314     * @return string   Assembled query string
315     */
316    public static function createQueryStringFromArray($queryString)
317    {
318    	return count($queryString) > 0 ? '?' . implode('&', $queryString) : '';
319    }
320    
321	/**
322	 * Get error message from Zend_Http_Response
323	 *
324	 * @param Zend_Http_Response $response Repsonse
325	 * @param string $alternativeError Alternative error message
326	 * @return string
327	 */
328	protected function _getErrorMessage(Zend_Http_Response $response, $alternativeError = 'Unknown error.')
329	{
330		$response = $this->_parseResponse($response);
331		if ($response && $response->Message) {
332			return (string)$response->Message;
333		} else {
334			return $alternativeError;
335		}
336	}
337	
338	/**
339	 * The Create Server operation adds a new SQL Azure server to a subscription.
340	 * 
341	 * @param string $administratorLogin Administrator login.
342	 * @param string $administratorPassword Administrator password.
343	 * @param string $location Location of the server.
344	 * @return Zend_Service_SqlAzure_Management_ServerInstance Server information.
345	 * @throws Zend_Service_SqlAzure_Management_Exception
346	 */
347	public function createServer($administratorLogin, $administratorPassword, $location)
348	{
349		if ($administratorLogin == '' || is_null($administratorLogin)) {
350                    require_once 'Zend/Service/SqlAzure/Management/Exception.php';
351                    throw new Zend_Service_SqlAzure_Management_Exception('Administrator login should be specified.');
352                }
353		if ($administratorPassword == '' || is_null($administratorPassword)) {
354                    require_once 'Zend/Service/SqlAzure/Management/Exception.php';
355                    throw new Zend_Service_SqlAzure_Management_Exception('Administrator password should be specified.');
356                }
357                if (is_null($location) && is_null($affinityGroup)) {
358                    require_once 'Zend/Service/SqlAzure/Management/Exception.php';
359                    throw new Zend_Service_SqlAzure_Management_Exception('Please specify a location for the server.');
360                }
361    	
362                $response = $this->_performRequest(self::OP_SERVERS, '',
363    		Zend_Http_Client::POST,
364    		array('Content-Type' => 'application/xml; charset=utf-8'),
365    		'<Server xmlns="http://schemas.microsoft.com/sqlazure/2010/12/"><AdministratorLogin>' . $administratorLogin . '</AdministratorLogin><AdministratorLoginPassword>' . $administratorPassword . '</AdministratorLoginPassword><Location>' . $location . '</Location></Server>');
366 	
367                if ($response->isSuccessful()) {
368			$xml = $this->_parseResponse($response);
369			
370			return new Zend_Service_SqlAzure_Management_ServerInstance(
371				(string)$xml,
372				$administratorLogin,
373				$location
374			);
375                } else {
376			require_once 'Zend/Service/SqlAzure/Management/Exception.php';
377			throw new Zend_Service_SqlAzure_Management_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
378		}	
379	}
380	
381	/**
382	 * The Get Servers operation enumerates SQL Azure servers that are provisioned for a subscription.
383	 * 
384	 * @return array An array of Zend_Service_SqlAzure_Management_ServerInstance.
385	 * @throws Zend_Service_SqlAzure_Management_Exception
386	 */
387	public function listServers()
388	{
389            $response = $this->_performRequest(self::OP_SERVERS);
390 	
391            if ($response->isSuccessful()) {
392		$xml = $this->_parseResponse($response);
393		$xmlServices = null;
394			
395                if (!$xml->Server) {
396                    return array();
397		}
398		if (count($xml->Server) > 1) {
399    		    $xmlServices = $xml->Server;
400    		} else {
401    		    $xmlServices = array($xml->Server);
402    		}
403    		
404		$services = array();
405		if (!is_null($xmlServices)) {				
406				
407                    for ($i = 0; $i < count($xmlServices); $i++) {
408                        $services[] = new Zend_Service_SqlAzure_Management_ServerInstance(
409                                	    (string)$xmlServices[$i]->Name,
410					    (string)$xmlServices[$i]->AdministratorLogin,
411					    (string)$xmlServices[$i]->Location
412					);
413                    }
414		}
415		return $services;
416            } else {
417		require_once 'Zend/Service/SqlAzure/Management/Exception.php';
418		throw new Zend_Service_SqlAzure_Management_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
419            }
420	}
421	
422	/**
423	 * The Drop Server operation drops a SQL Azure server from a subscription.
424	 * 
425	 * @param string $serverName Server to drop.
426	 * @throws Zend_Service_SqlAzure_Management_Exception
427	 */
428	public function dropServer($serverName)
429	{
430            if ($serverName == '' || is_null($serverName)) {
431                require_once 'Zend/Service/SqlAzure/Management/Exception.php';
432                throw new Zend_Service_SqlAzure_Management_Exception('Server name should be specified.');
433            }
434    	
435            $response = $this->_performRequest(self::OP_SERVERS . '/' . $serverName, '', Zend_Http_Client::DELETE);
436
437            if (!$response->isSuccessful()) {
438		require_once 'Zend/Service/SqlAzure/Management/Exception.php';
439		throw new Zend_Service_SqlAzure_Management_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
440            }	
441	}
442	
443	/**
444	 * The Set Server Administrator Password operation sets the administrative password of a SQL Azure server for a subscription.
445	 * 
446	 * @param string $serverName Server to set password for.
447	 * @param string $administratorPassword Administrator password.
448	 * @throws Zend_Service_SqlAzure_Management_Exception
449	 */
450	public function setAdministratorPassword($serverName, $administratorPassword)
451	{
452            if ($serverName == '' || is_null($serverName)) {
453		require_once 'Zend/Service/SqlAzure/Management/Exception.php';
454    		throw new Zend_Service_SqlAzure_Management_Exception('Server name should be specified.');
455            }
456            if ($administratorPassword == '' || is_null($administratorPassword)) {
457                require_once 'Zend/Service/SqlAzure/Management/Exception.php';
458    		throw new Zend_Service_SqlAzure_Management_Exception('Administrator password should be specified.');
459            }
460    	
461            $response = $this->_performRequest(self::OP_SERVERS . '/' . $serverName, '?op=ResetPassword',
462    		Zend_Http_Client::POST,
463    		array('Content-Type' => 'application/xml; charset=utf-8'),
464    		'<AdministratorLoginPassword xmlns="http://schemas.microsoft.com/sqlazure/2010/12/">' . $administratorPassword . '</AdministratorLoginPassword>');
465    		
466            if (!$response->isSuccessful()) {
467		require_once 'Zend/Service/SqlAzure/Management/Exception.php';
468		throw new Zend_Service_SqlAzure_Management_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
469            }	
470	}
471	
472	/**
473	 * 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.
474	 * 
475	 * @param string $serverName Server name.
476	 * @param string $ruleName Firewall rule name.
477	 * @param string $startIpAddress Start IP address.
478	 * @param string $endIpAddress End IP address.
479	 * @return Zend_Service_SqlAzure_Management_FirewallRuleInstance
480	 * @throws Zend_Service_SqlAzure_Management_Exception
481	 */
482	public function createFirewallRule($serverName, $ruleName, $startIpAddress, $endIpAddress)
483	{
484            if ($serverName == '' || is_null($serverName)) {
485                require_once 'Zend/Service/SqlAzure/Management/Exception.php';
486                throw new Zend_Service_SqlAzure_Management_Exception('Server name should be specified.');
487            }
488            if ($ruleName == '' || is_null($ruleName)) {
489                require_once 'Zend/Service/SqlAzure/Management/Exception.php';
490                throw new Zend_Service_SqlAzure_Management_Exception('Rule name should be specified.');
491            }
492            if ($startIpAddress == '' || is_null($startIpAddress) || !filter_var($startIpAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
493                require_once 'Zend/Service/SqlAzure/Management/Exception.php';
494                throw new Zend_Service_SqlAzure_Management_Exception('Start IP address should be specified.');
495            }
496            if ($endIpAddress == '' || is_null($endIpAddress) || !filter_var($endIpAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
497                require_once 'Zend/Service/SqlAzure/Management/Exception.php';
498                throw new Zend_Service_SqlAzure_Management_Exception('End IP address should be specified.');
499            }
500    	
501            $response = $this->_performRequest(self::OP_SERVERS . '/' . $serverName . '/' . self::OP_FIREWALLRULES . '/' . $ruleName, '',
502    		Zend_Http_Client::PUT,
503    		array('Content-Type' => 'application/xml; charset=utf-8'),
504    		'<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>');
505
506            if ($response->isSuccessful()) {
507		
508    		return new Zend_Service_SqlAzure_Management_FirewallRuleInstance(
509    			$ruleName,
510    			$startIpAddress,
511    			$endIpAddress
512    		);
513            } else {
514		require_once 'Zend/Service/SqlAzure/Management/Exception.php';
515		throw new Zend_Service_SqlAzure_Management_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
516            }
517	}
518	
519	/**
520	 * The Get Server Firewall Rules operation retrieves a list of all the firewall rules for a SQL Azure server that belongs to a subscription.
521	 * 
522	 * @param string $serverName Server name.
523	 * @return Array of Zend_Service_SqlAzure_Management_FirewallRuleInstance.
524	 * @throws Zend_Service_SqlAzure_Management_Exception
525	 */
526	public function listFirewallRules($serverName)
527	{
528            if ($serverName == '' || is_null($serverName)) {
529		require_once 'Zend/Service/SqlAzure/Management/Exception.php';
530                throw new Zend_Service_SqlAzure_Management_Exception('Server name should be specified.');
531            }
532    	
533	    $response = $this->_performRequest(self::OP_SERVERS . '/' . $serverName . '/' . self::OP_FIREWALLRULES);
534 	
535            if ($response->isSuccessful()) {
536		$xml = $this->_parseResponse($response);
537		$xmlServices = null;
538			
539    		if (!$xml->FirewallRule) {
540                    return array();
541		}
542		if (count($xml->FirewallRule) > 1) {
543    		    $xmlServices = $xml->FirewallRule;
544    		} else {
545    		    $xmlServices = array($xml->FirewallRule);
546    		}
547    		
548		$services = array();
549		if (!is_null($xmlServices)) {				
550                    
551                    for ($i = 0; $i < count($xmlServices); $i++) {
552                        $services[] = new Zend_Service_SqlAzure_Management_FirewallRuleInstance(
553					    (string)$xmlServices[$i]->Name,
554					    (string)$xmlServices[$i]->StartIpAddress,
555					    (string)$xmlServices[$i]->EndIpAddress
556					);
557                    }
558		}
559		return $services;
560            } else {
561		require_once 'Zend/Service/SqlAzure/Management/Exception.php';
562		throw new Zend_Service_SqlAzure_Management_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
563            }		
564	}
565	
566	/**
567	 * The Delete Server Firewall Rule operation deletes a firewall rule from a SQL Azure server that belongs to a subscription.
568	 * 
569	 * @param string $serverName Server name.
570	 * @param string $ruleName Rule name.
571	 * @throws Zend_Service_SqlAzure_Management_Exception
572	 */
573	public function deleteFirewallRule($serverName, $ruleName)
574	{
575		if ($serverName == '' || is_null($serverName)) {
576			require_once 'Zend/Service/SqlAzure/Management/Exception.php';
577    		throw new Zend_Service_SqlAzure_Management_Exception('Server name should be specified.');
578    	}
579		if ($ruleName == '' || is_null($ruleName)) {
580			require_once 'Zend/Service/SqlAzure/Management/Exception.php';
581    		throw new Zend_Service_SqlAzure_Management_Exception('Rule name should be specified.');
582    	}
583    	
584        $response = $this->_performRequest(self::OP_SERVERS . '/' . $serverName . '/' . self::OP_FIREWALLRULES . '/' . $ruleName, '',
585    		Zend_Http_Client::DELETE);
586
587    	if (!$response->isSuccessful()) {
588			require_once 'Zend/Service/SqlAzure/Management/Exception.php';
589			throw new Zend_Service_SqlAzure_Management_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
590		}
591	}
592	
593	/**
594	 * Creates a firewall rule for Microsoft Services. This is required if access to SQL Azure is required from other services like Windows Azure.
595	 * 
596	 * @param string $serverName Server name.
597	 * @param boolean $allowAccess Allow access from other Microsoft Services?
598	 * @throws Zend_Service_SqlAzure_Management_Exception
599	 */
600	public function createFirewallRuleForMicrosoftServices($serverName, $allowAccess)
601	{
602		if ($allowAccess) {
603			$this->createFirewallRule($serverName, 'MicrosoftServices', '0.0.0.0', '0.0.0.0');
604		} else {
605			$this->deleteFirewallRule($serverName, 'MicrosoftServices');
606		}
607	}
608	
609}