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