PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/Microsoft/SqlAzure/Management/Client.php

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