Skip to content
RscApi.php 18 KiB
Newer Older
root's avatar
root committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
<?php
/**
 * Rackspace Cloud Server API PHP Library
 *
 * @package RscApi
 */

/**
 * Rackspace Cloud Server API PHP Library
 *
 * The Rackspace Cloud has released an API for their Cloud Servers which you can
 * find below
 *
 * The Cloud Server API is currently in beta, and does not have any libraries
 * available to simplify making calls, so I have created this PHP one.
 *
 * This is strictly for PHP5 since PHP4 should be forgotten forever.
 *
 * The API has some poorly written documentation, but it is still useful (link
 * below).
 *
 * @link http://www.rackspacecloud.com/cloud_hosting_products/servers/api
 * @link http://docs.rackspacecloud.com/servers/api/cs-devguide-latest.pdf
 *
 * @package RscApi
 */
class RscApi {
	/**
	 * Timeout in seconds for an API call to respond
	 * @var integer
	 */
	private static $TIMEOUT = 10;

	private $serverUrl;
	private $authToken;
	private $authUser;
	private $authKey;
	private $lastResponseStatus;

	/**
	 * Creates a new Rackspace Cloud Servers API object to make calls with
	 *
	 * Your API key needs to be generated using the Rackspace Cloud Management
	 * Console. You can do this under Cloud Files (not Cloud Servers).
	 *
	 * Authentication is done automatically when making the first API call
	 * using this object.
	 *
	 * @param string $user The username of the account to use
	 * @param string $key The API key to use
	 */
	public function __construct($user, $key) {
		$this->authUser = $user;
		$this->authKey = $key;

		$this->serverUrl = NULL;
		$this->authToken = NULL;
	}

	/**
	 * Get a list of flavors (available hardware configurations)
	 *
	 * A flavor is a hardware configuration for a server. Each flavor has a
	 * a different combination of disk space, memory capacity and priority for
	 * CPU time.
	 *
	 * @param boolean $detailed If TRUE, get detailed config information
	 * @return array A list of flavor details comprising of ID, name, RAM and
	 * 		disk information
	 */
	public function flavorList($detailed = FALSE) {
		$url = "/flavors";
		if ($detailed) {
			$url .= "/detail";
		}

		$response = $this->makeApiCall($url);
		if (isset($response['flavors'])) {
			return $response['flavors'];
		}

		return NULL;
	}

	/**
	 * Creates an image of the given server
	 *
	 * You can use this method to create custom images. Once your image has
	 * been created, you can build new servers with it.
	 *
	 * @param string $name The name of the image to create
	 * @param integer $serverId The ID of the server to build the image from
	 * @return array Details of the new images (most importantly, it's ID)
	 */
	public function imageCreate($name, $serverId) {
		$url = "/images";

		$data = array(
			"image" => array(
				"serverId" => $serverId,
				"name" => $name,
			),
		);
		$jsonData = json_encode($data);

		$response = $this->makeApiCall($url, $jsonData);
		if (isset($response['image'])) {
			return $response['image'];
		}

		return NULL;
	}

	/**
	 * Delete a image, destroying all data on it
	 *
	 * Make sure you want to do this before calling this method.
	 *
	 * @param integer $imageId The ID of the image to delete
	 * @return boolean TRUE if the image has been deleted
	 */
	public function imageDelete($imageId) {
		$url = "/images/$imageId";

		$this->makeApiCall($url, NULL, "delete");
		if ($this->getLastResponseStatus() == "202") {
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * Gets the details of a specific image
	 *
	 * @param integer $imageId The ID of the image to get the details for
	 * @return array Image details
	 */
	public function imageDetails($imageId) {
		$url = "/images/$imageId";

		$response = $this->makeApiCall($url);
		if (in_array($this->getLastResponseStatus(), array(200, 203))) {
			if (isset($response['image'])) {
				return $response['image'];
			}
		}

		return NULL;
	}

	/**
	 * Get a list of images
	 *
	 * An image is a collection of files you can use to create or rebuild a
	 * server with. There are pre-build ones provided, but you can also create
	 * your own.
	 *
	 * @param boolean $detailed If TRUE, get detailed image information
	 * @return array Image details
	 */
	public function imageList($detailed = FALSE) {
		$url = "/images";
		if ($detailed) {
			$url .= "/detail";
		}

		$response = $this->makeApiCall($url);
		if (isset($response['images'])) {
			return $response['images'];
		}

		return NULL;
	}

	/**
	 * Gets the API call limits for this account
	 *
	 * There are two types of limits enforced by Rackspace Cloud - rate limits
	 * and absolute limits.
	 *
	 * @return array Absolute and rate limits
	 */
	public function limits() {
		$response = $this->makeApiCall("/limits");
		if (in_array($this->getLastResponseStatus(), array(200, 203))
				&& isset($response['limits'])) {
			return $response['limits'];
		}

		return NULL;
	}

	/**
	 * Gets a list of all of the IP addresses (public and private) for the
	 * specified server
	 *
	 * @param integer $serverId The ID of the server to list addresses of
	 * @return array The list of public and private IP addresses
	 */
	public function serverAddressList($serverId) {
		$url = "/servers/$serverId/ips";

		$response = $this->makeApiCall($url);
		if (in_array($this->getLastResponseStatus(), array(200, 203))) {
			if (isset($response['addresses'])) {
				return $response['addresses'];
			}
		}

		return NULL;
	}

	/**
	 * Share an IP Address with another server
	 *
	 * This is a little strange, but the way it works is you pick a public IP
	 * Address from a server in the Shared IP Group. You then pick another
	 * server to share that IP Address with in the same Shared IP Group.
	 *
	 * @param integer $serverId The server to share the IP Address with - the
	 * 		destination, not the source/owner of the address now.
	 * @param string $ipAddress The public IP address to share
	 * @param integer $sharedIpGroupId The ID of the group to share it with
	 * @param boolean $configure (Optional) Set to TRUE to configure and reboot
	 * 		the server to accept the new IP Address
	 * @return boolean TRUE if the IP Address is now shared with $serverId
	 */
	public function serverAddressShare($serverId, $ipAddress, $sharedIpGroupId,
			$configure = FALSE) {
		$data = array(
			"shareIp" => array(
				"sharedIpGroupId" => $sharedIpGroupId,
			),
		);
		if ($configure) {
			$data['shareIp']['configureServer'] = true;
		}
		$jsonData = json_encode($data);

		$url = "/servers/$serverId/ips/public/$ipAddress";
		$this->makeApiCall($url, $jsonData, "put");
		if ($this->getLastResponseStatus() == "202") {
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * Removes a shared IP Address from the specified server
	 *
	 * @param integer $serverId The server to remove a share the IP Address from
	 * @param string $ipAddress The shared public IP address to remove
	 * @return boolean TRUE if the IP Address is no longer shared
	 */
	public function serverAddressUnshare($serverId, $ipAddress) {
		$url = "/servers/$serverId/ips/public/$ipAddress";
		$this->makeApiCall($url, NULL, "delete");
		if ($this->getLastResponseStatus() == "202") {
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * Creates a new server
	 *
	 * Keep in mind that servers are created asynchronously. This means that
	 * after this call, your server will be built over time. You can use the
	 * server ID returned from this call to make subsequent calls to get the
	 * build progress status.
	 *
	 * Note that there is currently no support for server metadata.
	 *
	 * @param string $name The friendly name of the server
	 * @param integer $imageId The ID of the image to use
	 * @param integer $flavorId The ID of the hardware config (flavor)
	 * @param integer $sharedIpGroupId (Optional) The ID of the shared IP group
	 * 		to put the new server into (this is the only way you can add a
	 * 		server into a shared IP group)
	 * @return array New server details including the generated root password
	 */
	public function serverCreate($name, $imageId, $flavorId,
			$sharedIpGroupId = NULL) {
		$data = array(
			"server" => array(
				"name" => $name,
				"imageId" => $imageId,
				"flavorId" => $flavorId,
			),
		);
		if ($sharedIpGroupId) {
			$data['server']['sharedIpGroupId'] = $sharedIpGroupId;
		}
		$jsonData = json_encode($data);

		$url = "/servers";
		$response = $this->makeApiCall($url, $jsonData);
		if (isset($response['server'])) {
			return $response['server'];
		}

		return NULL;
	}

	/**
	 * Delete a server, destroying all data on it
	 *
	 * Make sure you want to do this before calling this method. Server deletes
	 * also destroy all images created by that server (strange as it may seem).
	 *
	 * @param integer $serverId The ID of the server to delete
	 * @return boolean TRUE if the server has been deleted
	 */
	public function serverDelete($serverId) {
		$url = "/servers/$serverId";

		$this->makeApiCall($url, NULL, "delete");
		if ($this->getLastResponseStatus() == "202") {
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * Gets the details of a specific server
	 *
	 * @param integer $serverId The ID of the server to get the details for
	 * @return array Server details
	 */
	public function serverDetails($serverId) {
		$url = "/servers/$serverId";

		$response = $this->makeApiCall($url);
		if (isset($response['server'])) {
			return $response['server'];
		}

		return NULL;
	}

	/**
	 * Get a list of servers associated with this account
	 *
	 * @param boolean $detailed If TRUE, get detailed server information
	 * @return array Server details
	 */
	public function serverList($detailed = FALSE) {
		$url = "/servers";
		if ($detailed) {
			$url .= "/detail?cacheid=".time();
		}
		else {
		  $url .= "?cacheid=".time();
		}

		$response = $this->makeApiCall($url);
		if (isset($response['servers'])) {
			return $response['servers'];
		}

		return NULL;
	}

	/**
	 * Resize a server - either up or down
	 *
	 * Keep in mind that servers are created asynchronously. This means that
	 * after this call, your server will be resized over time.
	 *
	 * @param integer $serverId The ID of the server to get the details for
	 * @param integer $flavorId The ID of the hardware config (flavor)
	 * @return boolean TRUE if the reboot is underway
	 */
	public function serverResize($serverId, $flavorId) {
		$data = array(
			"resize" => array(
				"flavorId" => $flavorId,
			),
		);
		$jsonData = json_encode($data);

		$url = "/servers/$serverId/action";
		$response = $this->makeApiCall($url, $jsonData);
		if ($this->getLastResponseStatus() == "202") {
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * Reboot a server
	 *
	 * The default is to do a SOFT reboot, meaning a graceful shutdown and
	 * reboot of the system. You can also do a HARD reboot, which is the
	 * equivalent of taking the power cord out and putting it back in.
	 *
	 * @param integer $serverId The ID of the server to reboot
	 * @param boolean $hardReboot (Optional) Set to TRUE to perform a hard
	 * 		reboot
	 * @return boolean TRUE if the reboot is underway
	 */
	public function serverReboot($serverId, $hardReboot = FALSE) {
		$url = "/servers/$serverId/action";

		$data = array(
			"reboot" => array(),
		);
		if ($hardReboot) {
			$data['reboot']['type'] = "HARD";
		} else {
			$data['reboot']['type'] = "SOFT";
		}
		$jsonData = json_encode($data);

		$this->makeApiCall($url, $jsonData);
		if ($this->getLastResponseStatus() == "202") {
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * List the backup schedule for a specific server
	 *
	 * @param integer $serverId The ID of the server to list the schedule for
	 * @return array Backup schedule details
	 */
	public function serverBackupList($serverId) {
		$url = "/servers/$serverId/backup_schedule";

		$response = $this->makeApiCall($url);
		$status = $this->getLastResponseStatus();
		if ($status == "200" || $status == "203") {
			if (isset($response['backupSchedule'])) {
				return $response['backupSchedule'];
			}
		}

		return NULL;
	}


	/**
	 * Creates a new shared IP group
	 *
	 * @param string $name The friendly name of the group
	 * @param integer $serverId (Optional) The ID of the server to add to the group
	 * @return array Details of the new group
	 */
	public function sharedIpGroupCreate($name, $serverId = NULL) {
		$data = array(
			"sharedIpGroup" => array(
				"name" => $name,
			),
		);
		if ($serverId) {
			$data['sharedIpGroup']['server'] = $serverId;
		}
		$jsonData = json_encode($data);

		$url = "/shared_ip_groups";
		$response = $this->makeApiCall($url, $jsonData);
		if (isset($response['sharedIpGroup'])) {
			return $response['sharedIpGroup'];
		}

		return NULL;
	}

	/**
	 * Gets details about a specific shared IP group
	 *
	 * @param integer $sharedIpGroupId The ID of the group to get details for
	 * @return array Group details
	 */
	public function sharedIpGroupDetails($sharedIpGroupId) {
		$url = "/shared_ip_groups/$sharedIpGroupId";

		$response = $this->makeApiCall($url);
		if (isset($response['sharedIpGroup'])) {
			return $response['sharedIpGroup'];
		}

		return NULL;
	}


	/**
	 * Get a list of all shared IP groups
	 *
	 * @param boolean $detailed If TRUE, get detailed shared IP group information
	 * @return array Shared IP group details
	 */
	public function sharedIpGroupList($detailed = FALSE) {
		$url = "/shared_ip_groups";
		if ($detailed) {
			$url .= "/detail";
		}

		$response = $this->makeApiCall($url);
		if (isset($response['sharedIpGroups'])) {
			return $response['sharedIpGroups'];
		}

		return NULL;
	}

	/**
	 * Translates the HTTP response status from the last API call to a human
	 * friendly message
	 *
	 * @return string The response message from the last call
	 */
	public function getLastResponseMessage() {
		$map = array(
			"200" => "Successful informational response",
			"202" => "Successful action response",
			"203" => "Successful informational response from the cache",
			"204" => "Authentication successful",
			"400" => "Bad request (check the validity of input values)",
			"401" => "Unauthorized (check username and API key)",
			"403" => "Resize not allowed",
			"404" => "Item not found",
			"409" => "Build, backup or resize in process",
			"413" => "Over API limit (check limits())",
			"415" => "Bad media type",
			"500" => "Cloud server issue",
			"503" => "API service in unavailable, or capacity is not available",
		);

		$status = $this->getLastResponseStatus();
		if ($status) {
			return $map[$status];
		}

		return "UNKNOWN - Probably a timeout on the connection";
	}

	/**
	 * Gets the HTTP response status from the last API call
	 *
	 * - 200 - successful informational response
	 * - 202 - successful action response
	 * - 203 - successful informational response from the cache
	 * - 400 - bad request (possibly because the input values were invalid)
	 * - 401 - unauthorized (check username and API key)
	 * - 403 - resize not allowed
	 * - 404 - item not found
	 * - 409 - build, backup or resize in process
	 * - 413 - over API limit (check limits())
	 * - 415 - bad media type
	 * - 500 - cloud server issue
	 * - 503 - API service in unavailable, or capacity is not available
	 *
	 * @return integer The 3 digit HTTP response status, or NULL if the call had
	 * 		issues
	 */
	public function getLastResponseStatus() {
		return $this->lastResponseStatus;
	}

	/**
	 * Makes a call to the API
	 *
	 * @param string $url The relative URL to call (example: "/server")
	 * @param string $postData (Optional) The JSON string to send
	 * @param string $method (Optional) The HTTP method to use
	 * @return array The parsed response, or NULL if there was an error
	 */
	private function makeApiCall($url, $postData = NULL, $method = NULL) {
		// Authenticate if necessary
		if (!$this->isAuthenticated()) {
			if (!$this->authenticate()) {
				return NULL;
			}
		}

		$this->lastResponseStatus = NULL;

		$jsonUrl = $this->serverUrl . $url . ".json";
		$httpHeaders = array(
			"X-Auth-Token: {$this->authToken}",
		);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $jsonUrl);
		if ($postData) {
			curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
			$httpHeaders[] = "Content-Type: application/json";
		}
		if ($method) {
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
		}
		curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$this, 'parseHeader'));
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
		curl_setopt($ch, CURLOPT_TIMEOUT, RscApi::$TIMEOUT);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

		$jsonResponse = curl_exec($ch);
		curl_close($ch);

		return json_decode($jsonResponse, TRUE);
	}

	/**
	 * Curl call back method to parse header values one by one (there will be
	 * many)
	 *
	 * @param resource $ch The Curl handler
	 * @param string $header The HTTP header line to parse
	 * @return integer The number of bytes in the header line
	 */
	private function parseHeader($ch, $header) {
		preg_match("/^HTTP\/1\.[01] (\d{3}) (.*)/", $header, $matches);
        if (isset($matches[1])) {
            $this->lastResponseStatus = $matches[1];
        }

        return strlen($header);
	}

	/**
	 * Determines if authentication has been complete
	 *
	 * @return boolean TRUE if authentication is complete, FALSE if it needs to
	 * 		be done
	 */
	private function isAuthenticated() {
		return ($this->serverUrl && $this->authToken);
	}

	/**
	 * Authenticates with the API
	 *
	 * @return boolean TRUE if the authentication was successful
	 */
	private function authenticate() {
		$authUrl = "https://auth.api.rackspacecloud.com/v1.0";
		$authHeaders = array(
			"X-Auth-User: {$this->authUser}",
			"X-Auth-Key: {$this->authKey}",
		);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $authUrl);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $authHeaders);
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$response = curl_exec($ch);
		curl_close($ch);

		preg_match("/^HTTP\/1\.[01] (\d{3}) (.*)/", $response, $matches);
		if (isset($matches[1])) {
			$this->lastResponseStatus = $matches[1];
			if ($this->lastResponseStatus == "204") {
				preg_match("/X-Server-Management-Url: (.*)/", $response,
						$matches);
				$this->serverUrl = trim($matches[1]);

				preg_match("/X-Auth-Token: (.*)/", $response, $matches);
				$this->authToken = trim($matches[1]);

				return TRUE;
			}
		}

		return FALSE;
	}
}
?>