PageRenderTime 46ms CodeModel.GetById 22ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

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