From e959b018e15f6ca2ef8a1a3ca75f19ca21b26efe Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 18 Dec 2014 16:11:08 +0530 Subject: [PATCH 001/181] Allow using PUT (default) or PATCH as update method depending on property. --- .../Common/Resource/PersistentResource.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index c012b8e76..9ae6582e3 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -28,6 +28,8 @@ abstract class PersistentResource extends BaseResource { + const UPDATE_METHOD = 'PUT'; + /** * Create a new resource * @@ -79,7 +81,16 @@ public function update($params = array()) $this->checkJsonError(); // send the request - return $this->getClient()->put($this->getUrl(), self::getJsonHeader(), $json)->send(); + return $this->makeUpdateRequest($json); + } + + protected function makeUpdateRequest($json) + { + if ('PATCH' === static::UPDATE_METHOD) { + return $this->getClient()->patch($this->getUrl(), self::getJsonHeader(), $json)->send(); + } else { + return $this->getClient()->put($this->getUrl(), self::getJsonHeader(), $json)->send(); + } } /** From 87d31166e56409d49198dbac7648c0970b417e44 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 19 Dec 2014 11:45:40 +0530 Subject: [PATCH 002/181] Setting memory limit needed for code coverage generation. --- phpunit.xml.dist | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index cd44e77df..be5f3c7e6 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -25,4 +25,8 @@ + + + + From 601e18c0af9dd62785c25dcb3bea9e351bdc855f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 19 Dec 2014 12:43:38 +0530 Subject: [PATCH 003/181] Parameterize type of service in catalog so it can be specified when building a service object. --- lib/OpenCloud/Common/Service/ServiceBuilder.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/Common/Service/ServiceBuilder.php b/lib/OpenCloud/Common/Service/ServiceBuilder.php index cf59f4a2b..99747e900 100644 --- a/lib/OpenCloud/Common/Service/ServiceBuilder.php +++ b/lib/OpenCloud/Common/Service/ServiceBuilder.php @@ -37,6 +37,7 @@ class ServiceBuilder public static function factory(ClientInterface $client, $class, array $options = array()) { $name = isset($options['name']) ? $options['name'] : null; + $type = isset($options['type']) ? $options['type'] : null; $urlType = isset($options['urlType']) ? $options['urlType'] : null; if (isset($options['region'])) { @@ -47,6 +48,6 @@ public static function factory(ClientInterface $client, $class, array $options = $region = null; } - return new $class($client, null, $name, $region, $urlType); + return new $class($client, $type, $name, $region, $urlType); } } From 733ddd654af767ff5b9ec8a38c311857727f8514 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 19 Dec 2014 12:47:43 +0530 Subject: [PATCH 004/181] Adding tests and implementation for the CDN service. --- lib/OpenCloud/CDN/Resource/Flavor.php | 47 ++++++ lib/OpenCloud/CDN/Resource/Service.php | 90 +++++++++++ lib/OpenCloud/CDN/Service.php | 145 ++++++++++++++++++ lib/OpenCloud/OpenStack.php | 18 +++ lib/OpenCloud/Rackspace.php | 19 +++ tests/OpenCloud/Tests/CDN/CDNTestCase.php | 49 ++++++ .../Tests/CDN/Resource/ServiceTest.php | 40 +++++ tests/OpenCloud/Tests/CDN/ServiceTest.php | 82 ++++++++++ tests/OpenCloud/Tests/_response/Auth.resp | 11 ++ 9 files changed, 501 insertions(+) create mode 100644 lib/OpenCloud/CDN/Resource/Flavor.php create mode 100644 lib/OpenCloud/CDN/Resource/Service.php create mode 100644 lib/OpenCloud/CDN/Service.php create mode 100644 tests/OpenCloud/Tests/CDN/CDNTestCase.php create mode 100644 tests/OpenCloud/Tests/CDN/Resource/ServiceTest.php create mode 100644 tests/OpenCloud/Tests/CDN/ServiceTest.php diff --git a/lib/OpenCloud/CDN/Resource/Flavor.php b/lib/OpenCloud/CDN/Resource/Flavor.php new file mode 100644 index 000000000..28bf8c1b8 --- /dev/null +++ b/lib/OpenCloud/CDN/Resource/Flavor.php @@ -0,0 +1,47 @@ +noUpdate(); + } +} diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php new file mode 100644 index 000000000..00348129b --- /dev/null +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -0,0 +1,90 @@ + 'flavorId' + ); + + protected $createKeys = array( + 'name', + 'domains', + 'origins', + 'caching', + 'restrictions', + 'flavorId' + ); + + protected $updateKeys = array( + 'name', + 'domains', + 'origins', + 'caching', + 'restrictions', + 'flavorId' + ); + + public function purgeAssets($assetUrl = null) + { + $assetsUrl = $this->assetsUrl(); + if (null === $assetUrl) { + $assetsUrl->setQuery(array('all' => 'true')); + } else { + $assetsUrl->setQuery(array('url' => $assetUrl)); + } + + return $this->getClient()->delete($assetsUrl)->send(); + } + + protected function assetsUrl() + { + $url = clone $this->getUrl(); + $url->addPath('assets'); + + return $url; + } + + protected function primaryKeyField() + { + return 'name'; + } +} diff --git a/lib/OpenCloud/CDN/Service.php b/lib/OpenCloud/CDN/Service.php new file mode 100644 index 000000000..12f8a928c --- /dev/null +++ b/lib/OpenCloud/CDN/Service.php @@ -0,0 +1,145 @@ +resource('Service', $id); + } + + /** + * Creates a new Service and returns it. + * + * @param array $params Service creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/CDN/USERGUIDE.md#create-a-service + * @return \OpenCloud\CDN\Resource\Service Object representing created service + */ + public function createService(array $params = array()) + { + $service = $this->service(); + $service->create($params); + return $service; + } + + /** + * Returns a Service object associated with this CDN service + * + * @param string $id ID of service to retrieve + * @return \OpenCloud\CDN\Resource\Service object + */ + public function getService($id) + { + return $this->service($id); + } + + /** + * Returns a list of services you created + * + * @param array $params + * @return \OpenCloud\Common\Collection\PaginatedIterator + */ + public function listServices(array $params = array()) + { + $url = clone $this->getUrl(); + $url->addPath(ServiceResource::resourceName())->setQuery($params); + + return $this->resourceList('Service', $url); + } + + /** + * Returns a Flavor object associated with this CDN service + * + * @param string $id ID of flavor to retrieve + * @return \OpenCloud\CDN\Resource\Flavor object + */ + public function flavor($id = null) + { + return $this->resource('Flavor', $id); + } + + /** + * Creates a new Flavor and returns it. + * + * @param array $params Flavor creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/CDN/USERGUIDE.md#create-a-flavor + * @return \OpenCloud\CDN\Resource\Flavor Object representing created flavor + */ + public function createFlavor(array $params = array()) + { + $flavor = $this->flavor(); + $flavor->create($params); + return $flavor; + } + + /** + * Returns a Flavor object associated with this CDN service + * + * @param string $id ID of flavor to retrieve + * @return \OpenCloud\CDN\Resource\Flavor object + */ + public function getFlavor($id) + { + return $this->flavor($id); + } + + /** + * Returns a list of flavors you created + * + * @param array $params + * @return \OpenCloud\Common\Collection\PaginatedIterator + */ + public function listFlavors(array $params = array()) + { + $url = clone $this->getUrl(); + $url->addPath(Flavor::resourceName())->setQuery($params); + + return $this->resourceList('Flavor', $url); + } + + /** + * Return namespaces. + * + * @return array + */ + public function namespaces() + { + return array(); + } +} diff --git a/lib/OpenCloud/OpenStack.php b/lib/OpenCloud/OpenStack.php index 25e576959..6bc6eeba1 100644 --- a/lib/OpenCloud/OpenStack.php +++ b/lib/OpenCloud/OpenStack.php @@ -566,4 +566,22 @@ public function networkingService($name = null, $region = null, $urltype = null) 'urlType' => $urltype )); } + + /** + * Creates a new CDN (Poppy) service object + * + * @param string $name The name of the service as it appears in the Catalog + * @param string $region The region (DFW, IAD, ORD, LON, SYD) + * @param string $urltype The URL type ("publicURL" or "internalURL") + * @return \OpenCloud\Cdn\Service + * @codeCoverageIgnore + */ + public function cdnService($name = null, $region = null, $urltype = null) + { + return ServiceBuilder::factory($this, 'OpenCloud\CDN\Service', array( + 'name' => $name, + 'region' => $region, + 'urlType' => $urltype + )); + } } diff --git a/lib/OpenCloud/Rackspace.php b/lib/OpenCloud/Rackspace.php index 8480a0d71..40473a4b0 100644 --- a/lib/OpenCloud/Rackspace.php +++ b/lib/OpenCloud/Rackspace.php @@ -174,4 +174,23 @@ public function queuesService($name = null, $region = null, $urltype = null) 'urlType' => $urltype )); } + + /** + * Creates a new CDN (Rackspace CDN) service object + * + * @param string $name The name of the service as it appears in the Catalog + * @param string $region The region (DFW, IAD, ORD, LON, SYD) + * @param string $urltype The URL type ("publicURL" or "internalURL") + * @return \OpenCloud\Cdn\Service + * @codeCoverageIgnore + */ + public function cdnService($name = null, $region = null, $urltype = null) + { + return ServiceBuilder::factory($this, 'OpenCloud\CDN\Service', array( + 'name' => $name, + 'type' => 'rax:cdn', + 'region' => $region, + 'urlType' => $urltype + )); + } } diff --git a/tests/OpenCloud/Tests/CDN/CDNTestCase.php b/tests/OpenCloud/Tests/CDN/CDNTestCase.php new file mode 100644 index 000000000..4f07d58f4 --- /dev/null +++ b/tests/OpenCloud/Tests/CDN/CDNTestCase.php @@ -0,0 +1,49 @@ +service = $this->getClient()->cdnService(); + + $this->addMockSubscriber($this->makeResponse('{"name":"mywebsite.com","domains":[{"domain":"blog.mywebsite.com"}],"origins":[{"origin":"mywebsite.com","port":80,"ssl":false},{"origin":"77.66.55.44","port":80,"ssl":false,"rules":[{"name":"videos","request_url":"^/videos/*.m3u"}]}],"caching":[{"name":"default","ttl":3600},{"name":"home","ttl":17200,"rules":[{"name":"index","request_url":"/index.htm"}]},{"name":"images","ttl":12800,"rules":[{"name":"images","request_url":"*.png"}]}],"restrictions":[{"name":"website only","rules":[{"name":"mywebsite.com","http_host":"www.mywebsite.com"}]}],"flavor_id":"cdn","status":"deployed","links":[{"href":"https://global.cdn.api.rackspacecloud.com/v1.0/services/mywebsite.com","rel":"self"},{"href":"mywebsite.com","rel":"access_url"}]}')); + $this->serviceResource = $this->service->getService('mywebsite.com'); + } + + protected function assertIsService($object) + { + $this->assertInstanceOf('OpenCloud\CDN\Service', $object); + } + + protected function assertIsServiceResource($object) + { + $this->assertInstanceOf('OpenCloud\CDN\Resource\Service', $object); + } + + protected function assertIsFlavorResource($object) + { + $this->assertInstanceOf('OpenCloud\CDN\Resource\Flavor', $object); + } +} diff --git a/tests/OpenCloud/Tests/CDN/Resource/ServiceTest.php b/tests/OpenCloud/Tests/CDN/Resource/ServiceTest.php new file mode 100644 index 000000000..37bd61a50 --- /dev/null +++ b/tests/OpenCloud/Tests/CDN/Resource/ServiceTest.php @@ -0,0 +1,40 @@ +addMockSubscriber($this->makeResponse(null, 202)); + + $actualResponse = $this->serviceResource->purgeAssets('/images/foo.png'); + $this->assertEquals(202, $actualResponse->getStatusCode()); + } + + public function testPurgeAllAssets() + { + $this->addMockSubscriber($this->makeResponse(null, 202)); + + $actualResponse = $this->serviceResource->purgeAssets(); + $this->assertEquals(202, $actualResponse->getStatusCode()); + } +} diff --git a/tests/OpenCloud/Tests/CDN/ServiceTest.php b/tests/OpenCloud/Tests/CDN/ServiceTest.php new file mode 100644 index 000000000..e24298e00 --- /dev/null +++ b/tests/OpenCloud/Tests/CDN/ServiceTest.php @@ -0,0 +1,82 @@ +getClient()->cdnService(); + $this->assertIsService($service); + } + + public function testCreateService() + { + $this->assertIsServiceResource($this->service->createService(array( + 'name' => 'mywebsite' + ))); + } + + public function testListServices() + { + $this->addMockSubscriber($this->makeResponse('{"links":[{"rel":"next","href":"https://global.cdn.api.rackspacecloud.com/v1.0/services?marker=www.myothersite.com&limit=20"}],"services":[{"name":"mywebsite.com","domains":[{"domain":"www.mywebsite.com"}],"origins":[{"origin":"mywebsite.com","port":80,"ssl":false}],"caching":[{"name":"default","ttl":3600},{"name":"home","ttl":17200,"rules":[{"name":"index","request_url":"/index.htm"}]},{"name":"images","ttl":12800,"rules":[{"name":"images","request_url":"*.png"}]}],"restrictions":[{"name":"website only","rules":[{"name":"mywebsite.com","http_host":"www.mywebsite.com"}]}],"flavor_id":"cdn","status":"deployed","links":[{"href":"https://global.cdn.api.rackspacecloud.com/v1.0/services/mywebsite.com","rel":"self"},{"href":"mywebsite.com","rel":"access_url"}]},{"name":"myothersite.com","domains":[{"domain":"www.myothersite.com"}],"origins":[{"origin":"44.33.22.11","port":80,"ssl":false},{"origin":"77.66.55.44","port":80,"ssl":false,"rules":[{"name":"videos","request_url":"^/videos/*.m3u"}]}],"caching":[{"name":"default","ttl":3600}],"restrictions":[{}],"flavor_id":"cdn","status":"deployed","links":[{"href":"https://global.cdn.api.rackspacecloud.com/v1.0/services/myothersite.com","rel":"self"},{"href":"myothersite.com","rel":"access_url"}]}]}')); + + $services = $this->service->listServices(); + $this->isCollection($services); + $this->assertIsServiceResource($services->getElement(0)); + } + + public function testGetService() + { + $this->addMockSubscriber($this->makeResponse('{"name":"mywebsite.com","domains":[{"domain":"blog.mywebsite.com"}],"origins":[{"origin":"mywebsite.com","port":80,"ssl":false},{"origin":"77.66.55.44","port":80,"ssl":false,"rules":[{"name":"videos","request_url":"^/videos/*.m3u"}]}],"caching":[{"name":"default","ttl":3600},{"name":"home","ttl":17200,"rules":[{"name":"index","request_url":"/index.htm"}]},{"name":"images","ttl":12800,"rules":[{"name":"images","request_url":"*.png"}]}],"restrictions":[{"name":"website only","rules":[{"name":"mywebsite.com","http_host":"www.mywebsite.com"}]}],"flavor_id":"cdn","status":"deployed","links":[{"href":"https://global.cdn.api.rackspacecloud.com/v1.0/services/mywebsite.com","rel":"self"},{"href":"mywebsite.com","rel":"access_url"}]}')); + + $service = $this->service->getService('mywebsite.com'); + $this->assertIsServiceResource($service); + $this->assertEquals('mywebsite.com', $service->getName()); + $this->assertEquals('cdn', $service->getFlavorId()); + } + + public function testCreateFlavor() + { + $this->assertIsFlavorResource($this->service->createFlavor(array( + 'id' => 'asia' + ))); + } + + public function testListFlavors() + { + $this->addMockSubscriber($this->makeResponse('{"flavors":[{"id":"cdn","limits":{"origins":{"min":1,"max":5},"domains":{"min":1,"max":5},"caching":{"min":3600,"max":604800,"incr":300}},"providers":[{"provider":"akamai","links":[{"href":"http://www.akamai.com","rel":"provider_url"}]}],"links":[{"href":"https://global.cdn.api.rackspacecloud.com/v1.0/flavors/cdn","rel":"self"}]} ]}')); + + $flavors = $this->service->listFlavors(); + $this->isCollection($flavors); + $this->assertIsFlavorResource($flavors->getElement(0)); + } + + public function testGetFlavor() + { + $this->addMockSubscriber($this->makeResponse('{"id":"cdn","providers":[{"provider":"akamai","links":[{"href":"http://www.akamai.com","rel":"provider_url"}]}],"links":[{"href":"http://preview.cdn.api.rackspacecloud.com/v1.0/flavors/cdn","rel":"self"}]}')); + + $flavor = $this->service->getFlavor('cdn'); + $this->assertIsFlavorResource($flavor); + $this->assertEquals('cdn', $flavor->getId()); + $this->assertEquals('akamai', $flavor->getProviders()[0]->provider); + } +} diff --git a/tests/OpenCloud/Tests/_response/Auth.resp b/tests/OpenCloud/Tests/_response/Auth.resp index 518a634e7..add5174dc 100644 --- a/tests/OpenCloud/Tests/_response/Auth.resp +++ b/tests/OpenCloud/Tests/_response/Auth.resp @@ -364,6 +364,17 @@ Front-End-Https: on } ], "type": "network" + }, + { + "name": "rackCDN", + "endpoints": [ + { + "tenantId": "123456", + "publicURL": "https://global.cdn.api.rackspacecloud.com/v1.0/123456", + "internalURL": "https://global.cdn.api.rackspacecloud.com/v1.0/123456" + } + ], + "type": "rax:cdn" } ], "token": { From f156f4774c05d58993279532174e9f3a64cfb8fa Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 19 Dec 2014 12:50:40 +0530 Subject: [PATCH 005/181] Whitespace fixes. --- lib/OpenCloud/CDN/Resource/Flavor.php | 2 +- lib/OpenCloud/CDN/Resource/Service.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/OpenCloud/CDN/Resource/Flavor.php b/lib/OpenCloud/CDN/Resource/Flavor.php index 28bf8c1b8..d8cdbad6a 100644 --- a/lib/OpenCloud/CDN/Resource/Flavor.php +++ b/lib/OpenCloud/CDN/Resource/Flavor.php @@ -22,7 +22,7 @@ /** * A service represents your application that has its content cached to the * edge nodes. - * + * * @package OpenCloud\CDN\Resource */ class Flavor extends PersistentResource diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index 00348129b..521d2921a 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -22,7 +22,7 @@ /** * A service represents your application that has its content cached to the * edge nodes. - * + * * @package OpenCloud\CDN\Resource */ class Service extends PersistentResource From bde9c6606120ac60677b7cecb09ca1bbc31e5b1a Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 19 Dec 2014 13:06:07 +0530 Subject: [PATCH 006/181] Fixing docblock for Flavor class. --- lib/OpenCloud/CDN/Resource/Flavor.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/OpenCloud/CDN/Resource/Flavor.php b/lib/OpenCloud/CDN/Resource/Flavor.php index d8cdbad6a..31788bd40 100644 --- a/lib/OpenCloud/CDN/Resource/Flavor.php +++ b/lib/OpenCloud/CDN/Resource/Flavor.php @@ -20,8 +20,8 @@ use OpenCloud\Common\Resource\PersistentResource; /** - * A service represents your application that has its content cached to the - * edge nodes. + * A flavor is a configuration for the CDN service. A flavor enables you to + * choose from a generic setting that is powered by one or more CDN providers. * * @package OpenCloud\CDN\Resource */ From 95eada81549af52060ba5e81d6e09a4a0a5b7878 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 23 Dec 2014 08:37:36 +0530 Subject: [PATCH 007/181] Looping over object properties while changing them is a bad idea! --- lib/OpenCloud/Common/Resource/PersistentResource.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index 9ae6582e3..f769f9856 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -276,7 +276,8 @@ protected function recursivelyAliasPropertyValue($propertyValue) } } } elseif (is_object($propertyValue) && ($propertyValue instanceof \stdClass)) { - foreach ($propertyValue as $key => $subValue) { + $objectVars = get_object_vars($propertyValue); + foreach ($objectVars as $key => $subValue) { unset($propertyValue->$key); $propertyValue->{$this->getAlias($key)} = $this->recursivelyAliasPropertyValue($subValue); } From 6d65fca97fcd96298a36833bf998f27273995b38 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 23 Dec 2014 08:38:09 +0530 Subject: [PATCH 008/181] Use the maximum pagination limit supported by the API, unless client provides a lower one. --- lib/OpenCloud/CDN/Service.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/OpenCloud/CDN/Service.php b/lib/OpenCloud/CDN/Service.php index 12f8a928c..fafc63d6e 100644 --- a/lib/OpenCloud/CDN/Service.php +++ b/lib/OpenCloud/CDN/Service.php @@ -32,6 +32,7 @@ class Service extends CatalogService const SUPPORTED_VERSION = 'v1.0'; const DEFAULT_TYPE = 'cdn'; const DEFAULT_NAME = 'rackCDN'; + const MAX_LIMIT = 20; protected $regionless = true; @@ -78,6 +79,8 @@ public function getService($id) */ public function listServices(array $params = array()) { + $params['limit'] = isset($params['limit']) && $params['limit'] <= self::MAX_LIMIT ?: self::MAX_LIMIT; + $url = clone $this->getUrl(); $url->addPath(ServiceResource::resourceName())->setQuery($params); From f963aefddf2a5ce733aa70ba62cb59fdc293e891 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 23 Dec 2014 08:39:29 +0530 Subject: [PATCH 009/181] Do not use the top-level property in the create JSON. --- lib/OpenCloud/CDN/Resource/Flavor.php | 6 ++++++ lib/OpenCloud/CDN/Resource/Service.php | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/lib/OpenCloud/CDN/Resource/Flavor.php b/lib/OpenCloud/CDN/Resource/Flavor.php index 31788bd40..140516d65 100644 --- a/lib/OpenCloud/CDN/Resource/Flavor.php +++ b/lib/OpenCloud/CDN/Resource/Flavor.php @@ -44,4 +44,10 @@ public function update($params = array()) { return $this->noUpdate(); } + + protected function createJson() + { + $createJson = parent::createJson(); + return $createJson->{self::$json_name}; + } } diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index 521d2921a..98ce5a2dc 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -87,4 +87,10 @@ protected function primaryKeyField() { return 'name'; } + + protected function createJson() + { + $createJson = parent::createJson(); + return $createJson->{self::$json_name}; + } } From 020f7b3fc33cf448185b4b5af23720d5148c20e9 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 23 Dec 2014 08:43:17 +0530 Subject: [PATCH 010/181] Adding smoke tests for CDN. --- tests/OpenCloud/Smoke/Runner.php | 1 + tests/OpenCloud/Smoke/Unit/CDN.php | 87 ++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 tests/OpenCloud/Smoke/Unit/CDN.php diff --git a/tests/OpenCloud/Smoke/Runner.php b/tests/OpenCloud/Smoke/Runner.php index d1925ba83..57dc8852a 100644 --- a/tests/OpenCloud/Smoke/Runner.php +++ b/tests/OpenCloud/Smoke/Runner.php @@ -37,6 +37,7 @@ class Runner 'Autoscale', 'Compute', 'CloudMonitoring', + 'CDN', 'DNS', 'Database', 'Identity', diff --git a/tests/OpenCloud/Smoke/Unit/CDN.php b/tests/OpenCloud/Smoke/Unit/CDN.php new file mode 100644 index 000000000..7fba1cb6b --- /dev/null +++ b/tests/OpenCloud/Smoke/Unit/CDN.php @@ -0,0 +1,87 @@ +getConnection()->cdnService(); + // TODO: Remove shim below to replace prod with preview endpoint + $service->getEndpoint()->getPublicUrl()->setHost('preview.cdn.api.rackspacecloud.com'); + return $service; + + } + + public function main() + { + $this->step('List flavors'); + $flavors = $this->getService()->listFlavors(); + $this->stepInfo('%-40s | %s', 'Flavor ID', 'Number of providers'); + $this->stepInfo('%-40s | %s', str_repeat('-', 40), str_repeat('-', 40)); + foreach ($flavors as $flavor) { + $this->stepInfo('%-40s | %d', $flavor->getId(), count($flavor->getProviders())); + } + + $this->step('Create service'); + $createdService = $this->getService()->createService(array( + 'name' => 'php-opencloud.com', + 'domains' => array( + array( 'domain' => 'php-opencloud.com' ), + array( 'domain' => 'www.php-opencloud.com' ) + ), + 'origins' => array( + array( 'origin' => 'origin.php-opencloud.com' ) + ), + 'flavorId' => 'cdn' + )); + $this->stepInfo('Service name: ' . $createdService->getName()); + + $this->step('List services'); + $services = $this->getService()->listServices(); + $this->stepInfo('%-40s | %s', 'Service Name', 'Number of domains'); + $this->stepInfo('%-40s | %s', str_repeat('-', 40), str_repeat('-', 40)); + foreach ($services as $service) { + $this->stepInfo('%-40s | %d', $service->getName(), count($service->getDomains())); + } + + $this->step('Get service'); + $service = $this->getService()->getService('php-opencloud.com'); + $this->stepInfo('Service name: ' . $service->getName()); + $this->stepInfo('Status: ' . $service->getStatus()); + $this->stepInfo('Origin: ' . $service->getOrigins()[0]->origin); + + $this->step('Update service'); + $service->update(array( + 'origins' => array( + array( 'origin' => 'updated-origin.php-opencloud.com' ) + ) + )); + + $this->step('Purge ALL cached service assets'); + $service->purgeAssets(); + + $this->step('Delete service'); + $createdService->delete(); + } + + public function teardown() + { + } +} \ No newline at end of file From 1b0eef9c91cadce71fb020b1a0e6f7047db1cc2b Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 23 Dec 2014 08:43:55 +0530 Subject: [PATCH 011/181] Adding code samples. --- samples/CDN/create-flavor.php | 47 +++++++++++++++++++++ samples/CDN/create-service.php | 47 +++++++++++++++++++++ samples/CDN/delete-flavor.php | 36 ++++++++++++++++ samples/CDN/delete-service.php | 36 ++++++++++++++++ samples/CDN/get-flavor.php | 34 +++++++++++++++ samples/CDN/get-service.php | 34 +++++++++++++++ samples/CDN/list-flavors.php | 36 ++++++++++++++++ samples/CDN/list-services.php | 36 ++++++++++++++++ samples/CDN/purge-cached-service-asset.php | 36 ++++++++++++++++ samples/CDN/purge-cached-service-assets.php | 36 ++++++++++++++++ samples/CDN/update-service.php | 44 +++++++++++++++++++ 11 files changed, 422 insertions(+) create mode 100644 samples/CDN/create-flavor.php create mode 100644 samples/CDN/create-service.php create mode 100644 samples/CDN/delete-flavor.php create mode 100644 samples/CDN/delete-service.php create mode 100644 samples/CDN/get-flavor.php create mode 100644 samples/CDN/get-service.php create mode 100644 samples/CDN/list-flavors.php create mode 100644 samples/CDN/list-services.php create mode 100644 samples/CDN/purge-cached-service-asset.php create mode 100644 samples/CDN/purge-cached-service-assets.php create mode 100644 samples/CDN/update-service.php diff --git a/samples/CDN/create-flavor.php b/samples/CDN/create-flavor.php new file mode 100644 index 000000000..c9811cf85 --- /dev/null +++ b/samples/CDN/create-flavor.php @@ -0,0 +1,47 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Create flavor. +$flavor = $cdnFlavor->createFlavor(array( + 'id' => '{id}', + 'providers' => array( + array( + 'provider' => 'akamai', + 'links' => array( + array( + 'rel' => 'provider_url', + 'href' => 'http://www.akamai.com' + ) + ) + ) + ) +)); +/** @var $flavor OpenCloud\CDN\Resource\Flavor **/ diff --git a/samples/CDN/create-service.php b/samples/CDN/create-service.php new file mode 100644 index 000000000..2df1f5c5e --- /dev/null +++ b/samples/CDN/create-service.php @@ -0,0 +1,47 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Create service. +$service = $cdnService->createService(array( + 'name' => '{name}', + 'domains' => array( + array( + 'domain' => '{domain name}' + ) + ), + 'origins' => array( + array( + 'origin' => '{origin address}' + ) + ), + 'flavorId' => '{flavor ID}' +)); +/** @var $service OpenCloud\CDN\Resource\Service **/ diff --git a/samples/CDN/delete-flavor.php b/samples/CDN/delete-flavor.php new file mode 100644 index 000000000..760a0306b --- /dev/null +++ b/samples/CDN/delete-flavor.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get flavor. +$flavor = $cdnFlavor->getFlavors('{id}'); + +// 4. Delete it. +$flavor->delete(); diff --git a/samples/CDN/delete-service.php b/samples/CDN/delete-service.php new file mode 100644 index 000000000..345479084 --- /dev/null +++ b/samples/CDN/delete-service.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get service. +$service = $cdnService->getServices('{name}'); + +// 4. Delete it. +$service->delete(); diff --git a/samples/CDN/get-flavor.php b/samples/CDN/get-flavor.php new file mode 100644 index 000000000..e63ffcc29 --- /dev/null +++ b/samples/CDN/get-flavor.php @@ -0,0 +1,34 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get flavor. +$flavor = $cdnService->getFlavor('{flavor ID}'); +/** @var $flavor OpenCloud\CDN\Resource\Flavor **/ diff --git a/samples/CDN/get-service.php b/samples/CDN/get-service.php new file mode 100644 index 000000000..7a4a72dae --- /dev/null +++ b/samples/CDN/get-service.php @@ -0,0 +1,34 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get service. +$service = $cdnService->getService('{name}'); +/** @var $service OpenCloud\CDN\Resource\Service **/ diff --git a/samples/CDN/list-flavors.php b/samples/CDN/list-flavors.php new file mode 100644 index 000000000..8ddf9c4ce --- /dev/null +++ b/samples/CDN/list-flavors.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get flavor list. +$flavors = $cdnService->listFlavors(); +foreach ($flavors as $flavor) { + /** @var $flavor OpenCloud\CDN\Resource\Flavor **/ +} diff --git a/samples/CDN/list-services.php b/samples/CDN/list-services.php new file mode 100644 index 000000000..67f5d63a4 --- /dev/null +++ b/samples/CDN/list-services.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get service list. +$services = $cdnService->listServices(); +foreach ($services as $service) { + /** @var $service OpenCloud\CDN\Resource\Service **/ +} diff --git a/samples/CDN/purge-cached-service-asset.php b/samples/CDN/purge-cached-service-asset.php new file mode 100644 index 000000000..6d5e83c5c --- /dev/null +++ b/samples/CDN/purge-cached-service-asset.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get service. +$service = $cdnService->getServices('{name}'); + +// 4. Purge a specific asset belonging to service. +$service->purgeAsset('{asset URL}'); diff --git a/samples/CDN/purge-cached-service-assets.php b/samples/CDN/purge-cached-service-assets.php new file mode 100644 index 000000000..0d032c89c --- /dev/null +++ b/samples/CDN/purge-cached-service-assets.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get service. +$service = $cdnService->getServices('{name}'); + +// 4. Purge all assets belonging to service. +$service->purgeAssets(); diff --git a/samples/CDN/update-service.php b/samples/CDN/update-service.php new file mode 100644 index 000000000..13b34b7bf --- /dev/null +++ b/samples/CDN/update-service.php @@ -0,0 +1,44 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an CDN service object from the client. +$cdnService = $client->cdnService(); + +// 3. Get service. +$service = $cdnService->getService('{name}'); + +// 4. Update it. +$service->update(array( + 'origins' => array( + array( + 'origin' => '44.33.22.11', + 'port' => 80, + 'ssl' => false + ) + ) +)); From 07d62a0fd6bf990e5db578ed6db07821fafa19fb Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 08:46:03 +0530 Subject: [PATCH 012/181] Adding Getting Started Guide for CDN service. --- docs/userguide/CDN/README.md | 95 ++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 docs/userguide/CDN/README.md diff --git a/docs/userguide/CDN/README.md b/docs/userguide/CDN/README.md new file mode 100644 index 000000000..76ba95735 --- /dev/null +++ b/docs/userguide/CDN/README.md @@ -0,0 +1,95 @@ +# CDN + +**CDN** is a service that you can use to manage your CDN-enabled domains and the origins and assets associated with those domains. + +## Concepts + +To use the CDN service effectively, you should understand the following key concepts: + +* **Content delivery network**: A content delivery network (CDN) is a system of multiple computers that contains copies of data stored at various network nodes. A CDN is designed to improve performance of publicly distributed assets. Assets can be anything from website content, to web application components, to media such as videos, ads, and interactive experiences.  CDNs decrease the load time of these assets by caching them on edge servers, also called points of presence (PoPs).  Edge servers are distributed around the globe, meaning requests only travel to a local location to grab assets, rather than to and from a data center based far from the end user. + +* **Edge node**: CDN providers have many points of presence (PoP) servers around the world. These servers are known as edge nodes. These edge nodes cache the content and serve it directly to customers, thus reducing transit time to a customers location. + +* **Edge server**: An edge server is the same as an edge node. + +* **Origin**: An origin is an address (IP or domain) from which the CDN provider pulls content. A service can have multiple origins. + +* **Flavor**: A flavor is a configuration option. A flavor enables you to choose from a generic setting that is powered by one or more CDN providers. + +* **Service**: A service represents your application that has its content cached to the edge nodes. + +* **Status**: The status indicates the current state of the service. The time it takes for a service configuration to be distributed amongst a CDN provider cache can vary. + +* **Purge**: Purging removes content from the edge servers - thus invalidating the content - so that it can be refreshed from your origin servers. + +* **Caching rule**: A caching rule provides you with fine-grained control over the time-to-live (TTL) of an object. When the TTL expires for an object, the edge node pulls the object from the origin again. + +* **Restriction**: A restriction enables you to define rules about who can or cannot access content from the cache. Examples of a restriction are allowing requests only from certain domains, geographies, or IP addresses. + +## Getting started + +### 1. Instantiate an OpenStack or Rackspace client. + +To use the CDN service, you must first instantiate a `OpenStack` or `Rackspace` client object. + +* If you are working with an OpenStack cloud, instantiate an `OpenCloud\OpenStack` client as follows: + + ```php + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'password' => '' + )); + ``` + +* If you are working with the Rackspace cloud, instantiate a `OpenCloud\Rackspace` client as follows: + + ```php + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + ``` + +### 2. Obtain a CDN service object from the client. +All CDN operations are done via an _CDN service object_. To +instantiate this object, call the `cdnService` method on the `$client` +object. This method takes one argument: + +| Position | Description | Data type | Required? | Default value | Example value | +| -------- | ----------- | ----------| --------- | ------------- | ------------- | +| 1 | Name of the service, as it appears in the service catalog | String | No | `null`; automatically determined when possible | `rackCDN` | + + +```php +$cdnService = $client->cdnService(); +``` + +### 3. Create a service. +```php +$service = $cdnService->createService(array( + 'name' => 'acme_site', + 'domains' => array( + array( + 'domain' => 'www.acme.com' + ), + array( + 'domain' => 'acme.com' + ) + ), + 'origins' => array( + array( + 'origin' => 'origin.acme.com' + ) + ), + 'flavorId' => 'cdn' +));``` + +[ [Get the executable PHP script for this example](/samples/CDN/create-cdn.php) ] + +## Next steps + +Once you have created a service, there is more you can do with it. See [complete user guide for CDN](USERGUIDE.md). From 8f54c4eafd302b678873b28b67914adf25f9b7c5 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 09:37:11 +0530 Subject: [PATCH 013/181] Adding another property alias. --- lib/OpenCloud/CDN/Resource/Service.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index 98ce5a2dc..444266f12 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -42,7 +42,8 @@ class Service extends PersistentResource protected $links; protected $aliases = array( - 'flavor_id' => 'flavorId' + 'flavor_id' => 'flavorId', + 'http_host' => 'httpHost' ); protected $createKeys = array( From 260f68f3b1a89f79591b09ff81a4fe7747897518 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 09:38:21 +0530 Subject: [PATCH 014/181] Clarifying definition. --- docs/userguide/CDN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/README.md b/docs/userguide/CDN/README.md index 76ba95735..6a7fc864f 100644 --- a/docs/userguide/CDN/README.md +++ b/docs/userguide/CDN/README.md @@ -16,7 +16,7 @@ To use the CDN service effectively, you should understand the following key conc * **Flavor**: A flavor is a configuration option. A flavor enables you to choose from a generic setting that is powered by one or more CDN providers. -* **Service**: A service represents your application that has its content cached to the edge nodes. +* **Service**: A service represents your web application that has its content cached to the edge nodes. * **Status**: The status indicates the current state of the service. The time it takes for a service configuration to be distributed amongst a CDN provider cache can vary. From 038e2da00a463a158bac036bc893fb248f65c7ce Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 09:38:42 +0530 Subject: [PATCH 015/181] Disambiguating "service" by providing additional context. --- docs/userguide/CDN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/README.md b/docs/userguide/CDN/README.md index 6a7fc864f..04ce14bc7 100644 --- a/docs/userguide/CDN/README.md +++ b/docs/userguide/CDN/README.md @@ -68,7 +68,7 @@ object. This method takes one argument: $cdnService = $client->cdnService(); ``` -### 3. Create a service. +### 3. Create a service (to represent your web application). ```php $service = $cdnService->createService(array( 'name' => 'acme_site', From f525941e65d71f71528aa98445ca6f22e02d57e9 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 09:39:17 +0530 Subject: [PATCH 016/181] Fixing link. --- docs/userguide/CDN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/README.md b/docs/userguide/CDN/README.md index 04ce14bc7..ba959ce11 100644 --- a/docs/userguide/CDN/README.md +++ b/docs/userguide/CDN/README.md @@ -88,7 +88,7 @@ $service = $cdnService->createService(array( 'flavorId' => 'cdn' ));``` -[ [Get the executable PHP script for this example](/samples/CDN/create-cdn.php) ] +[ [Get the executable PHP script for this example](/samples/CDN/create-service.php) ] ## Next steps From 157ea27bf0b3f3f95ffee62caa1d1e9479476d91 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 09:39:38 +0530 Subject: [PATCH 017/181] Adding Complete User Guide for CDN service. --- docs/userguide/CDN/USERGUIDE.md | 264 ++++++++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 docs/userguide/CDN/USERGUIDE.md diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md new file mode 100644 index 000000000..8c0abb7d4 --- /dev/null +++ b/docs/userguide/CDN/USERGUIDE.md @@ -0,0 +1,264 @@ +# Complete User Guide for the CDN Service + +CDN is a service that you can use to manage your CDN-enabled domains and the origins and assets associated with those domains. + +## Table of contents + * [Concepts](#concepts) + * [Prerequisites](#prerequisites) + * [Client](#client) + * [CDN service](#cdn-service) + * [Services](#services) + * [Create a service](#create-a-service-to-represent-your-web-application) + * [List Services](#list-Services) + * [Get a service](#get-a-service) + * [Purge cached service assets](#purge-cached-service-assets) + * [Update a service](#update-a-service) + * [Delete a service](#delete-a-service) + * [Flavors](#flavors) + * [Create a flavor](#create-a-flavor) + * [List flavors](#list-flavors) + * [Get a flavor](#get-a-flavor) + * [Delete a flavor](#delete-a-flavor) + +## Concepts + +To use the CDN service effectively, you should understand the following +key concepts: + +* **Content delivery service**: A content delivery service (CDN) is a system of multiple computers that contains copies of data stored at various service nodes. A CDN is designed to improve performance of publicly distributed assets. Assets can be anything from website content, to web application components, to media such as videos, ads, and interactive experiences.  CDNs decrease the load time of these assets by caching them on edge servers, also called points of presence (PoPs).  Edge servers are distributed around the globe, meaning requests only travel to a local location to grab assets, rather than to and from a data center based far from the end user. + +* **Edge node**: CDN providers have many points of presence (PoP) servers around the world. These servers are known as edge nodes. These edge nodes cache the content and serve it directly to customers, thus reducing transit time to a customers location. + +* **Edge server**: An edge server is the same as an edge node. + +* **Origin**: An origin is an address (IP or domain) from which the CDN provider pulls content. A service can have multiple origins. + +* **Flavor**: A flavor is a configuration option. A flavor enables you to choose from a generic setting that is powered by one or more CDN providers. + +* **Service**: A service represents your web application that has its content cached to the edge nodes. + +* **Status**: The status indicates the current state of the service. The time it takes for a service configuration to be distributed amongst a CDN provider cache can vary. + +* **Purge**: Purging removes content from the edge servers - thus invalidating the content - so that it can be refreshed from your origin servers. + +* **Caching rule**: A caching rule provides you with fine-grained control over the time-to-live (TTL) of an object. When the TTL expires for an object, the edge node pulls the object from the origin again. + +* **Restriction**: A restriction enables you to define rules about who can or cannot access content from the cache. Examples of a restriction are allowing requests only from certain domains, geographies, or IP addresses. + + +## Prerequisites + +### Client +To use the CDN service, you must first instantiate a `OpenStack` or `Rackspace` client object. + +* If you are working with an OpenStack cloud, instantiate an `OpenCloud\OpenStack` client as follows: + + ```php + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'password' => '' + )); + ``` + +* If you are working with the Rackspace cloud, instantiate a `OpenCloud\Rackspace` client as follows: + + ```php + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + ``` + +### CDN service + +All CDN operations are done via an _CDN service object_. To +instantiate this object, call the `cdnService` method on the `$client` +object. This method takes one argument: + +| Position | Description | Data type | Required? | Default value | Example value | +| -------- | ----------- | ----------| --------- | ------------- | ------------- | +| 1 | Name of the service, as it appears in the service catalog | String | No | `null`; automatically determined when possible | `rackCDN` | + + +```php +$cdnService = $client->cdnService(); +``` + +## Services + +A service represents your web application that has its content cached to the edge nodes. + +### Create a service (to represent your web application) + + +This operation takes one parameter, an associative array, with the following keys: + +| Name | Description | Data type | Required? | Default value | Example value | +| ---- | ----------- | --------- | --------- | ------------- | ------------- | +| `name` | A human-readable name for the service. This name must be unique. | String | No | `null` | `acme_site` | +| `domains` | An array of associative arrays, each specifying a domain name for your service. | Array of associative arrays | Yes | `null` | `array( array( 'domain' => 'www.acme.com' ), array ( 'domain' => 'acme.com' ) )` | +| `origins` | An array of associative arrays, each specifying an origin server for your service. The `port`, `ssl`, and `rules` elements for each origin server are optional. | Array of associative arrays | Yes | `null` | `array( array( 'origin' => 'origin.acme.com', 'port' => 80, 'ssl' => false, 'rules' => array() ) )` | +| `flavorId` | The flavor used to configure this service. Use the [list flavors](#list-flavors) operation to retrieve a list of all available flavors. | String | Yes| `null` | `cdn` | +| `restrictions` | An array of associative arrays, each specifying a restriction for who can or cannot access content from the CDN cache. | Array of associative arrays | No | `null` | `array( array( 'name' => 'website only', 'rules' => array( array( 'name' => 'mywebsite.com', 'httpHost' => 'www.mywebsite.com' ) ) ) )` | +| `caching` | An array of associative arrays, each specifying a caching rule for your service's assets. | No | `null` | `array( array( 'name' => 'default', 'ttl' => 3600 ) )` | + +You can create a service as shown in the following example: + +```php +$service = $cdnService->createService(array( + 'name' => 'acme_site', + 'domains' => array( + array( + 'domain' => 'www.acme.com' + ), + array( + 'domain' => 'acme.com' + ) + ), + 'origins' => array( + array( + 'origin' => 'origin.acme.com' + ) + ), + 'flavorId' => 'cdn' +));``` + +[ [Get the executable PHP script for this example](/samples/CDN/create-service.php) ] + +### List Services + +You can list all the services you have created as shown in the following example: + +```php +$services = $cdnService->listServices(); +foreach ($services as $service) { + /** @var $service OpenCloud\CDN\Resource\Service **/ +} +``` + +[ [Get the executable PHP script for this example](/samples/CDN/list-services.php) ] + +### Get a service + +You can retrieve a specific service by using that service's name, as shown in the following example: + +```php +$service = $cdnService->getservice('acme_site'); +/** @var $service OpenCloud\CDN\Resource\Service **/ +``` + +[ [Get the executable PHP script for this example](/samples/CDN/get-service.php) ] + +### Update a service + +This operation takes one parameter, an associative array, with the following keys: + +| Name | Description | Data type | Required? | Default value | Example value | +| ---- | ----------- | --------- | --------- | ------------- | ------------- | +| `domains` | An array of associative arrays, each specifying a domain name for your service. | Array of associative arrays | Yes | `null` | `array( array( 'domain' => 'www.acme.com' ), array ( 'domain' => 'acme.com' ) )` | +| `origins` | An array of associative arrays, each specifying an origin server for your service. The `port`, `ssl`, and `rules` elements for each origin server are optional. | Array of associative arrays | Yes | `null` | `array( array( 'origin' => 'origin.acme.com', 'port' => 80, 'ssl' => false, 'rules' => array() ) )` | +| `flavorId` | The flavor used to configure this service. Use the [list flavors](#list-flavors) operation to retrieve a list of all available flavors. | String | Yes| `null` | `cdn` | +| `restrictions` | An array of associative arrays, each specifying a restriction for who can or cannot access content from the CDN cache. | Array of associative arrays | No | `null` | `array( array( 'name' => 'website only', 'rules' => array( array( 'name' => 'mywebsite.com', 'httpHost' => 'www.mywebsite.com' ) ) ) )` | +| `caching` | An array of associative arrays, each specifying a caching rule for your service's assets. | No | `null` | `array( array( 'name' => 'default', 'ttl' => 3600 ) )` | + +You can update a service as shown in the following example: + +```php +$service->update(array( + 'origins' => array( + array( + 'origin' => '44.33.22.11', + 'port' => 80, + 'ssl' => false + ) + ) +)); +``` + +[ [Get the executable PHP script for this example](/samples/CDN/update-service.php) ] + +### Delete a service + +You can delete a service as shown in the following example: + +```php +$service->delete(); +``` + +[ [Get the executable PHP script for this example](/samples/CDN/delete-service.php) ] + +## Flavors + +A flavor is a configuration option. A flavor enables you to choose from a generic setting that is powered by one or more CDN providers. + +### Create a flavor + +Note: When working with the Rackspace Cloud, this operation requires the `cdn:operator` role. + +This operation takes one parameter, an associative array, with the following keys: + +| Name | Description | Data type | Required? | Default value | Example value | +| ---- | ----------- | --------- | --------- | ------------- | ------------- | +| `id` | ID of flavor. This ID must be unique. | String | Yes | `null` | `cdn` | +| `providers` | An array of associative arrays, each representing a CDN provider. | Array of associative arrays | Yes | `null` | `array( array( 'provider' => 'akamai', 'links' => array( array( 'rel' => 'provider_url', 'href' => 'http://www.akamai.com' ) ) ) )` | + +You can create a flavor as shown in the following example: + +```php +$Flavor = $CDNService->createFlavor(array( + 'id' => 'cdn', + 'providers' => array( + array( + 'name' => 'akamai', + 'links' => array( + 'rel' => 'provider_url', + 'href' => 'http://www.akamai.com' + ) + ) + ) +)); +/** @var $Flavor OpenCloud\CDN\Resource\Flavor **/ +``` + +[ [Get the executable PHP script for this example](/samples/CDN/create-flavor.php) ] + +### List flavors + +You can list all available flavors as shown in the following example: + +```php +$flavors = $cdnService->listFlavors(); +foreach ($flavors as $flavor) { + /** @var $flavor OpenCloud\CDN\Resource\Flavor **/ +} +``` + +[ [Get the executable PHP script for this example](/samples/CDN/list-flavors.php) ] + +### Get a flavor + +You can retrieve a specific flavor by using that flavor's ID, as shown in the +following example: + +```php +$flavor = $cdnService->getFlavor('cdn'); +/** @var $flavor OpenCloud\CDN\Resource\Flavor **/ +``` + +[ [Get the executable PHP script for this example](/samples/CDN/get-flavor.php) ] + +### Delete a flavor + +Note: When working with the Rackspace Cloud, this operation requires the `cdn:operator` role. + +You can delete a flavor as shown in the following example: + +```php +$flavor->delete(); +``` + +[ [Get the executable PHP script for this example](/samples/CDN/delete-flavor.php) ] From ad715657092677debe1b6d22af15c1f736baf18c Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 11:54:27 +0530 Subject: [PATCH 018/181] Whitespace lint fixes. --- tests/OpenCloud/Smoke/Unit/CDN.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/OpenCloud/Smoke/Unit/CDN.php b/tests/OpenCloud/Smoke/Unit/CDN.php index 7fba1cb6b..e996ab3d4 100644 --- a/tests/OpenCloud/Smoke/Unit/CDN.php +++ b/tests/OpenCloud/Smoke/Unit/CDN.php @@ -16,6 +16,7 @@ */ namespace OpenCloud\Smoke\Unit; + use Guzzle\Http\Exception\ClientErrorResponseException; class CDN extends AbstractUnit implements UnitInterface @@ -26,7 +27,6 @@ public function setupService() // TODO: Remove shim below to replace prod with preview endpoint $service->getEndpoint()->getPublicUrl()->setHost('preview.cdn.api.rackspacecloud.com'); return $service; - } public function main() @@ -84,4 +84,4 @@ public function main() public function teardown() { } -} \ No newline at end of file +} From 1c59c458dd7a4ac50e01c7718ead9ab913dcd273 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 25 Dec 2014 12:10:34 +0530 Subject: [PATCH 019/181] Removing limits. --- lib/OpenCloud/CDN/Resource/Flavor.php | 2 -- tests/OpenCloud/Tests/CDN/ServiceTest.php | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/OpenCloud/CDN/Resource/Flavor.php b/lib/OpenCloud/CDN/Resource/Flavor.php index 140516d65..de13eb9f2 100644 --- a/lib/OpenCloud/CDN/Resource/Flavor.php +++ b/lib/OpenCloud/CDN/Resource/Flavor.php @@ -31,12 +31,10 @@ class Flavor extends PersistentResource protected static $json_name = 'flavor'; protected $id; - protected $limits; protected $providers; protected $createKeys = array( 'id', - 'limits', 'providers' ); diff --git a/tests/OpenCloud/Tests/CDN/ServiceTest.php b/tests/OpenCloud/Tests/CDN/ServiceTest.php index e24298e00..dba96d576 100644 --- a/tests/OpenCloud/Tests/CDN/ServiceTest.php +++ b/tests/OpenCloud/Tests/CDN/ServiceTest.php @@ -63,7 +63,7 @@ public function testCreateFlavor() public function testListFlavors() { - $this->addMockSubscriber($this->makeResponse('{"flavors":[{"id":"cdn","limits":{"origins":{"min":1,"max":5},"domains":{"min":1,"max":5},"caching":{"min":3600,"max":604800,"incr":300}},"providers":[{"provider":"akamai","links":[{"href":"http://www.akamai.com","rel":"provider_url"}]}],"links":[{"href":"https://global.cdn.api.rackspacecloud.com/v1.0/flavors/cdn","rel":"self"}]} ]}')); + $this->addMockSubscriber($this->makeResponse('{"flavors":[{"id":"cdn","providers":[{"provider":"akamai","links":[{"href":"http://www.akamai.com","rel":"provider_url"}]}],"links":[{"href":"https://global.cdn.api.rackspacecloud.com/v1.0/flavors/cdn","rel":"self"}]} ]}')); $flavors = $this->service->listFlavors(); $this->isCollection($flavors); From ffb915dcd84ad5381e654f127106e73e33eef4aa Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 03:06:05 -0800 Subject: [PATCH 020/181] Fixing formatting. --- docs/userguide/CDN/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/userguide/CDN/README.md b/docs/userguide/CDN/README.md index ba959ce11..a64cca833 100644 --- a/docs/userguide/CDN/README.md +++ b/docs/userguide/CDN/README.md @@ -86,7 +86,8 @@ $service = $cdnService->createService(array( ) ), 'flavorId' => 'cdn' -));``` +)); +``` [ [Get the executable PHP script for this example](/samples/CDN/create-service.php) ] From 92cbf9895b12fa7adb5f2d097123803ce0b8b9e4 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 03:08:06 -0800 Subject: [PATCH 021/181] Fixing typo. --- docs/userguide/CDN/USERGUIDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index 8c0abb7d4..9468f2404 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -25,7 +25,7 @@ CDN is a service that you can use to manage your CDN-enabled domains and the ori To use the CDN service effectively, you should understand the following key concepts: -* **Content delivery service**: A content delivery service (CDN) is a system of multiple computers that contains copies of data stored at various service nodes. A CDN is designed to improve performance of publicly distributed assets. Assets can be anything from website content, to web application components, to media such as videos, ads, and interactive experiences.  CDNs decrease the load time of these assets by caching them on edge servers, also called points of presence (PoPs).  Edge servers are distributed around the globe, meaning requests only travel to a local location to grab assets, rather than to and from a data center based far from the end user. +* **Content delivery network**: A content delivery network (CDN) is a system of multiple computers that contains copies of data stored at various network nodes. A CDN is designed to improve performance of publicly distributed assets. Assets can be anything from website content, to web application components, to media such as videos, ads, and interactive experiences.  CDNs decrease the load time of these assets by caching them on edge servers, also called points of presence (PoPs).  Edge servers are distributed around the globe, meaning requests only travel to a local location to grab assets, rather than to and from a data center based far from the end user. * **Edge node**: CDN providers have many points of presence (PoP) servers around the world. These servers are known as edge nodes. These edge nodes cache the content and serve it directly to customers, thus reducing transit time to a customers location. From ee471356b0af824fc772a1dcb92b4cbce528b12f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 03:37:01 -0800 Subject: [PATCH 022/181] Changing syntax to be PHP5.3-compliant. --- tests/OpenCloud/Smoke/Unit/CDN.php | 3 ++- tests/OpenCloud/Tests/CDN/ServiceTest.php | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/OpenCloud/Smoke/Unit/CDN.php b/tests/OpenCloud/Smoke/Unit/CDN.php index e996ab3d4..97921d11f 100644 --- a/tests/OpenCloud/Smoke/Unit/CDN.php +++ b/tests/OpenCloud/Smoke/Unit/CDN.php @@ -65,7 +65,8 @@ public function main() $service = $this->getService()->getService('php-opencloud.com'); $this->stepInfo('Service name: ' . $service->getName()); $this->stepInfo('Status: ' . $service->getStatus()); - $this->stepInfo('Origin: ' . $service->getOrigins()[0]->origin); + $origins = $service->getOrigins(); + $this->stepInfo('Origin: ' . $origins[0]->origin); $this->step('Update service'); $service->update(array( diff --git a/tests/OpenCloud/Tests/CDN/ServiceTest.php b/tests/OpenCloud/Tests/CDN/ServiceTest.php index dba96d576..e37be35b9 100644 --- a/tests/OpenCloud/Tests/CDN/ServiceTest.php +++ b/tests/OpenCloud/Tests/CDN/ServiceTest.php @@ -77,6 +77,8 @@ public function testGetFlavor() $flavor = $this->service->getFlavor('cdn'); $this->assertIsFlavorResource($flavor); $this->assertEquals('cdn', $flavor->getId()); - $this->assertEquals('akamai', $flavor->getProviders()[0]->provider); + + $providers = $flavor->getProviders(); + $this->assertEquals('akamai', $providers[0]->provider); } } From 5804006358b13cdf4352d37f9a0dfdc94c040c54 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 03:45:47 -0800 Subject: [PATCH 023/181] Fixing link. --- docs/userguide/CDN/USERGUIDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index 9468f2404..a2cb7fceb 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -9,7 +9,7 @@ CDN is a service that you can use to manage your CDN-enabled domains and the ori * [CDN service](#cdn-service) * [Services](#services) * [Create a service](#create-a-service-to-represent-your-web-application) - * [List Services](#list-Services) + * [List Services](#list-services) * [Get a service](#get-a-service) * [Purge cached service assets](#purge-cached-service-assets) * [Update a service](#update-a-service) From 72182f3ddb6c567a9e15cc99b4e7a6011fdaaada Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 03:55:07 -0800 Subject: [PATCH 024/181] Adding section on service assets. --- docs/userguide/CDN/USERGUIDE.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index a2cb7fceb..eaff6aea6 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -11,9 +11,11 @@ CDN is a service that you can use to manage your CDN-enabled domains and the ori * [Create a service](#create-a-service-to-represent-your-web-application) * [List Services](#list-services) * [Get a service](#get-a-service) - * [Purge cached service assets](#purge-cached-service-assets) * [Update a service](#update-a-service) * [Delete a service](#delete-a-service) + * [Service Assets](#service-assets) + * [Purge all cached service assets](#purge-all-cached-service-assets) + * [Purge a specific cached service asset](#purge-a-specific-cached-service-asset) * [Flavors](#flavors) * [Create a flavor](#create-a-flavor) * [List flavors](#list-flavors) @@ -191,6 +193,29 @@ $service->delete(); [ [Get the executable PHP script for this example](/samples/CDN/delete-service.php) ] +## Service Assets +A service will have its assets distributed and cached across a CDN's edge nodes. + +### Purge all cached service assets + +You can purge all cached assets of a service as shown in the following example: + +```php +$service->purgeAssets(); +``` + +[ [Get the executable PHP script for this example](/samples/CDN/purge-cached-service-assets.php) ] + +### Purge a specific cached service asset + +You can purge a specific asset of a service by providing its relative URL, as shown in the following example: + +```php +$service->purgeAssets('/images/logo.png'); +``` + +[ [Get the executable PHP script for this example](/samples/CDN/purge-cached-service-asset.php) ] + ## Flavors A flavor is a configuration option. A flavor enables you to choose from a generic setting that is powered by one or more CDN providers. From 8b179f62c5f108d71894a6c236d9b140f6b6a3f1 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 03:55:21 -0800 Subject: [PATCH 025/181] Fixing typo in variable name. --- docs/userguide/CDN/USERGUIDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index eaff6aea6..4760e6da0 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -234,7 +234,7 @@ This operation takes one parameter, an associative array, with the following key You can create a flavor as shown in the following example: ```php -$Flavor = $CDNService->createFlavor(array( +$flavor = $CDNService->createFlavor(array( 'id' => 'cdn', 'providers' => array( array( From 5f4976e89ab6d790bde31198d7e6e1c8036d32f5 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 03:59:04 -0800 Subject: [PATCH 026/181] Fixing case in variable names. --- docs/userguide/CDN/USERGUIDE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index 4760e6da0..de26dac3a 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -234,7 +234,7 @@ This operation takes one parameter, an associative array, with the following key You can create a flavor as shown in the following example: ```php -$flavor = $CDNService->createFlavor(array( +$flavor = $cdnService->createFlavor(array( 'id' => 'cdn', 'providers' => array( array( @@ -246,7 +246,7 @@ $flavor = $CDNService->createFlavor(array( ) ) )); -/** @var $Flavor OpenCloud\CDN\Resource\Flavor **/ +/** @var $flavor OpenCloud\CDN\Resource\Flavor **/ ``` [ [Get the executable PHP script for this example](/samples/CDN/create-flavor.php) ] From f45dc272c6997947bda9bb75884e2517a6df5b84 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 26 Dec 2014 04:00:01 -0800 Subject: [PATCH 027/181] Fixing method name. --- samples/CDN/purge-cached-service-asset.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/CDN/purge-cached-service-asset.php b/samples/CDN/purge-cached-service-asset.php index 6d5e83c5c..715a80699 100644 --- a/samples/CDN/purge-cached-service-asset.php +++ b/samples/CDN/purge-cached-service-asset.php @@ -33,4 +33,4 @@ $service = $cdnService->getServices('{name}'); // 4. Purge a specific asset belonging to service. -$service->purgeAsset('{asset URL}'); +$service->purgeAssets('{asset URL}'); From 36336cbc9662c05b2a7060b100ae1e14a99d30b2 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 30 Dec 2014 04:45:48 -0800 Subject: [PATCH 028/181] Adding support for GET / and GET /ping APIs. --- lib/OpenCloud/CDN/Service.php | 24 +++++++++++++++++++++++ tests/OpenCloud/Tests/CDN/ServiceTest.php | 17 ++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/lib/OpenCloud/CDN/Service.php b/lib/OpenCloud/CDN/Service.php index fafc63d6e..20143cc00 100644 --- a/lib/OpenCloud/CDN/Service.php +++ b/lib/OpenCloud/CDN/Service.php @@ -136,6 +136,30 @@ public function listFlavors(array $params = array()) return $this->resourceList('Flavor', $url); } + /** + * Returns the home document for the CDN service + * + * @return \stdClass home document response + */ + public function getHomeDocument() + { + $response = $this->getClient()->get($this->getUrl())->send(); + return Formatter::decode($response); + } + + /** + * Returns the ping (status) response for the CDN service + * + * @return Guzzle\Http\Message\Response + */ + public function getPing() + { + $url = clone $this->getUrl(); + $url->addPath('ping'); + + return $this->getClient()->get($url)->send(); + } + /** * Return namespaces. * diff --git a/tests/OpenCloud/Tests/CDN/ServiceTest.php b/tests/OpenCloud/Tests/CDN/ServiceTest.php index e37be35b9..b3a2bb7f7 100644 --- a/tests/OpenCloud/Tests/CDN/ServiceTest.php +++ b/tests/OpenCloud/Tests/CDN/ServiceTest.php @@ -81,4 +81,21 @@ public function testGetFlavor() $providers = $flavor->getProviders(); $this->assertEquals('akamai', $providers[0]->provider); } + + public function testGetHomeDocument() + { + $this->addMockSubscriber($this->makeResponse('{"resources":{"rel/cdn":{"href-template":"services{?marker,limit}","href-vars":{"marker":"param/marker","limit":"param/limit"},"hints":{"allow":["GET"],"formats":{"application/json":{}}}}}}')); + + $homeDocument = $this->service->getHomeDocument(); + $this->assertNotEmpty($homeDocument); + $this->assertEquals("services{?marker,limit}", $homeDocument->resources->{"rel/cdn"}->{"href-template"}); + } + + public function testGetPing() + { + $this->addMockSubscriber($this->makeResponse(null, 204)); + + $ping = $this->service->getPing(); + $this->assertEquals(204, $ping->getStatusCode()); + } } From f2fe5ab4b32cb45c3ca62ac673f1db2809bc0f64 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 30 Dec 2014 05:38:25 -0800 Subject: [PATCH 029/181] Adding errors property to Service resource. --- lib/OpenCloud/CDN/Resource/Service.php | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index 444266f12..beef278cd 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -40,6 +40,7 @@ class Service extends PersistentResource protected $flavorId; protected $status; protected $links; + protected $errors; protected $aliases = array( 'flavor_id' => 'flavorId', From 138e0962365cacf4ef40d75969f96c12dc9c986b Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 30 Dec 2014 05:39:19 -0800 Subject: [PATCH 030/181] Remove Accept request header for APIs that don't return responses. --- lib/OpenCloud/CDN/Resource/Service.php | 9 ++++++++- lib/OpenCloud/CDN/Service.php | 11 +++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index beef278cd..2823286d1 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -74,7 +74,14 @@ public function purgeAssets($assetUrl = null) $assetsUrl->setQuery(array('url' => $assetUrl)); } - return $this->getClient()->delete($assetsUrl)->send(); + $request = $this->getClient()->delete($assetsUrl); + + // This is necessary because the response does not include a body + // and fails with a 406 Not Acceptable if the default + // 'Accept: application/json' header is used in the request. + $request->removeHeader('Accept'); + + return $request->send(); } protected function assetsUrl() diff --git a/lib/OpenCloud/CDN/Service.php b/lib/OpenCloud/CDN/Service.php index 20143cc00..2fbef781c 100644 --- a/lib/OpenCloud/CDN/Service.php +++ b/lib/OpenCloud/CDN/Service.php @@ -156,8 +156,15 @@ public function getPing() { $url = clone $this->getUrl(); $url->addPath('ping'); - - return $this->getClient()->get($url)->send(); + + $request = $this->getClient()->get($url); + + // This is necessary because the response does not include a body + // and fails with a 406 Not Acceptable if the default + // 'Accept: application/json' header is used in the request. + $request->removeHeader('Accept'); + + return $request->send(); } /** From cae80de1d2a0dec9e2523a100f5e916eb45bf451 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 30 Dec 2014 05:40:25 -0800 Subject: [PATCH 031/181] Force addition of trailing slash to URL in order to make GET / work. --- lib/OpenCloud/CDN/Service.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/OpenCloud/CDN/Service.php b/lib/OpenCloud/CDN/Service.php index 2fbef781c..14f2281a7 100644 --- a/lib/OpenCloud/CDN/Service.php +++ b/lib/OpenCloud/CDN/Service.php @@ -143,8 +143,15 @@ public function listFlavors(array $params = array()) */ public function getHomeDocument() { - $response = $this->getClient()->get($this->getUrl())->send(); - return Formatter::decode($response); + $url = clone $this->getUrl(); + + // This hack is necessary otherwise Guzzle will remove the trailing + // slash from the URL and the request will fail because the service + // expects the trailing slash :( + $url->setPath($url->getPath() . '/'); + + $response = $this->getClient()->get($url)->send(); + return Formatter::decode($response); } /** From 97f8037cb0d8e971033275ca2a8f99e1014edf41 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 30 Dec 2014 05:41:14 -0800 Subject: [PATCH 032/181] Adding smoke tests for GET / and GET /ping APIs. --- tests/OpenCloud/Smoke/Unit/CDN.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/OpenCloud/Smoke/Unit/CDN.php b/tests/OpenCloud/Smoke/Unit/CDN.php index 97921d11f..59366bb93 100644 --- a/tests/OpenCloud/Smoke/Unit/CDN.php +++ b/tests/OpenCloud/Smoke/Unit/CDN.php @@ -24,13 +24,19 @@ class CDN extends AbstractUnit implements UnitInterface public function setupService() { $service = $this->getConnection()->cdnService(); - // TODO: Remove shim below to replace prod with preview endpoint - $service->getEndpoint()->getPublicUrl()->setHost('preview.cdn.api.rackspacecloud.com'); return $service; } public function main() { + $this->step('Get home document'); + $homeDocument = $this->getService()->getHomeDocument(); + $this->stepInfo('Home document: %s', json_encode($homeDocument)); + + $this->step('Get ping'); + $ping = $this->getService()->getPing(); + $this->stepInfo('Ping successful'); + $this->step('List flavors'); $flavors = $this->getService()->listFlavors(); $this->stepInfo('%-40s | %s', 'Flavor ID', 'Number of providers'); From 9686882b3418fbad36e53412bf5140ffb32ca7d6 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 30 Dec 2014 05:41:53 -0800 Subject: [PATCH 033/181] Wait for service to return to a status where further changes can be made. --- tests/OpenCloud/Smoke/Unit/CDN.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/OpenCloud/Smoke/Unit/CDN.php b/tests/OpenCloud/Smoke/Unit/CDN.php index 59366bb93..c6ec30209 100644 --- a/tests/OpenCloud/Smoke/Unit/CDN.php +++ b/tests/OpenCloud/Smoke/Unit/CDN.php @@ -75,6 +75,9 @@ public function main() $this->stepInfo('Origin: ' . $origins[0]->origin); $this->step('Update service'); + $service->waitFor('deployed', null, function ($s) { + $this->stepInfo('Service is still being created. Waiting...'); + }); $service->update(array( 'origins' => array( array( 'origin' => 'updated-origin.php-opencloud.com' ) @@ -82,6 +85,9 @@ public function main() )); $this->step('Purge ALL cached service assets'); + $service->waitFor('deployed', null, function ($s) { + $this->stepInfo('Service is still being updated. Waiting...'); + }); $service->purgeAssets(); $this->step('Delete service'); From a9de5fcf5de9bafea3c028624f298cc52f495b1f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 30 Dec 2014 05:43:42 -0800 Subject: [PATCH 034/181] Removing trailing space to make the linter happy. --- lib/OpenCloud/CDN/Service.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/OpenCloud/CDN/Service.php b/lib/OpenCloud/CDN/Service.php index 14f2281a7..af4669e81 100644 --- a/lib/OpenCloud/CDN/Service.php +++ b/lib/OpenCloud/CDN/Service.php @@ -157,7 +157,7 @@ public function getHomeDocument() /** * Returns the ping (status) response for the CDN service * - * @return Guzzle\Http\Message\Response + * @return Guzzle\Http\Message\Response */ public function getPing() { From 3386d76ef298cf64f2c819a4395844e01e984453 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 31 Dec 2014 09:22:26 -0800 Subject: [PATCH 035/181] Adding ID property (primary key; generated) to Service resource. --- docs/userguide/CDN/USERGUIDE.md | 4 ++-- lib/OpenCloud/CDN/Resource/Service.php | 6 +----- samples/CDN/delete-service.php | 2 +- samples/CDN/get-service.php | 2 +- samples/CDN/purge-cached-service-asset.php | 2 +- samples/CDN/purge-cached-service-assets.php | 2 +- samples/CDN/update-service.php | 2 +- tests/OpenCloud/Smoke/Unit/CDN.php | 2 +- 8 files changed, 9 insertions(+), 13 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index de26dac3a..113fe46a4 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -146,10 +146,10 @@ foreach ($services as $service) { ### Get a service -You can retrieve a specific service by using that service's name, as shown in the following example: +You can retrieve a specific service by using that service's ID, as shown in the following example: ```php -$service = $cdnService->getservice('acme_site'); +$service = $cdnService->getService('0e09ad12-2bfe-4607-80fd-116fa68d9c79'); /** @var $service OpenCloud\CDN\Resource\Service **/ ``` diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index 2823286d1..0a4977329 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -32,6 +32,7 @@ class Service extends PersistentResource const UPDATE_METHOD = 'PATCH'; + protected $id; protected $name; protected $domains; protected $origins; @@ -92,11 +93,6 @@ protected function assetsUrl() return $url; } - protected function primaryKeyField() - { - return 'name'; - } - protected function createJson() { $createJson = parent::createJson(); diff --git a/samples/CDN/delete-service.php b/samples/CDN/delete-service.php index 345479084..6b6fc1914 100644 --- a/samples/CDN/delete-service.php +++ b/samples/CDN/delete-service.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getServices('{name}'); +$service = $cdnService->getServices('{id}'); // 4. Delete it. $service->delete(); diff --git a/samples/CDN/get-service.php b/samples/CDN/get-service.php index 7a4a72dae..3b2d9044e 100644 --- a/samples/CDN/get-service.php +++ b/samples/CDN/get-service.php @@ -30,5 +30,5 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getService('{name}'); +$service = $cdnService->getService('{id}'); /** @var $service OpenCloud\CDN\Resource\Service **/ diff --git a/samples/CDN/purge-cached-service-asset.php b/samples/CDN/purge-cached-service-asset.php index 715a80699..33b785209 100644 --- a/samples/CDN/purge-cached-service-asset.php +++ b/samples/CDN/purge-cached-service-asset.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getServices('{name}'); +$service = $cdnService->getServices('{id}'); // 4. Purge a specific asset belonging to service. $service->purgeAssets('{asset URL}'); diff --git a/samples/CDN/purge-cached-service-assets.php b/samples/CDN/purge-cached-service-assets.php index 0d032c89c..5e74c989e 100644 --- a/samples/CDN/purge-cached-service-assets.php +++ b/samples/CDN/purge-cached-service-assets.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getServices('{name}'); +$service = $cdnService->getServices('{id}'); // 4. Purge all assets belonging to service. $service->purgeAssets(); diff --git a/samples/CDN/update-service.php b/samples/CDN/update-service.php index 13b34b7bf..a839a07e2 100644 --- a/samples/CDN/update-service.php +++ b/samples/CDN/update-service.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getService('{name}'); +$service = $cdnService->getService('{id}'); // 4. Update it. $service->update(array( diff --git a/tests/OpenCloud/Smoke/Unit/CDN.php b/tests/OpenCloud/Smoke/Unit/CDN.php index c6ec30209..da828676b 100644 --- a/tests/OpenCloud/Smoke/Unit/CDN.php +++ b/tests/OpenCloud/Smoke/Unit/CDN.php @@ -68,7 +68,7 @@ public function main() } $this->step('Get service'); - $service = $this->getService()->getService('php-opencloud.com'); + $service = $this->getService()->getService($createdService->getId()); $this->stepInfo('Service name: ' . $service->getName()); $this->stepInfo('Status: ' . $service->getStatus()); $origins = $service->getOrigins(); From 67da4ede71f0d97708824a0c0ad0704db3cddcbd Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 04:41:18 -0800 Subject: [PATCH 036/181] Expanding on arguments. --- docs/userguide/CDN/USERGUIDE.md | 71 ++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 11 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index 113fe46a4..1569b8d4b 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -101,12 +101,36 @@ This operation takes one parameter, an associative array, with the following key | Name | Description | Data type | Required? | Default value | Example value | | ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | A human-readable name for the service. This name must be unique. | String | No | `null` | `acme_site` | -| `domains` | An array of associative arrays, each specifying a domain name for your service. | Array of associative arrays | Yes | `null` | `array( array( 'domain' => 'www.acme.com' ), array ( 'domain' => 'acme.com' ) )` | -| `origins` | An array of associative arrays, each specifying an origin server for your service. The `port`, `ssl`, and `rules` elements for each origin server are optional. | Array of associative arrays | Yes | `null` | `array( array( 'origin' => 'origin.acme.com', 'port' => 80, 'ssl' => false, 'rules' => array() ) )` | -| `flavorId` | The flavor used to configure this service. Use the [list flavors](#list-flavors) operation to retrieve a list of all available flavors. | String | Yes| `null` | `cdn` | -| `restrictions` | An array of associative arrays, each specifying a restriction for who can or cannot access content from the CDN cache. | Array of associative arrays | No | `null` | `array( array( 'name' => 'website only', 'rules' => array( array( 'name' => 'mywebsite.com', 'httpHost' => 'www.mywebsite.com' ) ) ) )` | -| `caching` | An array of associative arrays, each specifying a caching rule for your service's assets. | No | `null` | `array( array( 'name' => 'default', 'ttl' => 3600 ) )` | +| `name` | A human-readable name for the service. This name must be unique. | String | Yes | - | `acme_site` | +| `flavorId` | The ID of the flavor to use for this service. | String | Yes | - | `cdn` | +| `domains` | List of domain for your service. | Array of associative arrays | Yes | - | `array( ... )` | +| `domains[n]` | Information about a domain for your service. | Associative array | Yes | - | `array( ... )` | +| `domains[n]['domain'] | The domain name for your service. | String | Yes | - | 'www.acme.com' | +| `domains[n]['protocol'] | The protocol used by your service web site, `http` or `https`. | String | No | `http` | `http` | +| `origins` | List of origin servers for your service. | Array of associative arrays | Yes | - | `array( ... )` | +| `origins[n]` | Information about an origin server for your service. | Associative array | Yes | - | `array( ... )` | +| `origins[n]['origin']` | The origin server address, from where the CDN will pull your web site's assets. | String | Yes | - | `origin.acme.com` | +| `origins[n]['origin']['port']` | The origin server's port. | Integer | No | 80 | `8080` | +| `origins[n]['origin']['ssl']` | Whether origin server uses SSL. | Boolean | No | `false` | `true` | +| `origins[n]['origin']['rules'] | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n] | Information about an access rule. | Associative array | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n]['name'] | A human-readable name of the rule. | String | No | `null` | `images` | +| `origins[n]['origin']['rules'][n]['request_url'] | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `caching` | List of TTL rules for assets of this service. | Array of associative arrays | No | `null` | `array( ... )` | +| `caching[n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | +| `caching[n]['name']` | A human-readable name of the TTL rule. | String | No | `null` | `long_ttl` | +| `caching[n]['ttl']` | The TTL value, in seconds. | Integer | No | `null` | `604800` | +| `caching[n]['rules']` | List of rules that determine if this TTL should be applied to an asset. | Array of associative arrays | No | `null` | `array( ... )` | +| `caching[n]['rules'][n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | +| `caching[n]['rules'][n]['name']` | A human-readable name of the TTL rule. | No | `null` | `images` | +| `caching[n]['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `restrictions` | List of restrictions on who can access new service. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | +| `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | +| `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | +| `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | +| `restrictions[n]['rules'][n]['referrer'] | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | You can create a service as shown in the following example: @@ -161,11 +185,36 @@ This operation takes one parameter, an associative array, with the following key | Name | Description | Data type | Required? | Default value | Example value | | ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `domains` | An array of associative arrays, each specifying a domain name for your service. | Array of associative arrays | Yes | `null` | `array( array( 'domain' => 'www.acme.com' ), array ( 'domain' => 'acme.com' ) )` | -| `origins` | An array of associative arrays, each specifying an origin server for your service. The `port`, `ssl`, and `rules` elements for each origin server are optional. | Array of associative arrays | Yes | `null` | `array( array( 'origin' => 'origin.acme.com', 'port' => 80, 'ssl' => false, 'rules' => array() ) )` | -| `flavorId` | The flavor used to configure this service. Use the [list flavors](#list-flavors) operation to retrieve a list of all available flavors. | String | Yes| `null` | `cdn` | -| `restrictions` | An array of associative arrays, each specifying a restriction for who can or cannot access content from the CDN cache. | Array of associative arrays | No | `null` | `array( array( 'name' => 'website only', 'rules' => array( array( 'name' => 'mywebsite.com', 'httpHost' => 'www.mywebsite.com' ) ) ) )` | -| `caching` | An array of associative arrays, each specifying a caching rule for your service's assets. | No | `null` | `array( array( 'name' => 'default', 'ttl' => 3600 ) )` | +| `name` | A human-readable name for the service. This name must be unique. | String | Yes | - | `acme_site` | +| `flavorId` | The ID of the flavor to use for this service. | String | Yes | - | `cdn` | +| `domains` | List of domain for your service. | Array of associative arrays | Yes | - | `array( ... )` | +| `domains[n]` | Information about a domain for your service. | Associative array | Yes | - | `array( ... )` | +| `domains[n]['domain'] | The domain name for your service. | String | Yes | - | 'www.acme.com' | +| `domains[n]['protocol'] | The protocol used by your service web site, `http` or `https`. | String | No | `http` | `http` | +| `origins` | List of origin servers for your service. | Array of associative arrays | Yes | - | `array( ... )` | +| `origins[n]` | Information about an origin server for your service. | Associative array | Yes | - | `array( ... )` | +| `origins[n]['origin']` | The origin server address, from where the CDN will pull your web site's assets. | String | Yes | - | `origin.acme.com` | +| `origins[n]['origin']['port']` | The origin server's port. | Integer | No | 80 | `8080` | +| `origins[n]['origin']['ssl']` | Whether origin server uses SSL. | Boolean | No | `false` | `true` | +| `origins[n]['origin']['rules'] | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n] | Information about an access rule. | Associative array | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n]['name'] | A human-readable name of the rule. | String | No | `null` | `images` | +| `origins[n]['origin']['rules'][n]['request_url'] | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `caching` | List of TTL rules for assets of this service. | Array of associative arrays | No | `null` | `array( ... )` | +| `caching[n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | +| `caching[n]['name']` | A human-readable name of the TTL rule. | String | No | `null` | `long_ttl` | +| `caching[n]['ttl']` | The TTL value, in seconds. | Integer | No | `null` | `604800` | +| `caching[n]['rules']` | List of rules that determine if this TTL should be applied to an asset. | Array of associative arrays | No | `null` | `array( ... )` | +| `caching[n]['rules'][n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | +| `caching[n]['rules'][n]['name']` | A human-readable name of the TTL rule. | No | `null` | `images` | +| `caching[n]['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `restrictions` | List of restrictions on who can access new service. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | +| `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | +| `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | +| `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | +| `restrictions[n]['rules'][n]['referrer'] | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | You can update a service as shown in the following example: From e29681eda1c5d505f9836e44d1f01beb014104a0 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 04:42:49 -0800 Subject: [PATCH 037/181] Moving @see annotations to new line. --- lib/OpenCloud/CDN/Service.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/OpenCloud/CDN/Service.php b/lib/OpenCloud/CDN/Service.php index af4669e81..57c880052 100644 --- a/lib/OpenCloud/CDN/Service.php +++ b/lib/OpenCloud/CDN/Service.php @@ -50,7 +50,8 @@ public function service($id = null) /** * Creates a new Service and returns it. * - * @param array $params Service creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/CDN/USERGUIDE.md#create-a-service + * @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/CDN/USERGUIDE.md#create-a-service + * @param array $params Service creation parameters. * @return \OpenCloud\CDN\Resource\Service Object representing created service */ public function createService(array $params = array()) @@ -101,7 +102,8 @@ public function flavor($id = null) /** * Creates a new Flavor and returns it. * - * @param array $params Flavor creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/CDN/USERGUIDE.md#create-a-flavor + * @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/CDN/USERGUIDE.md#create-a-flavor + * @param array $params Flavor creation parameters. * @return \OpenCloud\CDN\Resource\Flavor Object representing created flavor */ public function createFlavor(array $params = array()) From b7b020e5e3a22d5d275897a4f8e048f9838151ff Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 04:46:47 -0800 Subject: [PATCH 038/181] Doing the same things with fewer lines of code. --- lib/OpenCloud/Common/Resource/PersistentResource.php | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index f769f9856..bd6111675 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -86,11 +86,8 @@ public function update($params = array()) protected function makeUpdateRequest($json) { - if ('PATCH' === static::UPDATE_METHOD) { - return $this->getClient()->patch($this->getUrl(), self::getJsonHeader(), $json)->send(); - } else { - return $this->getClient()->put($this->getUrl(), self::getJsonHeader(), $json)->send(); - } + $updateMethod = ('PATCH' === static::UPDATE_METHOD) ? 'patch' : 'post'; + return $this->getClient()->$updateMethod($this->getUrl(), self::getJsonHeader(), $json)->send(); } /** From 70be88b5bcefdc4be5af2d9570d40b49f33f545e Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 04:48:34 -0800 Subject: [PATCH 039/181] Refactoring to remove single-use local variable. --- lib/OpenCloud/Common/Resource/PersistentResource.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index bd6111675..35e86529e 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -273,8 +273,7 @@ protected function recursivelyAliasPropertyValue($propertyValue) } } } elseif (is_object($propertyValue) && ($propertyValue instanceof \stdClass)) { - $objectVars = get_object_vars($propertyValue); - foreach ($objectVars as $key => $subValue) { + foreach (get_object_vars($propertyValue) as $key => $subValue) { unset($propertyValue->$key); $propertyValue->{$this->getAlias($key)} = $this->recursivelyAliasPropertyValue($subValue); } From 5dc7b411c0c3882f97d57997ad8fc819e08bed10 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 04:52:45 -0800 Subject: [PATCH 040/181] Condensing single-element array literals to single line. --- samples/CDN/create-service.php | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/samples/CDN/create-service.php b/samples/CDN/create-service.php index 2df1f5c5e..a35c8ec61 100644 --- a/samples/CDN/create-service.php +++ b/samples/CDN/create-service.php @@ -33,14 +33,10 @@ $service = $cdnService->createService(array( 'name' => '{name}', 'domains' => array( - array( - 'domain' => '{domain name}' - ) + array( 'domain' => '{domain name}' ) ), 'origins' => array( - array( - 'origin' => '{origin address}' - ) + array( 'origin' => '{origin address}' ) ), 'flavorId' => '{flavor ID}' )); From 8908d8a5a170145b9425080c04dd3c450fa14d5e Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 04:53:14 -0800 Subject: [PATCH 041/181] Fixing typo in method names. --- samples/CDN/delete-flavor.php | 2 +- samples/CDN/delete-service.php | 2 +- samples/CDN/purge-cached-service-asset.php | 2 +- samples/CDN/purge-cached-service-assets.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/CDN/delete-flavor.php b/samples/CDN/delete-flavor.php index 760a0306b..9d2f291ef 100644 --- a/samples/CDN/delete-flavor.php +++ b/samples/CDN/delete-flavor.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get flavor. -$flavor = $cdnFlavor->getFlavors('{id}'); +$flavor = $cdnFlavor->getFlavor('{id}'); // 4. Delete it. $flavor->delete(); diff --git a/samples/CDN/delete-service.php b/samples/CDN/delete-service.php index 6b6fc1914..0947bcd60 100644 --- a/samples/CDN/delete-service.php +++ b/samples/CDN/delete-service.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getServices('{id}'); +$service = $cdnService->getService('{id}'); // 4. Delete it. $service->delete(); diff --git a/samples/CDN/purge-cached-service-asset.php b/samples/CDN/purge-cached-service-asset.php index 33b785209..8bbf61a38 100644 --- a/samples/CDN/purge-cached-service-asset.php +++ b/samples/CDN/purge-cached-service-asset.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getServices('{id}'); +$service = $cdnService->getService('{id}'); // 4. Purge a specific asset belonging to service. $service->purgeAssets('{asset URL}'); diff --git a/samples/CDN/purge-cached-service-assets.php b/samples/CDN/purge-cached-service-assets.php index 5e74c989e..36a5e37b5 100644 --- a/samples/CDN/purge-cached-service-assets.php +++ b/samples/CDN/purge-cached-service-assets.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getServices('{id}'); +$service = $cdnService->getService('{id}'); // 4. Purge all assets belonging to service. $service->purgeAssets(); From 9acbae5aa4af846b808cdc554dd70faea8d69f2c Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 04:57:34 -0800 Subject: [PATCH 042/181] Using better ID placeholder names. --- samples/CDN/create-flavor.php | 2 +- samples/CDN/delete-flavor.php | 2 +- samples/CDN/delete-service.php | 2 +- samples/CDN/get-flavor.php | 2 +- samples/CDN/get-service.php | 2 +- samples/CDN/purge-cached-service-asset.php | 2 +- samples/CDN/purge-cached-service-assets.php | 2 +- samples/CDN/update-service.php | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/samples/CDN/create-flavor.php b/samples/CDN/create-flavor.php index c9811cf85..5e2433ad7 100644 --- a/samples/CDN/create-flavor.php +++ b/samples/CDN/create-flavor.php @@ -31,7 +31,7 @@ // 3. Create flavor. $flavor = $cdnFlavor->createFlavor(array( - 'id' => '{id}', + 'id' => '{flavorId}', 'providers' => array( array( 'provider' => 'akamai', diff --git a/samples/CDN/delete-flavor.php b/samples/CDN/delete-flavor.php index 9d2f291ef..28f901c50 100644 --- a/samples/CDN/delete-flavor.php +++ b/samples/CDN/delete-flavor.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get flavor. -$flavor = $cdnFlavor->getFlavor('{id}'); +$flavor = $cdnFlavor->getFlavor('{flavorId}'); // 4. Delete it. $flavor->delete(); diff --git a/samples/CDN/delete-service.php b/samples/CDN/delete-service.php index 0947bcd60..2b223cdf7 100644 --- a/samples/CDN/delete-service.php +++ b/samples/CDN/delete-service.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getService('{id}'); +$service = $cdnService->getService('{serviceId}'); // 4. Delete it. $service->delete(); diff --git a/samples/CDN/get-flavor.php b/samples/CDN/get-flavor.php index e63ffcc29..90e605c21 100644 --- a/samples/CDN/get-flavor.php +++ b/samples/CDN/get-flavor.php @@ -30,5 +30,5 @@ $cdnService = $client->cdnService(); // 3. Get flavor. -$flavor = $cdnService->getFlavor('{flavor ID}'); +$flavor = $cdnService->getFlavor('{flavorId}'); /** @var $flavor OpenCloud\CDN\Resource\Flavor **/ diff --git a/samples/CDN/get-service.php b/samples/CDN/get-service.php index 3b2d9044e..113d4ae24 100644 --- a/samples/CDN/get-service.php +++ b/samples/CDN/get-service.php @@ -30,5 +30,5 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getService('{id}'); +$service = $cdnService->getService('{serviceId}'); /** @var $service OpenCloud\CDN\Resource\Service **/ diff --git a/samples/CDN/purge-cached-service-asset.php b/samples/CDN/purge-cached-service-asset.php index 8bbf61a38..2ab5141d0 100644 --- a/samples/CDN/purge-cached-service-asset.php +++ b/samples/CDN/purge-cached-service-asset.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getService('{id}'); +$service = $cdnService->getService('{serviceId}'); // 4. Purge a specific asset belonging to service. $service->purgeAssets('{asset URL}'); diff --git a/samples/CDN/purge-cached-service-assets.php b/samples/CDN/purge-cached-service-assets.php index 36a5e37b5..afc9cb1c6 100644 --- a/samples/CDN/purge-cached-service-assets.php +++ b/samples/CDN/purge-cached-service-assets.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getService('{id}'); +$service = $cdnService->getService('{serviceId}'); // 4. Purge all assets belonging to service. $service->purgeAssets(); diff --git a/samples/CDN/update-service.php b/samples/CDN/update-service.php index a839a07e2..8f5c9db6f 100644 --- a/samples/CDN/update-service.php +++ b/samples/CDN/update-service.php @@ -30,7 +30,7 @@ $cdnService = $client->cdnService(); // 3. Get service. -$service = $cdnService->getService('{id}'); +$service = $cdnService->getService('{serviceId}'); // 4. Update it. $service->update(array( From e16e9a03b55691f1647deb17c39cc09e12641fb9 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 05:46:37 -0800 Subject: [PATCH 043/181] Fixing formatting issues due to missing backticks. --- docs/userguide/CDN/USERGUIDE.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index 1569b8d4b..cc285834d 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -105,17 +105,17 @@ This operation takes one parameter, an associative array, with the following key | `flavorId` | The ID of the flavor to use for this service. | String | Yes | - | `cdn` | | `domains` | List of domain for your service. | Array of associative arrays | Yes | - | `array( ... )` | | `domains[n]` | Information about a domain for your service. | Associative array | Yes | - | `array( ... )` | -| `domains[n]['domain'] | The domain name for your service. | String | Yes | - | 'www.acme.com' | -| `domains[n]['protocol'] | The protocol used by your service web site, `http` or `https`. | String | No | `http` | `http` | +| `domains[n]['domain']` | The domain name for your service. | String | Yes | - | 'www.acme.com' | +| `domains[n]['protocol']` | The protocol used by your service web site, `http` or `https`. | String | No | `http` | `http` | | `origins` | List of origin servers for your service. | Array of associative arrays | Yes | - | `array( ... )` | | `origins[n]` | Information about an origin server for your service. | Associative array | Yes | - | `array( ... )` | | `origins[n]['origin']` | The origin server address, from where the CDN will pull your web site's assets. | String | Yes | - | `origin.acme.com` | | `origins[n]['origin']['port']` | The origin server's port. | Integer | No | 80 | `8080` | | `origins[n]['origin']['ssl']` | Whether origin server uses SSL. | Boolean | No | `false` | `true` | -| `origins[n]['origin']['rules'] | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | -| `origins[n]['origin']['rules'][n] | Information about an access rule. | Associative array | No | `null` | `array( ... )` | -| `origins[n]['origin']['rules'][n]['name'] | A human-readable name of the rule. | String | No | `null` | `images` | -| `origins[n]['origin']['rules'][n]['request_url'] | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `origins[n]['origin']['rules']` | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n]` | Information about an access rule. | Associative array | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n]['name']` | A human-readable name of the rule. | String | No | `null` | `images` | +| `origins[n]['origin']['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | | `caching` | List of TTL rules for assets of this service. | Array of associative arrays | No | `null` | `array( ... )` | | `caching[n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['name']` | A human-readable name of the TTL rule. | String | No | `null` | `long_ttl` | @@ -130,7 +130,7 @@ This operation takes one parameter, an associative array, with the following key | `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | -| `restrictions[n]['rules'][n]['referrer'] | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | +| `restrictions[n]['rules'][n]['referrer']` | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | You can create a service as shown in the following example: @@ -189,17 +189,17 @@ This operation takes one parameter, an associative array, with the following key | `flavorId` | The ID of the flavor to use for this service. | String | Yes | - | `cdn` | | `domains` | List of domain for your service. | Array of associative arrays | Yes | - | `array( ... )` | | `domains[n]` | Information about a domain for your service. | Associative array | Yes | - | `array( ... )` | -| `domains[n]['domain'] | The domain name for your service. | String | Yes | - | 'www.acme.com' | -| `domains[n]['protocol'] | The protocol used by your service web site, `http` or `https`. | String | No | `http` | `http` | +| `domains[n]['domain']` | The domain name for your service. | String | Yes | - | 'www.acme.com' | +| `domains[n]['protocol']` | The protocol used by your service web site, `http` or `https`. | String | No | `http` | `http` | | `origins` | List of origin servers for your service. | Array of associative arrays | Yes | - | `array( ... )` | | `origins[n]` | Information about an origin server for your service. | Associative array | Yes | - | `array( ... )` | | `origins[n]['origin']` | The origin server address, from where the CDN will pull your web site's assets. | String | Yes | - | `origin.acme.com` | | `origins[n]['origin']['port']` | The origin server's port. | Integer | No | 80 | `8080` | | `origins[n]['origin']['ssl']` | Whether origin server uses SSL. | Boolean | No | `false` | `true` | -| `origins[n]['origin']['rules'] | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | -| `origins[n]['origin']['rules'][n] | Information about an access rule. | Associative array | No | `null` | `array( ... )` | -| `origins[n]['origin']['rules'][n]['name'] | A human-readable name of the rule. | String | No | `null` | `images` | -| `origins[n]['origin']['rules'][n]['request_url'] | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `origins[n]['origin']['rules']` | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n]` | Information about an access rule. | Associative array | No | `null` | `array( ... )` | +| `origins[n]['origin']['rules'][n]['name']` | A human-readable name of the rule. | String | No | `null` | `images` | +| `origins[n]['origin']['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | | `caching` | List of TTL rules for assets of this service. | Array of associative arrays | No | `null` | `array( ... )` | | `caching[n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['name']` | A human-readable name of the TTL rule. | String | No | `null` | `long_ttl` | @@ -214,7 +214,7 @@ This operation takes one parameter, an associative array, with the following key | `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | -| `restrictions[n]['rules'][n]['referrer'] | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | +| `restrictions[n]['rules'][n]['referrer']` | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | You can update a service as shown in the following example: From 7f1b97127dd01c1d255332efac0ee467b7f1b806 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 05:48:26 -0800 Subject: [PATCH 044/181] Trimming whitespace. --- samples/CDN/create-service.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/CDN/create-service.php b/samples/CDN/create-service.php index a35c8ec61..33967d470 100644 --- a/samples/CDN/create-service.php +++ b/samples/CDN/create-service.php @@ -33,10 +33,10 @@ $service = $cdnService->createService(array( 'name' => '{name}', 'domains' => array( - array( 'domain' => '{domain name}' ) + array('domain' => '{domain name}') ), 'origins' => array( - array( 'origin' => '{origin address}' ) + array('origin' => '{origin address}') ), 'flavorId' => '{flavor ID}' )); From c908eb9ade929c045988846d3668b9600a296cc8 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 2 Jan 2015 05:49:58 -0800 Subject: [PATCH 045/181] Standardizing placeholders to use camelCase. --- samples/CDN/create-service.php | 6 +++--- samples/CDN/purge-cached-service-asset.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/CDN/create-service.php b/samples/CDN/create-service.php index 33967d470..102fd1f18 100644 --- a/samples/CDN/create-service.php +++ b/samples/CDN/create-service.php @@ -33,11 +33,11 @@ $service = $cdnService->createService(array( 'name' => '{name}', 'domains' => array( - array('domain' => '{domain name}') + array('domain' => '{domainName}') ), 'origins' => array( - array('origin' => '{origin address}') + array('origin' => '{originAddress}') ), - 'flavorId' => '{flavor ID}' + 'flavorId' => '{flavorId}' )); /** @var $service OpenCloud\CDN\Resource\Service **/ diff --git a/samples/CDN/purge-cached-service-asset.php b/samples/CDN/purge-cached-service-asset.php index 2ab5141d0..fdb2f97c4 100644 --- a/samples/CDN/purge-cached-service-asset.php +++ b/samples/CDN/purge-cached-service-asset.php @@ -33,4 +33,4 @@ $service = $cdnService->getService('{serviceId}'); // 4. Purge a specific asset belonging to service. -$service->purgeAssets('{asset URL}'); +$service->purgeAssets('{assetUrl}'); From 959a48975eea23b11485a8b7a62dc95a3c62c211 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Sat, 3 Jan 2015 05:00:22 -0800 Subject: [PATCH 046/181] Fixing parameter paths. --- docs/userguide/CDN/USERGUIDE.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index cc285834d..ff908e1d7 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -110,12 +110,12 @@ This operation takes one parameter, an associative array, with the following key | `origins` | List of origin servers for your service. | Array of associative arrays | Yes | - | `array( ... )` | | `origins[n]` | Information about an origin server for your service. | Associative array | Yes | - | `array( ... )` | | `origins[n]['origin']` | The origin server address, from where the CDN will pull your web site's assets. | String | Yes | - | `origin.acme.com` | -| `origins[n]['origin']['port']` | The origin server's port. | Integer | No | 80 | `8080` | -| `origins[n]['origin']['ssl']` | Whether origin server uses SSL. | Boolean | No | `false` | `true` | -| `origins[n]['origin']['rules']` | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | -| `origins[n]['origin']['rules'][n]` | Information about an access rule. | Associative array | No | `null` | `array( ... )` | -| `origins[n]['origin']['rules'][n]['name']` | A human-readable name of the rule. | String | No | `null` | `images` | -| `origins[n]['origin']['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `origins[n]['port']` | The origin server's port. | Integer | No | 80 | `8080` | +| `origins[n]['ssl']` | Whether origin server uses SSL. | Boolean | No | `false` | `true` | +| `origins[n]['rules']` | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | +| `origins[n]['rules'][n]` | Information about an access rule. | Associative array | No | `null` | `array( ... )` | +| `origins[n]['rules'][n]['name']` | A human-readable name of the rule. | String | No | `null` | `images` | +| `origins[n]['rules'][n]['requestUrl']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | | `caching` | List of TTL rules for assets of this service. | Array of associative arrays | No | `null` | `array( ... )` | | `caching[n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['name']` | A human-readable name of the TTL rule. | String | No | `null` | `long_ttl` | From 6d0a4e0ca5a75649425fd9afddaa7f12bb871de9 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Sat, 3 Jan 2015 05:00:44 -0800 Subject: [PATCH 047/181] Aliasing requestUrl -> request_url. --- docs/userguide/CDN/USERGUIDE.md | 6 +++--- lib/OpenCloud/CDN/Resource/Service.php | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index ff908e1d7..be9404778 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -123,7 +123,7 @@ This operation takes one parameter, an associative array, with the following key | `caching[n]['rules']` | List of rules that determine if this TTL should be applied to an asset. | Array of associative arrays | No | `null` | `array( ... )` | | `caching[n]['rules'][n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['rules'][n]['name']` | A human-readable name of the TTL rule. | No | `null` | `images` | -| `caching[n]['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `caching[n]['rules'][n]['requestUrl']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | | `restrictions` | List of restrictions on who can access new service. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | @@ -199,7 +199,7 @@ This operation takes one parameter, an associative array, with the following key | `origins[n]['origin']['rules']` | List of rules defining the conditions when this origin should be accessed. | Array of associative arrays | No | `null` | `array( ... )` | | `origins[n]['origin']['rules'][n]` | Information about an access rule. | Associative array | No | `null` | `array( ... )` | | `origins[n]['origin']['rules'][n]['name']` | A human-readable name of the rule. | String | No | `null` | `images` | -| `origins[n]['origin']['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `origins[n]['origin']['rules'][n]['requestUrl']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | | `caching` | List of TTL rules for assets of this service. | Array of associative arrays | No | `null` | `array( ... )` | | `caching[n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['name']` | A human-readable name of the TTL rule. | String | No | `null` | `long_ttl` | @@ -207,7 +207,7 @@ This operation takes one parameter, an associative array, with the following key | `caching[n]['rules']` | List of rules that determine if this TTL should be applied to an asset. | Array of associative arrays | No | `null` | `array( ... )` | | `caching[n]['rules'][n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['rules'][n]['name']` | A human-readable name of the TTL rule. | No | `null` | `images` | -| `caching[n]['rules'][n]['request_url']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | +| `caching[n]['rules'][n]['requestUrl']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | | `restrictions` | List of restrictions on who can access new service. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index 0a4977329..233faacc9 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -45,7 +45,8 @@ class Service extends PersistentResource protected $aliases = array( 'flavor_id' => 'flavorId', - 'http_host' => 'httpHost' + 'http_host' => 'httpHost', + 'request_url' => 'requestUrl' ); protected $createKeys = array( From 7a7ff518c58373be9ded148b9891774d0547a9f7 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Sat, 3 Jan 2015 05:09:31 -0800 Subject: [PATCH 048/181] Clarifying parameter descriptions. --- docs/userguide/CDN/USERGUIDE.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index be9404778..e02599b5d 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -124,13 +124,13 @@ This operation takes one parameter, an associative array, with the following key | `caching[n]['rules'][n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['rules'][n]['name']` | A human-readable name of the TTL rule. | No | `null` | `images` | | `caching[n]['rules'][n]['requestUrl']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | -| `restrictions` | List of restrictions on who can access new service. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions` | List of restrictions on where the service can be accessed from. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | | `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | -| `restrictions[n]['rules'][n]['referrer']` | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | +| `restrictions[n]['rules'][n]['referrer']` | The domain from which the service can be accessed. | String | No | `null` | `www.wilecoyote.com` | You can create a service as shown in the following example: @@ -208,13 +208,13 @@ This operation takes one parameter, an associative array, with the following key | `caching[n]['rules'][n]` | Information about a TTL rule. | Associative array | No | `null` | `array( ... )` | | `caching[n]['rules'][n]['name']` | A human-readable name of the TTL rule. | No | `null` | `images` | | `caching[n]['rules'][n]['requestUrl']` | The request URL this rule should match (regex supported). | String | No | `null` | `^/images/.+$` | -| `restrictions` | List of restrictions on who can access new service. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions` | List of restrictions on where the service can be accessed from. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | | `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | -| `restrictions[n]['rules'][n]['referrer']` | The domain from which the new service can be accessed. | String | No | `null` | `www.wilecoyote.com` | +| `restrictions[n]['rules'][n]['referrer']` | The domain from which the service can be accessed. | String | No | `null` | `www.wilecoyote.com` | You can update a service as shown in the following example: From 5f550f9aef8a21ba71367f60266c77f735bef892 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Sat, 3 Jan 2015 05:09:40 -0800 Subject: [PATCH 049/181] Fixing typos. --- docs/userguide/CDN/USERGUIDE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index e02599b5d..8093b7c39 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -127,7 +127,7 @@ This operation takes one parameter, an associative array, with the following key | `restrictions` | List of restrictions on where the service can be accessed from. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | -| `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions[n]['rules']` | List of restriction rules. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | | `restrictions[n]['rules'][n]['referrer']` | The domain from which the service can be accessed. | String | No | `null` | `www.wilecoyote.com` | @@ -211,7 +211,7 @@ This operation takes one parameter, an associative array, with the following key | `restrictions` | List of restrictions on where the service can be accessed from. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]` | Information about an access restriction. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['name']` | A human-readable name of the restriction. | String | No | `null` | `affiliate_sites_only` | -| `restrictions[n]['rules']` | List of restrition rules. | Array of associative arrays | No | `null` | `array( ... )` | +| `restrictions[n]['rules']` | List of restriction rules. | Array of associative arrays | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]` | Information about a restriction rule. | Associative array | No | `null` | `array( ... )` | | `restrictions[n]['rules'][n]['name']` | A human-readable name of the restriction rule. | String | No | `null` | `Wile E. Coyote's site` | | `restrictions[n]['rules'][n]['referrer']` | The domain from which the service can be accessed. | String | No | `null` | `www.wilecoyote.com` | From 013d768e8af72143e0476e2ba9fc200cf4ab02a7 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Sat, 3 Jan 2015 05:15:38 -0800 Subject: [PATCH 050/181] Clarifying parameter description. --- docs/userguide/CDN/USERGUIDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index 8093b7c39..1db7acebe 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -105,7 +105,7 @@ This operation takes one parameter, an associative array, with the following key | `flavorId` | The ID of the flavor to use for this service. | String | Yes | - | `cdn` | | `domains` | List of domain for your service. | Array of associative arrays | Yes | - | `array( ... )` | | `domains[n]` | Information about a domain for your service. | Associative array | Yes | - | `array( ... )` | -| `domains[n]['domain']` | The domain name for your service. | String | Yes | - | 'www.acme.com' | +| `domains[n]['domain']` | A domain name used by your service. | String | Yes | - | 'www.acme.com' | | `domains[n]['protocol']` | The protocol used by your service web site, `http` or `https`. | String | No | `http` | `http` | | `origins` | List of origin servers for your service. | Array of associative arrays | Yes | - | `array( ... )` | | `origins[n]` | Information about an origin server for your service. | Associative array | Yes | - | `array( ... )` | From a0671b8c46dfb615d61c92f617e0ad80ae3efe99 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 5 Jan 2015 12:17:10 -0800 Subject: [PATCH 051/181] Adding helper methods to generate JSON Patch representation for resource. --- composer.json | 9 ++- .../Common/Resource/PersistentResource.php | 43 +++++++++++ .../Resource/PersistentResourceTest.php | 74 +++++++++++++++++++ 3 files changed, 125 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index eed385e82..71d8b7903 100644 --- a/composer.json +++ b/composer.json @@ -20,10 +20,17 @@ "OpenCloud": ["lib/", "tests/"] } }, + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/ycombinator/json-patch-php" + } + ], "require": { "php" : ">=5.3.3", "guzzle/http" : "~3.8", - "psr/log": "~1.0" + "psr/log": "~1.0", + "mikemccabe/json-patch-php": "dev-master" }, "require-dev" : { "phpunit/phpunit": "4.3.*", diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index 35e86529e..57d2dca8e 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -25,6 +25,7 @@ use OpenCloud\Common\Exceptions\NameError; use OpenCloud\Common\Exceptions\UnsupportedExtensionError; use OpenCloud\Common\Exceptions\UpdateError; +use mikemccabe\JsonPatch\JsonPatch; abstract class PersistentResource extends BaseResource { @@ -345,6 +346,48 @@ public function checkExtension($alias) return true; } + /** + * Returns the object's properties as an array + */ + protected function getPropertiesAsArray() + { + $properties = get_object_vars($this); + + $propertiesToRemove = array('aliases', 'service', 'parent', 'metadata'); + foreach ($propertiesToRemove as $property) { + unset($properties[$property]); + } + + return $properties; + } + + /** + * Generates a JSON Patch representation and return its + * + * @param mixed $updatedProperties Properties of the resource to update + * @return String JSON Patch representation for updates + */ + protected function generateJsonPatch($updatedProperties) + { + // Normalize current and updated properties into nested arrays + $currentProperties = json_decode(json_encode($this->getPropertiesAsArray()), true); + $updatedProperties = json_decode(json_encode($updatedProperties), true); + + // Add any properties that haven't changed to generate the correct patch + // (otherwise unchanging properties are marked as removed in the patch) + foreach ($currentProperties as $key => $value) { + if (!array_key_exists($key, $updatedProperties)) { + $updatedProperties[$key] = $value; + } + } + + // Generate JSON Patch representation + $json = json_encode(JsonPatch::diff($currentProperties, $updatedProperties)); + $this->checkJsonError(); + + return $json; + } + /******** DEPRECATED METHODS ********/ /** diff --git a/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php b/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php index cd81b93ab..b0dffeb80 100644 --- a/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php +++ b/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php @@ -31,6 +31,16 @@ public function recursivelyAliasPropertyValue($propertyValue) { return parent::recursivelyAliasPropertyValue($propertyValue); } + + public function getPropertiesAsArray() + { + return parent::getPropertiesAsArray(); + } + + public function generateJsonPatch($updateParams) + { + return parent::generateJsonPatch($updateParams); + } } class PersistentResourceTest extends OpenCloudTestCase @@ -106,4 +116,68 @@ public function testRecursivelyAliasPropertyValueWithObjects() $this->assertEquals($obj3Expected, $this->persistentResource->recursivelyAliasPropertyValue($obj3)); } + + public function testGetPropertiesAsArray() + { + $this->persistentResource->id = 17; + $this->persistentResource->tags = array('foo', 'bar'); + $this->persistentResource->domains = array( + (object) array('domain' => 'foo.phpopencloud.com'), + array('domain' => 'bar.phpopencloud.com') + ); + $this->persistentResource->origins = array( + array('origin' => 'origin1.phpopencloud.com') + ); + $this->persistentResource->status = (object) array('message' => 'Creation in progress'); + + $expectedArray = array( + 'id' => 17, + 'tags' => array('foo', 'bar'), + 'domains' => array( + (object) array('domain' => 'foo.phpopencloud.com'), + array('domain' => 'bar.phpopencloud.com') + ), + 'origins' => array( + array('origin' => 'origin1.phpopencloud.com'), + ), + 'status' => (object) array('message' => 'Creation in progress'), + ); + + $this->assertEquals($expectedArray, $this->persistentResource->getPropertiesAsArray()); + } + + public function testGenerateJsonPatch() + { + $this->persistentResource->id = 17; + $this->persistentResource->tags = array('foo', 'bar'); + $this->persistentResource->domains = array( + array('domain' => 'foo.phpopencloud.com'), + array('domain' => 'bar.phpopencloud.com') + ); + $this->persistentResource->origins = array( + array('origin' => 'origin1.phpopencloud.com') + ); + $this->persistentResource->status = array('message' => 'Creation in progress'); + + $updateParams = array( + 'tags' => array('foo', 'qux', 'baz'), + 'domains' => array( + array('domain' => 'foo.phpopencloud.com') + ), + 'origins' => array( + array('origin' => 'origin1.phpopencloud.com'), + array('origin' => 'origin2.phpopencloud.com') + ) + ); + + $expectedJsonPatch = json_encode(array( + array('op' => 'add', 'path' => '/tags/2', 'value' => 'baz'), + array('op' => 'replace', 'path' => '/tags/1', 'value' => 'qux'), + array('op' => 'remove', 'path' => '/domains/1'), + array('op' => 'add', 'path' => '/origins/1', 'value' => array("origin" => "origin2.phpopencloud.com")) + )); + + $actualJsonPatch = $this->persistentResource->generateJsonPatch($updateParams); + $this->assertEquals($expectedJsonPatch, $actualJsonPatch); + } } From 703941cb665f3efbda968fdc7d9be4150ea405d3 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 5 Jan 2015 13:00:09 -0800 Subject: [PATCH 052/181] Refactoring PATCH headers to Base. --- lib/OpenCloud/Common/Base.php | 7 +++++++ lib/OpenCloud/Common/Constants/Mime.php | 1 + lib/OpenCloud/Image/Resource/Image.php | 4 +++- lib/OpenCloud/Image/Service.php | 13 ------------- tests/OpenCloud/Tests/Common/BaseTest.php | 15 +++++++++++++++ .../Tests/Image/Resource/ImageTest.php | 19 ++++++++++++++++++- 6 files changed, 44 insertions(+), 15 deletions(-) diff --git a/lib/OpenCloud/Common/Base.php b/lib/OpenCloud/Common/Base.php index 3e0bc3dfb..fd638cc81 100644 --- a/lib/OpenCloud/Common/Base.php +++ b/lib/OpenCloud/Common/Base.php @@ -32,6 +32,8 @@ */ abstract class Base { + const PATCH_CONTENT_TYPE = MimeConst::JSON_PATCH; + /** * Holds all the properties added by overloading. * @@ -419,4 +421,9 @@ protected static function getJsonHeader() { return array(HeaderConst::CONTENT_TYPE => MimeConst::JSON); } + + protected static function getPatchHeaders() + { + return array(HeaderConst::CONTENT_TYPE => static::PATCH_CONTENT_TYPE); + } } diff --git a/lib/OpenCloud/Common/Constants/Mime.php b/lib/OpenCloud/Common/Constants/Mime.php index 23df6cfe9..4e2942ebb 100644 --- a/lib/OpenCloud/Common/Constants/Mime.php +++ b/lib/OpenCloud/Common/Constants/Mime.php @@ -21,4 +21,5 @@ class Mime { const JSON = 'application/json'; const TEXT = 'text/plain'; + const JSON_PATCH = 'application/json-patch+json'; } diff --git a/lib/OpenCloud/Image/Resource/Image.php b/lib/OpenCloud/Image/Resource/Image.php index b8ab7407c..f24eb510b 100644 --- a/lib/OpenCloud/Image/Resource/Image.php +++ b/lib/OpenCloud/Image/Resource/Image.php @@ -35,6 +35,8 @@ class Image extends AbstractSchemaResource implements ImageInterface protected static $json_name = ''; protected static $json_collection_name = 'images'; + const PATCH_CONTENT_TYPE = 'application/openstack-images-v2.1-json-patch'; + /** * Update this resource * @@ -85,7 +87,7 @@ public function update(array $params, Schema $schema = null) $body = $document->toString(); return $this->getClient() - ->patch($this->getUrl(), $this->getService()->getPatchHeaders(), $body) + ->patch($this->getUrl(), $this->getPatchHeaders(), $body) ->send(); } diff --git a/lib/OpenCloud/Image/Service.php b/lib/OpenCloud/Image/Service.php index 86462c8d6..f0ed4d72a 100644 --- a/lib/OpenCloud/Image/Service.php +++ b/lib/OpenCloud/Image/Service.php @@ -17,7 +17,6 @@ namespace OpenCloud\Image; -use OpenCloud\Common\Constants\Header; use OpenCloud\Common\Service\CatalogService; use OpenCloud\Image\Resource\Image; use OpenCloud\Image\Resource\Schema\Schema; @@ -32,18 +31,6 @@ class Service extends CatalogService const DEFAULT_TYPE = 'image'; const DEFAULT_NAME = 'cloudImages'; - const PATCH_CONTENT_TYPE = 'application/openstack-images-v2.1-json-patch'; - - /** - * Get the default headers to send for PATCH requests - * - * @return array - */ - public function getPatchHeaders() - { - return array(Header::CONTENT_TYPE => self::PATCH_CONTENT_TYPE); - } - /** * This operation returns images you created, shared images that you accepted, and standard images. * diff --git a/tests/OpenCloud/Tests/Common/BaseTest.php b/tests/OpenCloud/Tests/Common/BaseTest.php index c0a1c44ea..625863fb7 100644 --- a/tests/OpenCloud/Tests/Common/BaseTest.php +++ b/tests/OpenCloud/Tests/Common/BaseTest.php @@ -36,6 +36,11 @@ public function getBar() { return $this->bar; } + + public static function getPatchHeaders() + { + return parent::getPatchHeaders(); + } } class BaseTest extends \OpenCloud\Tests\OpenCloudTestCase @@ -100,4 +105,14 @@ public function testSetProperty() $this->my->setBaz('goodbye'); $this->assertEquals('goodbye', $this->my->getBaz()); } + + public function testGetPatchHeaders() + { + $expectedHeaders = array( + 'Content-Type' => 'application/json-patch+json' + ); + + $my = $this->my; + $this->assertEquals($expectedHeaders, $my::getPatchHeaders()); + } } diff --git a/tests/OpenCloud/Tests/Image/Resource/ImageTest.php b/tests/OpenCloud/Tests/Image/Resource/ImageTest.php index 5b9fc03b4..bcea3e089 100644 --- a/tests/OpenCloud/Tests/Image/Resource/ImageTest.php +++ b/tests/OpenCloud/Tests/Image/Resource/ImageTest.php @@ -22,11 +22,19 @@ use OpenCloud\Image\Resource\Schema\Schema; use OpenCloud\Tests\OpenCloudTestCase; +class PublicImage extends Image +{ + public static function getPatchHeaders() + { + return parent::getPatchHeaders(); + } +} + class ImageTest extends OpenCloudTestCase { public function setupObjects() { - $this->image = new Image($this->getClient()->imageService('cloudImages', 'IAD')); + $this->image = new PublicImage($this->getClient()->imageService('cloudImages', 'IAD')); } protected function getSchemaData() @@ -139,4 +147,13 @@ public function test_Delete_Tag() $this->assertInstanceOf('Guzzle\Http\Message\Response', $this->image->deleteTag(12345)); } + + public function testGetPatchHeaders() + { + $expectedHeaders = array( + 'Content-Type' => 'application/openstack-images-v2.1-json-patch' + ); + + $this->assertEquals($expectedHeaders, $this->image->getPatchHeaders()); + } } From 4d8688166543a52ef97746d60f18a83df09fd47a Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 5 Jan 2015 13:51:34 -0800 Subject: [PATCH 053/181] Overriding update() for Service resource; getting rid of update logic in PersistentResource. --- lib/OpenCloud/CDN/Resource/Service.php | 17 +++++++++++++++-- .../Common/Resource/PersistentResource.php | 10 +--------- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/lib/OpenCloud/CDN/Resource/Service.php b/lib/OpenCloud/CDN/Resource/Service.php index 233faacc9..5e3a2ff48 100644 --- a/lib/OpenCloud/CDN/Resource/Service.php +++ b/lib/OpenCloud/CDN/Resource/Service.php @@ -30,8 +30,6 @@ class Service extends PersistentResource protected static $url_resource = 'services'; protected static $json_name = 'service'; - const UPDATE_METHOD = 'PATCH'; - protected $id; protected $name; protected $domains; @@ -99,4 +97,19 @@ protected function createJson() $createJson = parent::createJson(); return $createJson->{self::$json_name}; } + + /** + * Update this resource + * + * @param array $params + * @return \Guzzle\Http\Message\Response + */ + public function update($params = array()) + { + $json = $this->generateJsonPatch($params); + + return $this->getClient() + ->patch($this->getUrl(), $this->getPatchHeaders(), $json) + ->send(); + } } diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index 57d2dca8e..6a3bc19d8 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -29,8 +29,6 @@ abstract class PersistentResource extends BaseResource { - const UPDATE_METHOD = 'PUT'; - /** * Create a new resource * @@ -82,13 +80,7 @@ public function update($params = array()) $this->checkJsonError(); // send the request - return $this->makeUpdateRequest($json); - } - - protected function makeUpdateRequest($json) - { - $updateMethod = ('PATCH' === static::UPDATE_METHOD) ? 'patch' : 'post'; - return $this->getClient()->$updateMethod($this->getUrl(), self::getJsonHeader(), $json)->send(); + return $this->getClient()->put($this->getUrl(), self::getJsonHeader(), $json)->send(); } /** From 650e80dcaa83032f98f00fa011785bad4b472ebe Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 5 Jan 2015 18:27:42 -0800 Subject: [PATCH 054/181] Removing newline to trigger build. --- docs/userguide/CDN/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/CDN/README.md b/docs/userguide/CDN/README.md index a64cca833..fbe813627 100644 --- a/docs/userguide/CDN/README.md +++ b/docs/userguide/CDN/README.md @@ -93,4 +93,4 @@ $service = $cdnService->createService(array( ## Next steps -Once you have created a service, there is more you can do with it. See [complete user guide for CDN](USERGUIDE.md). +Once you have created a service, there is more you can do with it. See [complete user guide for CDN](USERGUIDE.md). \ No newline at end of file From b610917b7ebeb4d33e49ac5e4a727cf4b4199dc9 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 6 Jan 2015 02:56:13 -0800 Subject: [PATCH 055/181] Removing docs for administrative operations. --- docs/userguide/CDN/USERGUIDE.md | 45 --------------------------------- 1 file changed, 45 deletions(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index 1db7acebe..b59ffdb2e 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -17,10 +17,8 @@ CDN is a service that you can use to manage your CDN-enabled domains and the ori * [Purge all cached service assets](#purge-all-cached-service-assets) * [Purge a specific cached service asset](#purge-a-specific-cached-service-asset) * [Flavors](#flavors) - * [Create a flavor](#create-a-flavor) * [List flavors](#list-flavors) * [Get a flavor](#get-a-flavor) - * [Delete a flavor](#delete-a-flavor) ## Concepts @@ -269,37 +267,6 @@ $service->purgeAssets('/images/logo.png'); A flavor is a configuration option. A flavor enables you to choose from a generic setting that is powered by one or more CDN providers. -### Create a flavor - -Note: When working with the Rackspace Cloud, this operation requires the `cdn:operator` role. - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `id` | ID of flavor. This ID must be unique. | String | Yes | `null` | `cdn` | -| `providers` | An array of associative arrays, each representing a CDN provider. | Array of associative arrays | Yes | `null` | `array( array( 'provider' => 'akamai', 'links' => array( array( 'rel' => 'provider_url', 'href' => 'http://www.akamai.com' ) ) ) )` | - -You can create a flavor as shown in the following example: - -```php -$flavor = $cdnService->createFlavor(array( - 'id' => 'cdn', - 'providers' => array( - array( - 'name' => 'akamai', - 'links' => array( - 'rel' => 'provider_url', - 'href' => 'http://www.akamai.com' - ) - ) - ) -)); -/** @var $flavor OpenCloud\CDN\Resource\Flavor **/ -``` - -[ [Get the executable PHP script for this example](/samples/CDN/create-flavor.php) ] - ### List flavors You can list all available flavors as shown in the following example: @@ -324,15 +291,3 @@ $flavor = $cdnService->getFlavor('cdn'); ``` [ [Get the executable PHP script for this example](/samples/CDN/get-flavor.php) ] - -### Delete a flavor - -Note: When working with the Rackspace Cloud, this operation requires the `cdn:operator` role. - -You can delete a flavor as shown in the following example: - -```php -$flavor->delete(); -``` - -[ [Get the executable PHP script for this example](/samples/CDN/delete-flavor.php) ] From 2377b064c15f7a959309d7926b3b4827960c0d8c Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 6 Jan 2015 02:56:30 -0800 Subject: [PATCH 056/181] Fixing ``` alignment. --- docs/userguide/CDN/USERGUIDE.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/userguide/CDN/USERGUIDE.md b/docs/userguide/CDN/USERGUIDE.md index b59ffdb2e..971175219 100644 --- a/docs/userguide/CDN/USERGUIDE.md +++ b/docs/userguide/CDN/USERGUIDE.md @@ -149,7 +149,8 @@ $service = $cdnService->createService(array( ) ), 'flavorId' => 'cdn' -));``` +)); +``` [ [Get the executable PHP script for this example](/samples/CDN/create-service.php) ] From 49d5ed85c0168f32429a00f3376bb1823894a729 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 6 Jan 2015 03:42:41 -0800 Subject: [PATCH 057/181] Using $this->updateKeys to determine the current values of updateable properties. --- .../Common/Resource/PersistentResource.php | 14 ++++++++------ .../Resource/PersistentResourceTest.php | 19 +++++++++++++------ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index 6a3bc19d8..803112472 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -341,16 +341,18 @@ public function checkExtension($alias) /** * Returns the object's properties as an array */ - protected function getPropertiesAsArray() + protected function getUpdateablePropertiesAsArray() { $properties = get_object_vars($this); - $propertiesToRemove = array('aliases', 'service', 'parent', 'metadata'); - foreach ($propertiesToRemove as $property) { - unset($properties[$property]); + $propertiesToKeep = array(); + foreach ($this->updateKeys as $key) { + if (isset($properties[$key])) { + $propertiesToKeep[$key] = $properties[$key]; + } } - return $properties; + return $propertiesToKeep; } /** @@ -362,7 +364,7 @@ protected function getPropertiesAsArray() protected function generateJsonPatch($updatedProperties) { // Normalize current and updated properties into nested arrays - $currentProperties = json_decode(json_encode($this->getPropertiesAsArray()), true); + $currentProperties = json_decode(json_encode($this->getUpdateablePropertiesAsArray()), true); $updatedProperties = json_decode(json_encode($updatedProperties), true); // Add any properties that haven't changed to generate the correct patch diff --git a/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php b/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php index b0dffeb80..0cf9342f0 100644 --- a/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php +++ b/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php @@ -27,14 +27,22 @@ class PublicPersistentResource extends PersistentResource 'foo_bar' => 'fooBar' ); + protected $updateKeys = array( + 'baz', + 'tags', + 'domains', + 'origins', + 'status' + ); + public function recursivelyAliasPropertyValue($propertyValue) { return parent::recursivelyAliasPropertyValue($propertyValue); } - public function getPropertiesAsArray() + public function getUpdateablePropertiesAsArray() { - return parent::getPropertiesAsArray(); + return parent::getUpdateablePropertiesAsArray(); } public function generateJsonPatch($updateParams) @@ -117,7 +125,7 @@ public function testRecursivelyAliasPropertyValueWithObjects() $this->persistentResource->recursivelyAliasPropertyValue($obj3)); } - public function testGetPropertiesAsArray() + public function testGetUpdateablePropertiesAsArray() { $this->persistentResource->id = 17; $this->persistentResource->tags = array('foo', 'bar'); @@ -131,7 +139,6 @@ public function testGetPropertiesAsArray() $this->persistentResource->status = (object) array('message' => 'Creation in progress'); $expectedArray = array( - 'id' => 17, 'tags' => array('foo', 'bar'), 'domains' => array( (object) array('domain' => 'foo.phpopencloud.com'), @@ -140,10 +147,10 @@ public function testGetPropertiesAsArray() 'origins' => array( array('origin' => 'origin1.phpopencloud.com'), ), - 'status' => (object) array('message' => 'Creation in progress'), + 'status' => (object) array('message' => 'Creation in progress') ); - $this->assertEquals($expectedArray, $this->persistentResource->getPropertiesAsArray()); + $this->assertEquals($expectedArray, $this->persistentResource->getUpdateablePropertiesAsArray()); } public function testGenerateJsonPatch() From 28a423451ac9c5b52f4519ee1b6bfce91ebb3543 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 6 Jan 2015 03:43:17 -0800 Subject: [PATCH 058/181] Using property aliases when generating JSON Patch representation. --- lib/OpenCloud/Common/Resource/PersistentResource.php | 4 ++++ .../Tests/Common/Resource/PersistentResourceTest.php | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/Common/Resource/PersistentResource.php b/lib/OpenCloud/Common/Resource/PersistentResource.php index 803112472..bb11b79be 100644 --- a/lib/OpenCloud/Common/Resource/PersistentResource.php +++ b/lib/OpenCloud/Common/Resource/PersistentResource.php @@ -375,6 +375,10 @@ protected function generateJsonPatch($updatedProperties) } } + // Recursively alias current and updated properties + $currentProperties = $this->recursivelyAliasPropertyValue($currentProperties); + $updatedProperties = $this->recursivelyAliasPropertyValue($updatedProperties); + // Generate JSON Patch representation $json = json_encode(JsonPatch::diff($currentProperties, $updatedProperties)); $this->checkJsonError(); diff --git a/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php b/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php index 0cf9342f0..79d350e3b 100644 --- a/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php +++ b/tests/OpenCloud/Tests/Common/Resource/PersistentResourceTest.php @@ -165,6 +165,7 @@ public function testGenerateJsonPatch() array('origin' => 'origin1.phpopencloud.com') ); $this->persistentResource->status = array('message' => 'Creation in progress'); + $this->persistentResource->baz = (object) array( 'fooBar' => 'barbar'); $updateParams = array( 'tags' => array('foo', 'qux', 'baz'), @@ -174,10 +175,12 @@ public function testGenerateJsonPatch() 'origins' => array( array('origin' => 'origin1.phpopencloud.com'), array('origin' => 'origin2.phpopencloud.com') - ) + ), + 'baz' => array('fooBar' => 'barbarbar') ); $expectedJsonPatch = json_encode(array( + array('op' => 'replace', 'path' => '/baz/foo_bar', 'value' => 'barbarbar'), array('op' => 'add', 'path' => '/tags/2', 'value' => 'baz'), array('op' => 'replace', 'path' => '/tags/1', 'value' => 'qux'), array('op' => 'remove', 'path' => '/domains/1'), From 8257700c121704eddf0abf59ef23331e475bbd42 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 6 Jan 2015 03:53:24 -0800 Subject: [PATCH 059/181] Accessing static method... statically. --- tests/OpenCloud/Tests/Image/Resource/ImageTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/OpenCloud/Tests/Image/Resource/ImageTest.php b/tests/OpenCloud/Tests/Image/Resource/ImageTest.php index bcea3e089..4a7554edc 100644 --- a/tests/OpenCloud/Tests/Image/Resource/ImageTest.php +++ b/tests/OpenCloud/Tests/Image/Resource/ImageTest.php @@ -154,6 +154,7 @@ public function testGetPatchHeaders() 'Content-Type' => 'application/openstack-images-v2.1-json-patch' ); - $this->assertEquals($expectedHeaders, $this->image->getPatchHeaders()); + $image = $this->image; + $this->assertEquals($expectedHeaders, $image::getPatchHeaders()); } } From 74a900a6803645169a2457505aa091429bd0aa29 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 6 Jan 2015 05:34:25 -0800 Subject: [PATCH 060/181] Trying GC disabling to kill the segfault. --- phpunit.xml.dist | 1 + 1 file changed, 1 insertion(+) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index be5f3c7e6..1ec5cd508 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -27,6 +27,7 @@ + From 859c7251d1631fa40972a63581175a290bfc9f75 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 6 Jan 2015 05:44:14 -0800 Subject: [PATCH 061/181] Increasing memory limit further to try and kill the segfault. --- phpunit.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 1ec5cd508..3d4b02cd2 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -26,7 +26,7 @@ - + From 1b9f7dea7cc43a468953f3aceeb3c2be8441327f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 7 Jan 2015 04:46:24 -0800 Subject: [PATCH 062/181] Setting version for release. --- lib/OpenCloud/Version.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/OpenCloud/Version.php b/lib/OpenCloud/Version.php index 061ac53d9..3e8504cfb 100644 --- a/lib/OpenCloud/Version.php +++ b/lib/OpenCloud/Version.php @@ -27,7 +27,7 @@ */ class Version { - const VERSION = '1.12.1'; + const VERSION = '1.13.0-alpha1'; /** * @return string Indicate current SDK version. From a6217b8f242beac89201a7f9c71ef8b3d5a6b4d6 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 7 Jan 2015 14:13:30 -0800 Subject: [PATCH 063/181] Using a stable version of the json-patch-php package. --- composer.json | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/composer.json b/composer.json index 76027703a..9c1752463 100644 --- a/composer.json +++ b/composer.json @@ -25,17 +25,11 @@ "OpenCloud": ["lib/", "tests/"] } }, - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/ycombinator/json-patch-php" - } - ], "require": { "php" : ">=5.3.3", "guzzle/http" : "~3.8", "psr/log": "~1.0", - "mikemccabe/json-patch-php": "dev-master" + "mikemccabe/json-patch-php": "~0.1" }, "require-dev" : { "phpunit/phpunit": "4.3.*", From 5b2a951c408abe032914714ceef90b2931526aab Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 3 Apr 2015 19:58:32 +0200 Subject: [PATCH 064/181] Use correct link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5f4d75da5..12fb530b8 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Requirements * PHP >=5.4 * cURL extension for PHP -**Note**: Since PHP 5.3 has reached [end of life](http://php.net/eol.php) and is no longer officially supported, we are moving to 5.4 as a minimum requirement. If upgrading is not an option and you still need a stable version of the SDK for 5.3, please follow [this guide](http://docs.php-opencloud.com/en/latest/using-php-5.3). +**Note**: Since PHP 5.3 has reached [end of life](http://php.net/eol.php) and is no longer officially supported, we are moving to 5.4 as a minimum requirement. If upgrading is not an option and you still need a stable version of the SDK for 5.3, please follow [this guide](http://docs.php-opencloud.com/en/latest/using-php-5.3.html). Installation ------------ From 51223391a413017d0a8b86f619d4494547232d34 Mon Sep 17 00:00:00 2001 From: AdamMerrifield Date: Sun, 5 Apr 2015 22:08:55 -0400 Subject: [PATCH 065/181] Guzzle Backoff Correction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first parameter in Guzzle’s BackoffPlugin is the max number of retries to attempt. --- doc/services/object-store/migrating-containers.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/services/object-store/migrating-containers.rst b/doc/services/object-store/migrating-containers.rst index da983af3e..2a985d20a 100644 --- a/doc/services/object-store/migrating-containers.rst +++ b/doc/services/object-store/migrating-containers.rst @@ -37,13 +37,13 @@ Requirements use Guzzle\Plugin\Backoff\BackoffPlugin; - // set timeout in secs - $timeout = 10; + // maximum number of retries + $maxRetries = 10; // set HTTP error codes $httpErrors = array(500, 503, 408); - $backoffPlugin = BackoffPlugin::getExponentialBackoff($timeout, $httpErrors); + $backoffPlugin = BackoffPlugin::getExponentialBackoff($maxRetries, $httpErrors); $client->addSubscriber($backoffPlugin); From baeaf15cef233db7d203e0da3273215f02f6eb08 Mon Sep 17 00:00:00 2001 From: AdamMerrifield Date: Mon, 6 Apr 2015 07:28:25 -0400 Subject: [PATCH 066/181] Fix method in documentation of Object->getContent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under the ‘get content of file’ header the code block should be $object->getContent(); --- doc/services/object-store/objects.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/services/object-store/objects.rst b/doc/services/object-store/objects.rst index e23d6d4cb..7e32f3610 100644 --- a/doc/services/object-store/objects.rst +++ b/doc/services/object-store/objects.rst @@ -259,7 +259,7 @@ Get content of file .. code-block:: php /** @param $content Guzzle\Http\EntityBody */ - $content = $object->getContainer(); + $content = $object->getContent(); Get type of file From d16851c31723e6ecea7283086bfd965946c53d5f Mon Sep 17 00:00:00 2001 From: Richard Date: Tue, 6 Jan 2015 15:12:39 +0100 Subject: [PATCH 067/181] replace Logger::deprecated with PRS-3 Logger::warning --- lib/OpenCloud/Common/Collection.php | 3 ++- lib/OpenCloud/Common/Collection/ResourceIterator.php | 3 ++- lib/OpenCloud/Common/Log/Logger.php | 4 ++++ lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php | 6 ++++-- lib/OpenCloud/LoadBalancer/Service.php | 3 ++- lib/OpenCloud/ObjectStore/Service.php | 3 ++- lib/OpenCloud/OpenStack.php | 9 ++++++--- 7 files changed, 22 insertions(+), 9 deletions(-) diff --git a/lib/OpenCloud/Common/Collection.php b/lib/OpenCloud/Common/Collection.php index f2710639e..b6fe7471b 100644 --- a/lib/OpenCloud/Common/Collection.php +++ b/lib/OpenCloud/Common/Collection.php @@ -50,7 +50,8 @@ class Collection extends Base */ public function __construct($service, $class, array $array = array()) { - $service->getLogger()->deprecated(__METHOD__, 'OpenCloud\Common\Collection\CollectionBuilder'); + $service->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead', __METHOD__, 'OpenCloud\Common\Collection\CollectionBuilder')); $this->setService($service); diff --git a/lib/OpenCloud/Common/Collection/ResourceIterator.php b/lib/OpenCloud/Common/Collection/ResourceIterator.php index 627ed78eb..a95455386 100644 --- a/lib/OpenCloud/Common/Collection/ResourceIterator.php +++ b/lib/OpenCloud/Common/Collection/ResourceIterator.php @@ -223,7 +223,8 @@ public function getElement($offset) */ public function first() { - Logger::newInstance()->deprecated(__METHOD__, 'getElement'); + Logger::newInstance()->warning(sprintf( + 'The %s method is deprecated, please use %s instead', __METHOD__, 'getElement')); return $this->getElement(0); } diff --git a/lib/OpenCloud/Common/Log/Logger.php b/lib/OpenCloud/Common/Log/Logger.php index 7eb48cdc0..56cb7cbf2 100644 --- a/lib/OpenCloud/Common/Log/Logger.php +++ b/lib/OpenCloud/Common/Log/Logger.php @@ -239,6 +239,10 @@ private function dispatch($message, $context) } } + /** + * @deprecated use warning for deprecated messages + * @see http://www.php-fig.org/psr/psr-3/ + */ public function deprecated($method, $new) { $string = sprintf('The %s method is deprecated, please use %s instead', $method, $new); diff --git a/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php b/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php index bd0742bcb..080dbb732 100644 --- a/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php +++ b/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php @@ -621,7 +621,8 @@ public function enableConnectionLogging($bool) */ public function connectionLogging() { - $this->getLogger()->deprecated(__METHOD__, 'hasConnectionLogging or enableConnectionLogging'); + $this->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead', __METHOD__, 'hasConnectionLogging or enableConnectionLogging')); } /** @@ -663,7 +664,8 @@ public function enableContentCaching($bool) */ public function contentCaching() { - $this->getLogger()->deprecated(__METHOD__, 'hasContentCaching or setContentCaching'); + $this->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead', __METHOD__, 'hasContentCaching or setContentCaching')); } /** diff --git a/lib/OpenCloud/LoadBalancer/Service.php b/lib/OpenCloud/LoadBalancer/Service.php index 8ba659f87..c11022114 100644 --- a/lib/OpenCloud/LoadBalancer/Service.php +++ b/lib/OpenCloud/LoadBalancer/Service.php @@ -62,7 +62,8 @@ public function loadBalancerList($detail = true, array $filter = array()) */ public function billableLoadBalancer($id = null) { - $this->getLogger()->deprecated(__METHOD__, 'loadBalancer'); + $this->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead', __METHOD__, 'loadBalancer')); return $this->resource('LoadBalancer', $id); } diff --git a/lib/OpenCloud/ObjectStore/Service.php b/lib/OpenCloud/ObjectStore/Service.php index a2d01a479..ce3446880 100644 --- a/lib/OpenCloud/ObjectStore/Service.php +++ b/lib/OpenCloud/ObjectStore/Service.php @@ -174,7 +174,8 @@ public function bulkExtract($path = '', $archive, $archiveType = UrlType::TAR_GZ */ public function bulkDelete(array $paths) { - $this->getLogger()->deprecated(__METHOD__, '::batchDelete()'); + $this->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead', __METHOD__, '::batchDelete()')); return $this->executeBatchDeleteRequest($paths); } diff --git a/lib/OpenCloud/OpenStack.php b/lib/OpenCloud/OpenStack.php index 6bc6eeba1..3511bc4f4 100644 --- a/lib/OpenCloud/OpenStack.php +++ b/lib/OpenCloud/OpenStack.php @@ -165,7 +165,8 @@ public function getTokenObject() */ public function setExpiration($expiration) { - $this->getLogger()->deprecated(__METHOD__, '::getTokenObject()->setExpires()'); + $this->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead',__METHOD__, '::getTokenObject()->setExpires()')); if ($this->getTokenObject()) { $this->getTokenObject()->setExpires($expiration); } @@ -178,7 +179,8 @@ public function setExpiration($expiration) */ public function getExpiration() { - $this->getLogger()->deprecated(__METHOD__, '::getTokenObject()->getExpires()'); + $this->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead',__METHOD__, '::getTokenObject()->getExpires()')); if ($this->getTokenObject()) { return $this->getTokenObject()->getExpires(); } @@ -290,7 +292,8 @@ public function getLogger() */ public function hasExpired() { - $this->getLogger()->deprecated(__METHOD__, 'getTokenObject()->hasExpired()'); + $this->getLogger()->warning(sprintf( + 'The %s method is deprecated, please use %s instead', __METHOD__, 'getTokenObject()->hasExpired()')); return $this->getTokenObject() && $this->getTokenObject()->hasExpired(); } From fd9fcefb026a6d989b9acce6c98252b803d53b0e Mon Sep 17 00:00:00 2001 From: Richard Date: Tue, 6 Jan 2015 17:41:36 +0100 Subject: [PATCH 068/181] move deprecation message to static function --- lib/OpenCloud/Common/Collection.php | 5 +++-- lib/OpenCloud/Common/Collection/ResourceIterator.php | 3 +-- lib/OpenCloud/Common/Log/Logger.php | 8 +++----- lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php | 4 ++-- lib/OpenCloud/LoadBalancer/Service.php | 4 ++-- lib/OpenCloud/ObjectStore/Service.php | 4 ++-- lib/OpenCloud/OpenStack.php | 10 ++++------ tests/OpenCloud/Tests/Common/Log/LoggerTest.php | 8 ++++++++ 8 files changed, 25 insertions(+), 21 deletions(-) diff --git a/lib/OpenCloud/Common/Collection.php b/lib/OpenCloud/Common/Collection.php index b6fe7471b..f15e83c47 100644 --- a/lib/OpenCloud/Common/Collection.php +++ b/lib/OpenCloud/Common/Collection.php @@ -17,6 +17,8 @@ namespace OpenCloud\Common; +use OpenCloud\Common\Log\Logger; + /** * @deprecated * @codeCoverageIgnore @@ -50,8 +52,7 @@ class Collection extends Base */ public function __construct($service, $class, array $array = array()) { - $service->getLogger()->warning(sprintf( - 'The %s method is deprecated, please use %s instead', __METHOD__, 'OpenCloud\Common\Collection\CollectionBuilder')); + $service->getLogger()->warning(Logger::deprecated(__METHOD__, 'OpenCloud\Common\Collection\CollectionBuilder')); $this->setService($service); diff --git a/lib/OpenCloud/Common/Collection/ResourceIterator.php b/lib/OpenCloud/Common/Collection/ResourceIterator.php index a95455386..c0054b8d1 100644 --- a/lib/OpenCloud/Common/Collection/ResourceIterator.php +++ b/lib/OpenCloud/Common/Collection/ResourceIterator.php @@ -223,8 +223,7 @@ public function getElement($offset) */ public function first() { - Logger::newInstance()->warning(sprintf( - 'The %s method is deprecated, please use %s instead', __METHOD__, 'getElement')); + Logger::newInstance()->warning(Logger::deprecated(__METHOD__, 'getElement')); return $this->getElement(0); } diff --git a/lib/OpenCloud/Common/Log/Logger.php b/lib/OpenCloud/Common/Log/Logger.php index 56cb7cbf2..b054fc004 100644 --- a/lib/OpenCloud/Common/Log/Logger.php +++ b/lib/OpenCloud/Common/Log/Logger.php @@ -240,13 +240,11 @@ private function dispatch($message, $context) } /** - * @deprecated use warning for deprecated messages + * Helper method, use PSR-3 warning function for deprecation warnings * @see http://www.php-fig.org/psr/psr-3/ */ - public function deprecated($method, $new) + public static function deprecated($method, $new) { - $string = sprintf('The %s method is deprecated, please use %s instead', $method, $new); - - return $this->warning($string); + return sprintf('The %s method is deprecated, please use %s instead', $method, $new); } } diff --git a/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php b/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php index 080dbb732..cc3e85339 100644 --- a/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php +++ b/lib/OpenCloud/LoadBalancer/Resource/LoadBalancer.php @@ -18,6 +18,7 @@ namespace OpenCloud\LoadBalancer\Resource; use OpenCloud\Common\Exceptions; +use OpenCloud\Common\Log\Logger; use OpenCloud\Common\Resource\PersistentResource; use OpenCloud\DNS\Resource\HasPtrRecordsInterface; use OpenCloud\LoadBalancer\Enum\NodeCondition; @@ -621,8 +622,7 @@ public function enableConnectionLogging($bool) */ public function connectionLogging() { - $this->getLogger()->warning(sprintf( - 'The %s method is deprecated, please use %s instead', __METHOD__, 'hasConnectionLogging or enableConnectionLogging')); + $this->getLogger()->warning(Logger::deprecated(__METHOD__, 'hasConnectionLogging or enableConnectionLogging')); } /** diff --git a/lib/OpenCloud/LoadBalancer/Service.php b/lib/OpenCloud/LoadBalancer/Service.php index c11022114..93905a0d2 100644 --- a/lib/OpenCloud/LoadBalancer/Service.php +++ b/lib/OpenCloud/LoadBalancer/Service.php @@ -17,6 +17,7 @@ namespace OpenCloud\LoadBalancer; +use OpenCloud\Common\Log\Logger; use OpenCloud\Common\Service\NovaService; /** @@ -62,8 +63,7 @@ public function loadBalancerList($detail = true, array $filter = array()) */ public function billableLoadBalancer($id = null) { - $this->getLogger()->warning(sprintf( - 'The %s method is deprecated, please use %s instead', __METHOD__, 'loadBalancer')); + $this->getLogger()->warning(Logger::deprecated(__METHOD__, 'loadBalancer')); return $this->resource('LoadBalancer', $id); } diff --git a/lib/OpenCloud/ObjectStore/Service.php b/lib/OpenCloud/ObjectStore/Service.php index ce3446880..66735dea8 100644 --- a/lib/OpenCloud/ObjectStore/Service.php +++ b/lib/OpenCloud/ObjectStore/Service.php @@ -24,6 +24,7 @@ use OpenCloud\Common\Exceptions\InvalidArgumentError; use OpenCloud\Common\Http\Client; use OpenCloud\Common\Http\Message\Formatter; +use OpenCloud\Common\Log\Logger; use OpenCloud\Common\Service\ServiceBuilder; use OpenCloud\ObjectStore\Constants\UrlType; use OpenCloud\ObjectStore\Resource\Container; @@ -174,8 +175,7 @@ public function bulkExtract($path = '', $archive, $archiveType = UrlType::TAR_GZ */ public function bulkDelete(array $paths) { - $this->getLogger()->warning(sprintf( - 'The %s method is deprecated, please use %s instead', __METHOD__, '::batchDelete()')); + $this->getLogger()->warning(Logger::deprecated(__METHOD__, '::batchDelete()')); return $this->executeBatchDeleteRequest($paths); } diff --git a/lib/OpenCloud/OpenStack.php b/lib/OpenCloud/OpenStack.php index 3511bc4f4..8e177135f 100644 --- a/lib/OpenCloud/OpenStack.php +++ b/lib/OpenCloud/OpenStack.php @@ -23,6 +23,7 @@ use OpenCloud\Common\Http\Message\Formatter; use OpenCloud\Common\Http\Message\RequestSubscriber; use OpenCloud\Common\Lang; +use OpenCloud\Common\Log\Logger; use OpenCloud\Common\Service\Catalog; use OpenCloud\Common\Service\ServiceBuilder; use OpenCloud\Identity\Resource\Tenant; @@ -165,8 +166,7 @@ public function getTokenObject() */ public function setExpiration($expiration) { - $this->getLogger()->warning(sprintf( - 'The %s method is deprecated, please use %s instead',__METHOD__, '::getTokenObject()->setExpires()')); + $this->getLogger()->warning(Logger::deprecated(__METHOD__, '::getTokenObject()->setExpires()')); if ($this->getTokenObject()) { $this->getTokenObject()->setExpires($expiration); } @@ -179,8 +179,7 @@ public function setExpiration($expiration) */ public function getExpiration() { - $this->getLogger()->warning(sprintf( - 'The %s method is deprecated, please use %s instead',__METHOD__, '::getTokenObject()->getExpires()')); + $this->getLogger()->warning(Logger::deprecated(__METHOD__, '::getTokenObject()->getExpires()')); if ($this->getTokenObject()) { return $this->getTokenObject()->getExpires(); } @@ -292,8 +291,7 @@ public function getLogger() */ public function hasExpired() { - $this->getLogger()->warning(sprintf( - 'The %s method is deprecated, please use %s instead', __METHOD__, 'getTokenObject()->hasExpired()')); + $this->getLogger()->warning(Logger::deprecated(__METHOD__, 'getTokenObject()->hasExpired()')); return $this->getTokenObject() && $this->getTokenObject()->hasExpired(); } diff --git a/tests/OpenCloud/Tests/Common/Log/LoggerTest.php b/tests/OpenCloud/Tests/Common/Log/LoggerTest.php index da06da6d0..c18f38c62 100644 --- a/tests/OpenCloud/Tests/Common/Log/LoggerTest.php +++ b/tests/OpenCloud/Tests/Common/Log/LoggerTest.php @@ -85,4 +85,12 @@ public function testOutputFailsWithIncorrectFile() $this->logger->emergency('Can anyone see this?'); } + + public function testDeprecationMessage() + { + $this->assertEquals( + 'The OpenCloud\Tests\Common\Log\LoggerTest::testDeprecationMessage method is deprecated, please use testMethod instead', + $this->logger->deprecated(__METHOD__, 'testMethod') + ); + } } From 5b5fc0fc3092f3f4b16c2beb0bbf0e830e75714b Mon Sep 17 00:00:00 2001 From: Richard Date: Wed, 7 Jan 2015 10:47:14 +0100 Subject: [PATCH 069/181] + inject Logger in service when available in Client * allow OpenStack Logger to be set via options array --- lib/OpenCloud/Common/Base.php | 8 +++++ .../Common/Service/CatalogService.php | 6 ++++ lib/OpenCloud/Identity/Service.php | 7 ++++ lib/OpenCloud/OpenStack.php | 12 +++++++ tests/OpenCloud/Tests/OpenStackTest.php | 35 +++++++++++++++++++ 5 files changed, 68 insertions(+) diff --git a/lib/OpenCloud/Common/Base.php b/lib/OpenCloud/Common/Base.php index fd638cc81..82bf0061b 100644 --- a/lib/OpenCloud/Common/Base.php +++ b/lib/OpenCloud/Common/Base.php @@ -266,6 +266,14 @@ public function getLogger() return $this->logger; } + /** + * @return bool + */ + public function hasLogger() + { + return (null !== $this->logger); + } + /** * @deprecated */ diff --git a/lib/OpenCloud/Common/Service/CatalogService.php b/lib/OpenCloud/Common/Service/CatalogService.php index addcd170b..69e5c659d 100644 --- a/lib/OpenCloud/Common/Service/CatalogService.php +++ b/lib/OpenCloud/Common/Service/CatalogService.php @@ -20,8 +20,10 @@ use Guzzle\Http\ClientInterface; use Guzzle\Http\Exception\BadResponseException; use Guzzle\Http\Url; +use OpenCloud\Common\Base; use OpenCloud\Common\Exceptions; use OpenCloud\Common\Http\Message\Formatter; +use OpenCloud\OpenStack; use Symfony\Component\EventDispatcher\EventSubscriberInterface; abstract class CatalogService extends AbstractService @@ -71,6 +73,10 @@ abstract class CatalogService extends AbstractService */ public function __construct(ClientInterface $client, $type = null, $name = null, $region = null, $urlType = null) { + if (($client instanceof Base || $client instanceof OpenStack) && $client->hasLogger()) { + $this->setLogger($client->getLogger()); + } + $this->setClient($client); $this->name = $name ? : static::DEFAULT_NAME; diff --git a/lib/OpenCloud/Identity/Service.php b/lib/OpenCloud/Identity/Service.php index 9c90d2811..4e34f1e24 100644 --- a/lib/OpenCloud/Identity/Service.php +++ b/lib/OpenCloud/Identity/Service.php @@ -18,11 +18,13 @@ namespace OpenCloud\Identity; use Guzzle\Http\ClientInterface; +use OpenCloud\Common\Base; use OpenCloud\Common\Collection\PaginatedIterator; use OpenCloud\Common\Collection\ResourceIterator; use OpenCloud\Common\Http\Message\Formatter; use OpenCloud\Common\Service\AbstractService; use OpenCloud\Identity\Constants\User as UserConst; +use OpenCloud\OpenStack; /** * Class responsible for working with Rackspace's Cloud Identity service. @@ -40,6 +42,11 @@ class Service extends AbstractService public static function factory(ClientInterface $client) { $identity = new self(); + + if (($client instanceof Base || $client instanceof OpenStack) && $client->hasLogger()) { + $identity->setLogger($client->getLogger()); + } + $identity->setClient($client); $identity->setEndpoint(clone $client->getAuthUrl()); diff --git a/lib/OpenCloud/OpenStack.php b/lib/OpenCloud/OpenStack.php index 8e177135f..e970b9912 100644 --- a/lib/OpenCloud/OpenStack.php +++ b/lib/OpenCloud/OpenStack.php @@ -79,6 +79,10 @@ class OpenStack extends Client public function __construct($url, array $secret, array $options = array()) { + if (isset($options['logger']) && $options['logger'] instanceof LoggerInterface) { + $this->setLogger($options['logger']); + } + $this->setSecret($secret); $this->setAuthUrl($url); @@ -286,6 +290,14 @@ public function getLogger() return $this->logger; } + /** + * @return bool + */ + public function hasLogger() + { + return (null !== $this->logger); + } + /** * @deprecated */ diff --git a/tests/OpenCloud/Tests/OpenStackTest.php b/tests/OpenCloud/Tests/OpenStackTest.php index f38f3777b..8ff20892a 100644 --- a/tests/OpenCloud/Tests/OpenStackTest.php +++ b/tests/OpenCloud/Tests/OpenStackTest.php @@ -184,4 +184,39 @@ public function test_Import_Credentials_Numeric_Tenant() $this->assertEquals('{expiration}', $this->client->getExpiration()); $this->assertEquals($randomNumericTenant, $this->client->getTenant()); } + + public function testLoggerServiceInjection() + { + // Create a new client, pass stub via constructor options argument + $stubLogger = $this->getMock('Psr\Log\NullLogger'); + $client = new OpenStack(Rackspace::US_IDENTITY_ENDPOINT, $this->credentials, array( + 'logger' => $stubLogger, + )); + $client->addSubscriber(new MockSubscriber()); + + // Test all OpenStack factory methods on proper Logger service injection + $service = $client->objectStoreService('cloudFiles', 'DFW'); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + + $service = $service->getCdnService(); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + + $service = $client->computeService('cloudServersOpenStack', 'DFW'); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + + $service = $client->orchestrationService(null, 'DFW'); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + + $service = $client->volumeService('cloudBlockStorage', 'DFW'); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + + $service = $client->identityService(); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + + $service = $client->imageService('cloudImages', 'IAD'); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + + $service = $client->networkingService(null, 'IAD'); + $this->assertContains("Mock_NullLogger", get_class($service->getLogger())); + } } From 208a9b71953e9c56ef8c5a214b53c86ea4b7cc2d Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Wed, 7 Jan 2015 15:22:14 +0100 Subject: [PATCH 070/181] Update getting-started.md added information about injecting `Logger` in the client --- docs/getting-started.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/getting-started.md b/docs/getting-started.md index 48f99fb86..f47daf5cf 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -55,6 +55,11 @@ You can see in the first example that the constant `Rackspace::US_IDENTITY_ENDPO Rackspace's identity endpoint (`https://identity.api.rackspacecloud.com/v2.0/`). Another difference is that Rackspace uses API key for authentication, whereas OpenStack uses a generic password. +#### 1.2 Logger injection +As the `Rackspace` client extends the `OpenStack` client, they both support passing `$options` as an array via the constructor's third parameter. The options are passed as a config to the `Guzzle` client, but also allow to inject your own `Logger`. + +Your logger should implement the `Psr\Log\LoggerInterface` [as defined in PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md). Example of a compatible logger is [`Monolog`](https://github.com/Seldaek/monolog). When the client does create a service, it will inject the logger if one is available. + ### 2. Pick what service you want to use In this case, we want to use the Compute (Nova) service: @@ -175,4 +180,4 @@ $callback = function($server) { $server->waitFor(ServerState::ACTIVE, 600, $callback); ``` So, the server will be polled until it is in an `ACTIVE` state, with a timeout of 600 seconds. When the poll happens, the -callback function is executed - which in this case just logs some output. \ No newline at end of file +callback function is executed - which in this case just logs some output. From 7f04cf2a8dac8b00b67f6dca704ec331ae054108 Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Wed, 7 Jan 2015 15:26:47 +0100 Subject: [PATCH 071/181] Update Clients.md also add `Logger` injection to Clients userguide --- docs/userguide/Clients.md | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/docs/userguide/Clients.md b/docs/userguide/Clients.md index 9a7efec8e..70f1a8131 100644 --- a/docs/userguide/Clients.md +++ b/docs/userguide/Clients.md @@ -11,7 +11,7 @@ Users have access to two types of client: `OpenCloud\OpenStack` and `OpenCloud\R 3. `OpenCloud\OpenStack` 4. `OpenCloud\Rackspace` -## Initializing a client +## 1. Initializing a client ### Rackspace @@ -44,7 +44,29 @@ $client = new OpenStack('http://identity.my-openstack.com/v2.0', array( )); ``` -## Authentication +#### 1.2 Logger injection +As the `Rackspace` client extends the `OpenStack` client, they both support passing `$options` as an array via the constructor's third parameter. The options are passed as a config to the `Guzzle` client, but also allow to inject your own `Logger`. + +Your logger should implement the `Psr\Log\LoggerInterface` [as defined in PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md). Example of a compatible logger is [`Monolog`](https://github.com/Seldaek/monolog). When the client does create a service, it will inject the logger if one is available. + +To inject a `LoggerInterface` compatible logger into a new `Client`: + +```php +use Monolog\Logger; +use OpenCloud\OpenStack; + +// create a log channel +$log = new Logger('name'); + +$client = new OpenStack('http://identity.my-openstack.com/v2.0', array( + 'username' => 'foo', + 'password' => 'bar' +), array( + 'logger' => $log, +)); +``` + +## 2. Authentication The Client does not automatically authenticate against the API on object creation - it waits for an API call. When this happens, it checks whether the current "token" has expired, and (re-)authenticates if necessary. @@ -56,7 +78,7 @@ $client->authenticate(); If the credentials are incorrect, a `401` error will be returned. If credentials are correct, a `200` status is returned with your Service Catalog. -## Service Catalog +## 3. Service Catalog The Service Catalog is returned on successful authentication, and is composed of all the different API services available to the current tenant. All of this functionality is encapsulated in the `Catalog` object, which allows you greater control and interactivity. @@ -86,7 +108,7 @@ foreach ($catalog->getItems() as $catalogItem) { As you can see, you have access to each Service's name, type and list of endpoints. Each endpoint provides access to the specific region, along with its public and private endpoint URLs. -## Default HTTP headers +## 4. Default HTTP headers To set default HTTP headers: @@ -94,6 +116,6 @@ To set default HTTP headers: $client->setDefaultOption('headers/X-Custom-Header', 'FooBar'); ``` -## Other functionality +## 5. Other functionality -For a full list of functionality provided by Guzzle, please consult the [official documentation](http://docs.guzzlephp.org/en/latest/http-client/client.html). \ No newline at end of file +For a full list of functionality provided by Guzzle, please consult the [official documentation](http://docs.guzzlephp.org/en/latest/http-client/client.html). From 5cb4ac7bf887c206b806778ba1df39485e619999 Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Wed, 7 Jan 2015 15:28:26 +0100 Subject: [PATCH 072/181] Link getting-started.md to the clients userguide --- docs/getting-started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/getting-started.md b/docs/getting-started.md index f47daf5cf..e661e0ce8 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -58,7 +58,7 @@ uses API key for authentication, whereas OpenStack uses a generic password. #### 1.2 Logger injection As the `Rackspace` client extends the `OpenStack` client, they both support passing `$options` as an array via the constructor's third parameter. The options are passed as a config to the `Guzzle` client, but also allow to inject your own `Logger`. -Your logger should implement the `Psr\Log\LoggerInterface` [as defined in PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md). Example of a compatible logger is [`Monolog`](https://github.com/Seldaek/monolog). When the client does create a service, it will inject the logger if one is available. +Prerequisities and usage example can be found in [the Clients userguide](/docs/userguide/Clients.md#12-logger-injection) ### 2. Pick what service you want to use From b153504bbcd130918697be7919a70dd0441c08ef Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 8 Jan 2015 16:12:13 +0100 Subject: [PATCH 073/181] Add mock HTTP responses --- .../_response/LoadBalancers1.resp | 80 +++++++++++++++++++ .../_response/LoadBalancers2.resp | 80 +++++++++++++++++++ .../_response/LoadBalancers3.resp | 34 ++++++++ 3 files changed, 194 insertions(+) create mode 100644 tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers1.resp create mode 100644 tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers2.resp create mode 100644 tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers3.resp diff --git a/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers1.resp b/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers1.resp new file mode 100644 index 000000000..1827f2b44 --- /dev/null +++ b/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers1.resp @@ -0,0 +1,80 @@ +HTTP/1.1 200 OK +Status: 200 OK +Date: Thu, 28 Jul 2011 21:54:21 GMT +X-API-VERSION: 1.0.17 +Content-Type: application/json +Content-Length: 1975 + +{ + "loadBalancers":[ + { + "name":"lb-site1", + "id":1, + "protocol":"HTTP", + "port":80, + "algorithm":"RANDOM", + "status":"ACTIVE", + "nodeCount":3, + "virtualIps":[ + { + "id":403, + "address":"206.55.130.1", + "type":"PUBLIC", + "ipVersion":"IPV4" + } + ], + "created":{ + "time":"2010-11-30T03:23:42Z" + }, + "updated":{ + "time":"2010-11-30T03:23:44Z" + } + }, + { + "name":"lb-site2", + "id":2, + "protocol":"HTTP", + "port":80, + "algorithm":"RANDOM", + "status":"ACTIVE", + "nodeCount":4, + "virtualIps":[ + { + "id":401, + "address":"206.55.130.2", + "type":"PUBLIC", + "ipVersion":"IPV4" + } + ], + "created":{ + "time":"2010-11-30T03:23:42Z" + }, + "updated":{ + "time":"2010-11-30T03:23:44Z" + } + }, + { + "name":"lb-site3", + "id":3, + "protocol":"HTTP", + "port":80, + "algorithm":"RANDOM", + "status":"ACTIVE", + "nodeCount":4, + "virtualIps":[ + { + "id":401, + "address":"206.55.130.2", + "type":"PUBLIC", + "ipVersion":"IPV4" + } + ], + "created":{ + "time":"2010-11-30T03:23:42Z" + }, + "updated":{ + "time":"2010-11-30T03:23:44Z" + } + } + ] +} \ No newline at end of file diff --git a/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers2.resp b/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers2.resp new file mode 100644 index 000000000..2ab7b2381 --- /dev/null +++ b/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers2.resp @@ -0,0 +1,80 @@ +HTTP/1.1 200 OK +Status: 200 OK +Date: Thu, 28 Jul 2011 21:54:21 GMT +X-API-VERSION: 1.0.17 +Content-Type: application/json +Content-Length: 1975 + +{ + "loadBalancers":[ + { + "name":"lb-site3", + "id":3, + "protocol":"HTTP", + "port":80, + "algorithm":"RANDOM", + "status":"ACTIVE", + "nodeCount":4, + "virtualIps":[ + { + "id":401, + "address":"206.55.130.2", + "type":"PUBLIC", + "ipVersion":"IPV4" + } + ], + "created":{ + "time":"2010-11-30T03:23:42Z" + }, + "updated":{ + "time":"2010-11-30T03:23:44Z" + } + }, + { + "name":"lb-site4", + "id":4, + "protocol":"HTTP", + "port":80, + "algorithm":"RANDOM", + "status":"ACTIVE", + "nodeCount":4, + "virtualIps":[ + { + "id":401, + "address":"206.55.130.2", + "type":"PUBLIC", + "ipVersion":"IPV4" + } + ], + "created":{ + "time":"2010-11-30T03:23:42Z" + }, + "updated":{ + "time":"2010-11-30T03:23:44Z" + } + }, + { + "name":"lb-site5", + "id":5, + "protocol":"HTTP", + "port":80, + "algorithm":"RANDOM", + "status":"ACTIVE", + "nodeCount":4, + "virtualIps":[ + { + "id":401, + "address":"206.55.130.2", + "type":"PUBLIC", + "ipVersion":"IPV4" + } + ], + "created":{ + "time":"2010-11-30T03:23:42Z" + }, + "updated":{ + "time":"2010-11-30T03:23:44Z" + } + } + ] +} \ No newline at end of file diff --git a/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers3.resp b/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers3.resp new file mode 100644 index 000000000..554a4430d --- /dev/null +++ b/tests/OpenCloud/Tests/LoadBalancer/_response/LoadBalancers3.resp @@ -0,0 +1,34 @@ +HTTP/1.1 200 OK +Status: 200 OK +Date: Thu, 28 Jul 2011 21:54:21 GMT +X-API-VERSION: 1.0.17 +Content-Type: application/json +Content-Length: 1975 + +{ + "loadBalancers":[ + { + "name":"lb-site5", + "id":5, + "protocol":"HTTP", + "port":80, + "algorithm":"RANDOM", + "status":"ACTIVE", + "nodeCount":4, + "virtualIps":[ + { + "id":401, + "address":"206.55.130.2", + "type":"PUBLIC", + "ipVersion":"IPV4" + } + ], + "created":{ + "time":"2010-11-30T03:23:42Z" + }, + "updated":{ + "time":"2010-11-30T03:23:44Z" + } + } + ] +} \ No newline at end of file From 4380e4ec0e58ce213f5717a82bd5f4f7ce987faf Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 8 Jan 2015 16:13:22 +0100 Subject: [PATCH 074/181] Decouple the process of retrieving last element from setting marker --- lib/OpenCloud/Common/Collection/PaginatedIterator.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/OpenCloud/Common/Collection/PaginatedIterator.php b/lib/OpenCloud/Common/Collection/PaginatedIterator.php index a0628993d..ef827ac80 100644 --- a/lib/OpenCloud/Common/Collection/PaginatedIterator.php +++ b/lib/OpenCloud/Common/Collection/PaginatedIterator.php @@ -145,7 +145,11 @@ public function updateMarkerToCurrent() } $element = $this->elements[$this->position]; + $this->setMarkerFromElement($element); + } + protected function setMarkerFromElement($element) + { $key = $this->getOption('key.marker'); if (isset($element->$key)) { From d4fa19512fbb77afeea34a32fdd42929614e65cd Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 8 Jan 2015 16:13:39 +0100 Subject: [PATCH 075/181] Add new iterator to handle differences --- .../Collection/LoadBalancerIterator.php | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php diff --git a/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php b/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php new file mode 100644 index 000000000..f554c6512 --- /dev/null +++ b/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php @@ -0,0 +1,43 @@ +getQuery(); + $query['limit'] = $query['limit'] + 1; + $url->setQuery($query); + + return $url; + } + + public function updateMarkerToCurrent() + { + $this->setMarkerFromElement($this->nextElement); + } + + public function parseResponseBody($body) + { + $response = parent::parseResponseBody($body); + + if (count($response) >= $this->getOption('limit.page')) { + // Save last element (we will need it for the next marker) + $this->nextElement = end($response); + + // Since we previously asked for n+1 elements, pop the unwanted element + array_pop($response); + reset($response); + } + + return $response; + } +} \ No newline at end of file From f9dda99147f6d81b9bed1e0f1c3213d00e220086 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 8 Jan 2015 16:13:51 +0100 Subject: [PATCH 076/181] Implement into service and refactor tests --- lib/OpenCloud/LoadBalancer/Service.php | 12 ++++- .../Tests/LoadBalancer/ServiceTest.php | 48 ++++++++++++++----- tests/OpenCloud/Tests/OpenCloudTestCase.php | 13 ++--- 3 files changed, 51 insertions(+), 22 deletions(-) diff --git a/lib/OpenCloud/LoadBalancer/Service.php b/lib/OpenCloud/LoadBalancer/Service.php index 93905a0d2..6f5052f2c 100644 --- a/lib/OpenCloud/LoadBalancer/Service.php +++ b/lib/OpenCloud/LoadBalancer/Service.php @@ -19,6 +19,7 @@ use OpenCloud\Common\Log\Logger; use OpenCloud\Common\Service\NovaService; +use OpenCloud\LoadBalancer\Collection\LoadBalancerIterator; /** * Class that encapsulates the Rackspace Cloud Load Balancers service @@ -51,11 +52,20 @@ public function loadBalancer($id = null) */ public function loadBalancerList($detail = true, array $filter = array()) { + $options = $this->makeResourceIteratorOptions($this->resolveResourceClass('LoadBalancer')); + + if (isset($filter['limit'])) { + $options['limit.page'] = $filter['limit']; + unset($filter['limit']); + } + $url = $this->getUrl(); $url->addPath(Resource\LoadBalancer::resourceName()); $url->setQuery($filter); - return $this->resourceList('LoadBalancer', $url); + $options += array('baseUrl' => $url, 'key.marker' => 'id'); + + return LoadBalancerIterator::factory($this, $options); } /** diff --git a/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php b/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php index 6bd047064..2d01e2f93 100644 --- a/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php +++ b/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php @@ -27,15 +27,13 @@ namespace OpenCloud\Tests\LoadBalancer; -class ServiceTest extends \OpenCloud\Tests\OpenCloudTestCase -{ - private $service; - - public function setupObjects() - { - $this->service = $this->getClient()->loadBalancerService('cloudLoadBalancers', 'DFW', 'publicURL'); - } +use Guzzle\Http\Message\Response; +use Guzzle\Plugin\Mock\MockPlugin; +use OpenCloud\Rackspace; +use OpenCloud\Tests\MockSubscriber; +class ServiceTest extends LoadBalancerTestCase +{ public function test__construct() { $this->assertInstanceOf( @@ -52,12 +50,36 @@ public function testLoadBalancer() ); } - public function testLoadBalancerList() + public function test_Listing_Load_Balancers() { - $this->assertInstanceOf( - self::COLLECTION_CLASS, - $this->service->loadBalancerList() - ); + // Load JSON HTTP data + $authData = file_get_contents($this->getTestFilePath('Auth', './')); + $data1 = file_get_contents($this->getTestFilePath('LoadBalancers1')); + $data2 = file_get_contents($this->getTestFilePath('LoadBalancers2')); + $data3 = file_get_contents($this->getTestFilePath('LoadBalancers3')); + + // Populate mock response queue + $mock = new MockPlugin(); + $mock->addResponse(Response::fromMessage($authData)) + ->addResponse(Response::fromMessage($data1)) + ->addResponse(Response::fromMessage($data2)) + ->addResponse(Response::fromMessage($data3)); + + // We need to define our own setup because *jazz hands* + $client = $this->newClient(); + $client->addSubscriber($mock); + $service = $client->loadBalancerService(null, 'IAD'); + + // Ensure that a series of paginated calls return a holistic collection + $lbs = $service->loadBalancerList(false, array('limit' => 2)); + $ids = array(); + foreach ($lbs as $lb) { + $ids[] = $lb->id; + } + + // Check our assumptions + $this->isCollection($lbs); + $this->assertEquals($ids, array(1,2,3,4,5)); } public function testBillableLoadBalancer() diff --git a/tests/OpenCloud/Tests/OpenCloudTestCase.php b/tests/OpenCloud/Tests/OpenCloudTestCase.php index 628881fbb..8d7582c1f 100644 --- a/tests/OpenCloud/Tests/OpenCloudTestCase.php +++ b/tests/OpenCloud/Tests/OpenCloudTestCase.php @@ -38,17 +38,10 @@ abstract class OpenCloudTestCase extends \PHPUnit_Framework_TestCase public function newClient() { - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + return new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( 'username' => 'foo', 'apiKey' => 'bar' )); - - $client->addSubscriber(new MockSubscriber()); - //$client->addSubscriber(LogPlugin::getDebugPlugin()); - - $client->authenticate(); - - return $client; } public function getClient() @@ -59,6 +52,10 @@ public function getClient() public function setUp() { $this->client = $this->newClient(); + + $this->client->addSubscriber(new MockSubscriber()); + $this->client->authenticate(); + $this->setupObjects(); $this->handleMockSubscribers(); } From 5473f31a343e0e104c3b177db09fd9b6e4a70131 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 9 Jan 2015 11:25:08 +0100 Subject: [PATCH 077/181] Appease PSR-2 gods --- lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php | 2 +- tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php b/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php index f554c6512..d6326048e 100644 --- a/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php +++ b/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php @@ -40,4 +40,4 @@ public function parseResponseBody($body) return $response; } -} \ No newline at end of file +} diff --git a/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php b/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php index 2d01e2f93..9beb0c620 100644 --- a/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php +++ b/tests/OpenCloud/Tests/LoadBalancer/ServiceTest.php @@ -79,7 +79,7 @@ public function test_Listing_Load_Balancers() // Check our assumptions $this->isCollection($lbs); - $this->assertEquals($ids, array(1,2,3,4,5)); + $this->assertEquals($ids, array(1, 2, 3, 4, 5)); } public function testBillableLoadBalancer() From 7a5efc45c97f6e4c7036c912cb20ca5a71f97536 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 9 Jan 2015 11:32:29 +0100 Subject: [PATCH 078/181] Attempt to fix 5.3 segfault --- phpunit.xml.dist | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 3d4b02cd2..c2aeed2d4 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -26,8 +26,8 @@ - - + + From d2cce750dfe19b6400c975a399231327088ffcaf Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 13 Jan 2015 12:36:20 +0100 Subject: [PATCH 079/181] Tweaks based on code review --- .../LoadBalancer/Collection/LoadBalancerIterator.php | 8 ++------ lib/OpenCloud/LoadBalancer/Service.php | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php b/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php index d6326048e..7febf1af3 100644 --- a/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php +++ b/lib/OpenCloud/LoadBalancer/Collection/LoadBalancerIterator.php @@ -30,12 +30,8 @@ public function parseResponseBody($body) $response = parent::parseResponseBody($body); if (count($response) >= $this->getOption('limit.page')) { - // Save last element (we will need it for the next marker) - $this->nextElement = end($response); - - // Since we previously asked for n+1 elements, pop the unwanted element - array_pop($response); - reset($response); + // Pop last element and save (we will need it for the next marker) + $this->nextElement = array_pop($response); } return $response; diff --git a/lib/OpenCloud/LoadBalancer/Service.php b/lib/OpenCloud/LoadBalancer/Service.php index 6f5052f2c..7f8d01f74 100644 --- a/lib/OpenCloud/LoadBalancer/Service.php +++ b/lib/OpenCloud/LoadBalancer/Service.php @@ -63,7 +63,7 @@ public function loadBalancerList($detail = true, array $filter = array()) $url->addPath(Resource\LoadBalancer::resourceName()); $url->setQuery($filter); - $options += array('baseUrl' => $url, 'key.marker' => 'id'); + $options = array_merge($options, array('baseUrl' => $url, 'key.marker' => 'id')); return LoadBalancerIterator::factory($this, $options); } From 25bd5e7b3fa1f02392e886d8935f322484fc84b1 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Tue, 13 Jan 2015 17:28:57 -0800 Subject: [PATCH 080/181] Add comment to clarify intent of code. --- lib/OpenCloud/Common/Service/CatalogItem.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/OpenCloud/Common/Service/CatalogItem.php b/lib/OpenCloud/Common/Service/CatalogItem.php index b55274762..5d0e44d1a 100644 --- a/lib/OpenCloud/Common/Service/CatalogItem.php +++ b/lib/OpenCloud/Common/Service/CatalogItem.php @@ -141,6 +141,8 @@ public function getEndpoints() public function getEndpointFromRegion($region) { foreach ($this->endpoints as $endpoint) { + // Return the endpoint if it is regionless OR if the endpoint's + // region matches the $region supplied by the caller. if (!isset($endpoint->region) || $endpoint->region == $region) { return $endpoint; } From a379aed93318dabf45e500948f18f90e59c4bac4 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 14 Jan 2015 03:41:21 -0800 Subject: [PATCH 081/181] Clarifying where to place autoloader require statement. --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6b05d1d58..42948e8c3 100644 --- a/README.md +++ b/README.md @@ -32,12 +32,15 @@ php composer.phar require rackspace/php-opencloud ``` Once you have installed the library, you will need to load Composer's autoloader (which registers all the required -namespaces): +namespaces). To do this, place the following line of PHP code at the top of your application's PHP files: ```php require 'vendor/autoload.php'; ``` +**Note**: this assumes your application's PHP files are located in the same folder as `vendor/`. If your files are located +elsewhere, please supply the path to `vendor/autoload.php` in the `require` statement above. + And you're ready to go! You can also check out the [Getting Started guide](docs/getting-started.md) for a quick tutorial. From fd0b51ec7bbb57a7cac62b35d343b78d27561e12 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 15 Jan 2015 10:42:32 +0100 Subject: [PATCH 082/181] Fix CDN container population when iterating --- lib/OpenCloud/ObjectStore/AbstractService.php | 16 --------- lib/OpenCloud/ObjectStore/CDNService.php | 35 +++++++++++++++++++ lib/OpenCloud/ObjectStore/Service.php | 13 +++++++ 3 files changed, 48 insertions(+), 16 deletions(-) diff --git a/lib/OpenCloud/ObjectStore/AbstractService.php b/lib/OpenCloud/ObjectStore/AbstractService.php index 8e24c0b96..8f92874f8 100644 --- a/lib/OpenCloud/ObjectStore/AbstractService.php +++ b/lib/OpenCloud/ObjectStore/AbstractService.php @@ -29,22 +29,6 @@ abstract class AbstractService extends CatalogService const MAX_OBJECT_NAME_LEN = 1024; const MAX_OBJECT_SIZE = 5102410241025; - /** - * List all available containers. If called by a CDN service, it returns CDN-enabled; if called by a regular - * service, normal containers are returned. - * - * @param array $filter - * @return Collection - */ - public function listContainers(array $filter = array()) - { - $filter['format'] = 'json'; - - $class = ($this instanceof Service) ? 'Container' : 'CDNContainer'; - - return $this->resourceList($class, $this->getUrl(null, $filter), $this); - } - /** * @return Resource\Account */ diff --git a/lib/OpenCloud/ObjectStore/CDNService.php b/lib/OpenCloud/ObjectStore/CDNService.php index e6b20cd5c..7d38c9956 100644 --- a/lib/OpenCloud/ObjectStore/CDNService.php +++ b/lib/OpenCloud/ObjectStore/CDNService.php @@ -16,6 +16,8 @@ */ namespace OpenCloud\ObjectStore; +use OpenCloud\ObjectStore\Resource\CDNContainer; +use OpenCloud\ObjectStore\Resource\ContainerMetadata; /** * This is the CDN version of the ObjectStore service. @@ -24,4 +26,37 @@ class CDNService extends AbstractService { const DEFAULT_NAME = 'cloudFilesCDN'; const DEFAULT_TYPE = 'rax:object-cdn'; + + /** + * List all available containers. If called by a CDN service, it returns CDN-enabled; if called by a regular + * service, normal containers are returned. + * + * @param array $filter + * @return CDNContainer + */ + public function listContainers(array $filter = array()) + { + $filter['format'] = 'json'; + return $this->resourceList('CDNContainer', $this->getUrl(null, $filter), $this); + } + + public function cdnContainer($data) + { + $container = new CDNContainer($this, $data); + + $metadata = new ContainerMetadata(); + $metadata->setArray(array( + 'Streaming-Uri' => $data->cdn_streaming_uri, + 'Ios-Uri' => $data->cdn_ios_uri, + 'Ssl-Uri' => $data->cdn_ssl_uri, + 'Enabled' => $data->cdn_enabled, + 'Ttl' => $data->ttl, + 'Log-Retention' => $data->log_retention, + 'Uri' => $data->cdn_uri, + )); + + $container->setMetadata($metadata); + + return $container; + } } diff --git a/lib/OpenCloud/ObjectStore/Service.php b/lib/OpenCloud/ObjectStore/Service.php index 66735dea8..df9ffa6c8 100644 --- a/lib/OpenCloud/ObjectStore/Service.php +++ b/lib/OpenCloud/ObjectStore/Service.php @@ -66,6 +66,19 @@ public function getCdnService() return $this->cdnService; } + /** + * List all available containers. If called by a CDN service, it returns CDN-enabled; if called by a regular + * service, normal containers are returned. + * + * @param array $filter + * @return Container + */ + public function listContainers(array $filter = array()) + { + $filter['format'] = 'json'; + return $this->resourceList('Container', $this->getUrl(null, $filter), $this); + } + /** * @param $data * @return Container From 45302cfff1e297bbb50fcc36e92660fa3e6a9e61 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 15 Jan 2015 10:50:13 +0100 Subject: [PATCH 083/181] Minor fixes --- lib/OpenCloud/ObjectStore/CDNService.php | 6 +++--- lib/OpenCloud/ObjectStore/Service.php | 5 ++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/lib/OpenCloud/ObjectStore/CDNService.php b/lib/OpenCloud/ObjectStore/CDNService.php index 7d38c9956..d45fc494d 100644 --- a/lib/OpenCloud/ObjectStore/CDNService.php +++ b/lib/OpenCloud/ObjectStore/CDNService.php @@ -16,6 +16,7 @@ */ namespace OpenCloud\ObjectStore; + use OpenCloud\ObjectStore\Resource\CDNContainer; use OpenCloud\ObjectStore\Resource\ContainerMetadata; @@ -28,11 +29,10 @@ class CDNService extends AbstractService const DEFAULT_TYPE = 'rax:object-cdn'; /** - * List all available containers. If called by a CDN service, it returns CDN-enabled; if called by a regular - * service, normal containers are returned. + * List CDN-enabled containers. * * @param array $filter - * @return CDNContainer + * @return \OpenCloud\Common\Collection\PaginatedIterator */ public function listContainers(array $filter = array()) { diff --git a/lib/OpenCloud/ObjectStore/Service.php b/lib/OpenCloud/ObjectStore/Service.php index df9ffa6c8..f0e1c3dc9 100644 --- a/lib/OpenCloud/ObjectStore/Service.php +++ b/lib/OpenCloud/ObjectStore/Service.php @@ -67,11 +67,10 @@ public function getCdnService() } /** - * List all available containers. If called by a CDN service, it returns CDN-enabled; if called by a regular - * service, normal containers are returned. + * List all available containers. * * @param array $filter - * @return Container + * @return \OpenCloud\Common\Collection\PaginatedIterator */ public function listContainers(array $filter = array()) { From d69194883abd950d4daf4444ad774c41415f1013 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 15 Jan 2015 15:13:34 +0100 Subject: [PATCH 084/181] [ci skip] Adding better documentation --- docs/userguide/ObjectStore/CDN/Container.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/userguide/ObjectStore/CDN/Container.md b/docs/userguide/ObjectStore/CDN/Container.md index 3d06216fc..642ee968d 100644 --- a/docs/userguide/ObjectStore/CDN/Container.md +++ b/docs/userguide/ObjectStore/CDN/Container.md @@ -21,7 +21,16 @@ $cdn = $container->getCdn(); ## List CDN-enabled container To list CDN-only containers, follow the same operation for Storage which lists all containers. The only difference is -which service object you execute the method on. +which service object you execute the method on: + +```php +$cdnService = $service->getCdnService(); +$cdnContainers = $cdnService->listContainers(); + +foreach ($cdnContainers as $cdnContainer) { + +} +``` ## CDN-enable and -disable a container @@ -66,4 +75,4 @@ To enable and disable logging for your CDN: ```php $cdn->enableCdnLogging(); $cdn->disableCdnLogging(); -``` \ No newline at end of file +``` From 5cb0fd8db94ab91388cbe489e8515ddd6a6a6d0f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 21 Jan 2015 15:24:42 -0800 Subject: [PATCH 085/181] Generate and publish SDK API reference from Travis builds of master branch. --- .travis.yml | 3 +++ composer.json | 3 ++- docs/generate.sh | 50 +++++++++++++++++++++++++++++++----------------- 3 files changed, 37 insertions(+), 19 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7d45afa70..fe792bec4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,3 +30,6 @@ notifications: - jamie.hannaford@rackspace.com - glen.campbell@rackspace.com - shaunak.kashyap@rackspace.com + +env: + - secure: "bdrUeYb3nSGgBB+QtDZxUHVPw6B/wjb3KXLm8TgonWrQm4GPeWKK29qhmDnFZmQjwQPfuebe7wAk1ZxGoZKbEiELVpJJ+8XYVOt6W/6V53H31JL6FqiIE5+7qBwDe+9ziveM6GcTXHT1GI5mUeACIbeBDPZaNubIJH3U6MPim64=" \ No newline at end of file diff --git a/composer.json b/composer.json index 9c1752463..abaae2a78 100644 --- a/composer.json +++ b/composer.json @@ -36,6 +36,7 @@ "guzzle/guzzle": "~3.8", "satooshi/php-coveralls": "0.6.*@dev", "jakub-onderka/php-parallel-lint": "0.*", - "fabpot/php-cs-fixer": "1.0.*@dev" + "fabpot/php-cs-fixer": "1.0.*@dev", + "apigen/apigen": "~4.0" } } diff --git a/docs/generate.sh b/docs/generate.sh index 01a43a58e..3970fe309 100644 --- a/docs/generate.sh +++ b/docs/generate.sh @@ -1,25 +1,39 @@ -#!/bin/bash -# (c)2013 Rackspace Hosting. See COPYING for license. +#!/bin/sh -DOC_DIR=docs/api -LIB_DIR=lib -BIN_FILE=vendor/bin/apigen.php +# Script to be used by Travis CI builds to generate the php-opencloud SDK API +# reference and publish it to the gh-pages branch of the rackerlabs/php-opencloud +# repository. -if [ ! -f $BIN_FILE ]; then - rm composer.lock - php composer.phar require apigen/apigen:dev-master --dev -fi +SOURCE_DIR=lib +WORK_DIR=build/api +API_DOCS_DIR=docs/api +REPO_REMOTE_URL=https://$GH_TOKEN@github.com/rackspace/php-opencloud -if [ ! -d $DOC_DIR ]; then - mkdir $DOC_DIR +# We want our generated API reference to reflect what is +# on the master branch. So if we aren't currently on +# the master branch, or we aren't part of a PR targetted +# to the master branch, do nothing. +if [ "$TRAVIS_BRANCH" != "master" ]; then + exit 0 fi -if [ ! -d docs ]; then - echo "No docs/ directory found; run this script from the top directory" - exit; -fi +# Generate the API references +rm -rf $API_DOCS_DIR && \ +./vendor/bin/apigen generate \ + --source $SOURCE_DIR \ + --destination $WORK_DIR + +# Switch the branch to gh-pages +git checkout gh-pages + +# Commit the generated API references +rm -rf $API_DOCS_DIR +mv $WORK_DIR $API_DOCS_DIR +git add -f $API_DOCS_DIR +git commit -m "Re-generated API documentation" -rm -rf DOCS_DIR +# Push to the remote gh-pages branch so +# changes show up on php-opencloud.com +git push $REPO_REMOTE_URL gh-pages -# regenerate all the docs! -php $BIN_FILE -s $LIB_DIR -d $DOC_DIR --title="PHP OpenCloud API" --groups="namespaces" --download --progressbar \ No newline at end of file +git checkout master From 9f47ec524237a127c109ae9b101e10c5cc6b9d40 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 21 Jan 2015 15:46:19 -0800 Subject: [PATCH 086/181] Using an older version of apigen that works with PHP 5.3. --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index abaae2a78..5fdc047a5 100644 --- a/composer.json +++ b/composer.json @@ -37,6 +37,6 @@ "satooshi/php-coveralls": "0.6.*@dev", "jakub-onderka/php-parallel-lint": "0.*", "fabpot/php-cs-fixer": "1.0.*@dev", - "apigen/apigen": "~4.0" + "apigen/apigen": "~2.8" } } From ebcec94cfdfed31a6815de66e080621332a55afe Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 21 Jan 2015 15:59:52 -0800 Subject: [PATCH 087/181] Making generation+publish script executable. --- docs/generate.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 docs/generate.sh diff --git a/docs/generate.sh b/docs/generate.sh old mode 100644 new mode 100755 From 2464ef7e165e0fd5b9ae255be1c3659c9b2b3374 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 21 Jan 2015 16:11:02 -0800 Subject: [PATCH 088/181] Pull in latest changes before making more changes. --- docs/generate.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/generate.sh b/docs/generate.sh index 3970fe309..ed06cb3a6 100755 --- a/docs/generate.sh +++ b/docs/generate.sh @@ -25,6 +25,7 @@ rm -rf $API_DOCS_DIR && \ # Switch the branch to gh-pages git checkout gh-pages +git pull $REPO_REMOTE_URL gh-pages # Commit the generated API references rm -rf $API_DOCS_DIR From 772998e7cce64adc80bacac74393b1f1792890b6 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 21 Jan 2015 16:14:17 -0800 Subject: [PATCH 089/181] Adding error checking if the pull/merge failed. --- docs/generate.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/generate.sh b/docs/generate.sh index ed06cb3a6..a27c6e404 100755 --- a/docs/generate.sh +++ b/docs/generate.sh @@ -27,6 +27,10 @@ rm -rf $API_DOCS_DIR && \ git checkout gh-pages git pull $REPO_REMOTE_URL gh-pages +if [ $? -ne 0 ]; then + exit 1 +fi + # Commit the generated API references rm -rf $API_DOCS_DIR mv $WORK_DIR $API_DOCS_DIR From 886a95832d1c2c21730a7088a36dcd77dda6e363 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 21 Jan 2015 16:20:58 -0800 Subject: [PATCH 090/181] Attempt merge commit if necessary. --- docs/generate.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/generate.sh b/docs/generate.sh index a27c6e404..d7965bfb7 100755 --- a/docs/generate.sh +++ b/docs/generate.sh @@ -25,7 +25,7 @@ rm -rf $API_DOCS_DIR && \ # Switch the branch to gh-pages git checkout gh-pages -git pull $REPO_REMOTE_URL gh-pages +git pull --commit $REPO_REMOTE_URL gh-pages if [ $? -ne 0 ]; then exit 1 From 6f23936ff0d62cd570c5038953e116cc5b42b579 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 23 Jan 2015 03:48:41 -0800 Subject: [PATCH 091/181] Removing unnecessary line. --- docs/generate.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/generate.sh b/docs/generate.sh index d7965bfb7..2c88f3eca 100755 --- a/docs/generate.sh +++ b/docs/generate.sh @@ -18,7 +18,6 @@ if [ "$TRAVIS_BRANCH" != "master" ]; then fi # Generate the API references -rm -rf $API_DOCS_DIR && \ ./vendor/bin/apigen generate \ --source $SOURCE_DIR \ --destination $WORK_DIR From df95b789f9f9142e8d3691ba77d038326d7cd6a0 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 23 Jan 2015 04:17:32 -0800 Subject: [PATCH 092/181] Adding apigen config file. --- apigen.neon | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 apigen.neon diff --git a/apigen.neon b/apigen.neon new file mode 100644 index 000000000..1907d65f4 --- /dev/null +++ b/apigen.neon @@ -0,0 +1,3 @@ +templateTheme: bootstrap + +accessLevels: [public] From 545c667033f665646c8fe0cc235e5abc806c1fc5 Mon Sep 17 00:00:00 2001 From: Glen Campbell Date: Sat, 7 Feb 2015 11:25:26 -0600 Subject: [PATCH 093/181] Docs said 'COMPLETE' but code uses 'COMPLETED' --- docs/userguide/DNS/Domains.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/userguide/DNS/Domains.md b/docs/userguide/DNS/Domains.md index 827020256..f0d94efee 100644 --- a/docs/userguide/DNS/Domains.md +++ b/docs/userguide/DNS/Domains.md @@ -90,7 +90,7 @@ This call provides the BIND (Berkeley Internet Name Domain) 9 formatted contents ```php $asyncResponse = $domain->export(); -$body = $asyncResponse->waitFor('COMPLETE'); +$body = $asyncResponse->waitFor('COMPLETED'); echo $body['contents']; ``` From f5dfde5cb9c360e88cf564de362712e5c23d4247 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 25 Feb 2015 14:20:34 +0100 Subject: [PATCH 094/181] Adding explanation for prefixing user-agents --- docs/userguide/Clients.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/userguide/Clients.md b/docs/userguide/Clients.md index 70f1a8131..6f1e35075 100644 --- a/docs/userguide/Clients.md +++ b/docs/userguide/Clients.md @@ -116,6 +116,26 @@ To set default HTTP headers: $client->setDefaultOption('headers/X-Custom-Header', 'FooBar'); ``` +## User agents + +php-opencloud will send a default `User-Agent` header for every HTTP request, unless a custom value is provided by the end-user. The default header will be in this format: + +> OpenCloud/xxx cURL/yyy PHP/zzz + +where `xxx` is the current version of the SDK, `yyy` is the current version of cURL, and `zzz` is the current PHP version. To override this default, you must run: + +```php +$client->setUserAgent('MyCustomUserAgent'); +``` + +If you want to set a _prefix_ for the user agent, but retain the default `User-Agent` as a suffix, you must run: + +```php +$client->setUserAgent('MyPrefix', true); +``` + +where `$client` is an instance of `OpenCloud\OpenStack` or `OpenCloud\Rackspace`. + ## 5. Other functionality For a full list of functionality provided by Guzzle, please consult the [official documentation](http://docs.guzzlephp.org/en/latest/http-client/client.html). From 6e2e78626c782eb807b1409aeb30b4d187aac025 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 25 Feb 2015 15:03:22 +0100 Subject: [PATCH 095/181] Install entire Guzzle package --- composer.json | 1 - 1 file changed, 1 deletion(-) diff --git a/composer.json b/composer.json index 5fdc047a5..fe720466b 100644 --- a/composer.json +++ b/composer.json @@ -33,7 +33,6 @@ }, "require-dev" : { "phpunit/phpunit": "4.3.*", - "guzzle/guzzle": "~3.8", "satooshi/php-coveralls": "0.6.*@dev", "jakub-onderka/php-parallel-lint": "0.*", "fabpot/php-cs-fixer": "1.0.*@dev", From 37ce5b3c95e987253ce63ae99569fcafaaa554cb Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 25 Feb 2015 20:25:43 +0100 Subject: [PATCH 096/181] Add example outputs --- docs/userguide/Clients.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/userguide/Clients.md b/docs/userguide/Clients.md index 6f1e35075..c7270d69e 100644 --- a/docs/userguide/Clients.md +++ b/docs/userguide/Clients.md @@ -120,7 +120,7 @@ $client->setDefaultOption('headers/X-Custom-Header', 'FooBar'); php-opencloud will send a default `User-Agent` header for every HTTP request, unless a custom value is provided by the end-user. The default header will be in this format: -> OpenCloud/xxx cURL/yyy PHP/zzz +> User-Agent: OpenCloud/xxx cURL/yyy PHP/zzz where `xxx` is the current version of the SDK, `yyy` is the current version of cURL, and `zzz` is the current PHP version. To override this default, you must run: @@ -128,12 +128,20 @@ where `xxx` is the current version of the SDK, `yyy` is the current version of c $client->setUserAgent('MyCustomUserAgent'); ``` +which will result in: + +> User-Agent: MyCustomUserAgent + If you want to set a _prefix_ for the user agent, but retain the default `User-Agent` as a suffix, you must run: ```php $client->setUserAgent('MyPrefix', true); ``` +which will result in: + +> User-Agent: MyPrefix OpenCloud/xxx cURL/yyy PHP/zzz + where `$client` is an instance of `OpenCloud\OpenStack` or `OpenCloud\Rackspace`. ## 5. Other functionality From e2433c00a57c0a700b6715a7538c628868f9b4e1 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 25 Feb 2015 15:17:22 -0800 Subject: [PATCH 097/181] Return array of DataObjects if such is requested. --- .../ObjectStore/Resource/Container.php | 23 +++++++++++++++---- .../ObjectStore/Resource/ContainerTest.php | 14 +++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/lib/OpenCloud/ObjectStore/Resource/Container.php b/lib/OpenCloud/ObjectStore/Resource/Container.php index 18e541bc7..ef8f27e68 100644 --- a/lib/OpenCloud/ObjectStore/Resource/Container.php +++ b/lib/OpenCloud/ObjectStore/Resource/Container.php @@ -30,6 +30,7 @@ use OpenCloud\ObjectStore\Exception\ObjectNotFoundException; use OpenCloud\ObjectStore\Upload\DirectorySync; use OpenCloud\ObjectStore\Upload\TransferBuilder; +use OpenCloud\ObjectStore\Enum\ReturnType; /** * A container is a storage compartment for your data and provides a way for you @@ -475,7 +476,7 @@ public function uploadObject($name, $data, array $headers = array()) * @throws \OpenCloud\Common\Exceptions\InvalidArgumentError * @return \Guzzle\Http\Message\Response */ - public function uploadObjects(array $files, array $commonHeaders = array()) + public function uploadObjects(array $files, array $commonHeaders = array(), $returnType = ReturnType::RESPONSE_ARRAY) { $requests = $entities = array(); @@ -514,11 +515,23 @@ public function uploadObjects(array $files, array $commonHeaders = array()) $responses = $this->getClient()->send($requests); - foreach ($entities as $entity) { - $entity->close(); + if (ReturnType::RESPONSE_ARRAY === $returnType) { + foreach ($entities as $entity) { + $entity->close(); + } + return $responses; + } else { + // Convert responses to DataObjects before returning + $dataObjects = array(); + foreach ($responses as $index => $response) { + $dataObject = $this->dataObject() + ->populateFromResponse($response) + ->setName($files[$index]['name']) + ->setContent($entities[$index]); + $dataObjects[] = $dataObject; + } + return $dataObjects; } - - return $responses; } /** diff --git a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php index 2ada2c41c..5e3171e6e 100644 --- a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php +++ b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php @@ -20,6 +20,7 @@ use Guzzle\Http\Message\Response; use OpenCloud\Common\Constants\Size; use OpenCloud\Tests\ObjectStore\ObjectStoreTestCase; +use OpenCloud\ObjectStore\Enum\ReturnType; class ContainerTest extends ObjectStoreTestCase { @@ -225,6 +226,19 @@ public function test_Upload_Multiple() )); } + public function test_Upload_Multiple_Return_DataObject_Array() + { + $container = $this->container; + + $dataObjects = $container->uploadObjects(array( + array('name' => 'test', 'body' => 'FOOBAR') + ), array(), ReturnType::DATA_OBJECT_ARRAY); + $this->assertInstanceOf('OpenCloud\ObjectStore\Resource\DataObject', $dataObjects[0]); + $this->assertEquals('test', $dataObjects[0]->getName()); + $this->assertInstanceOf('Guzzle\Http\EntityBody', $dataObjects[0]->getContent()); + $this->assertEquals('FOOBAR', (string) $dataObjects[0]->getContent()); + } + public function test_Upload() { $this->assertInstanceOf( From da68b2dc4e03022f1336f7e2b3d2cbff1a0b83d3 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 25 Feb 2015 16:35:05 -0800 Subject: [PATCH 098/181] Adding documentation. --- docs/userguide/ObjectStore/USERGUIDE.md | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/docs/userguide/ObjectStore/USERGUIDE.md b/docs/userguide/ObjectStore/USERGUIDE.md index 8bb3f3d45..fa04bdeaf 100644 --- a/docs/userguide/ObjectStore/USERGUIDE.md +++ b/docs/userguide/ObjectStore/USERGUIDE.md @@ -198,7 +198,8 @@ $localFileName = '/path/to/local/php-elephant.jpg'; $remoteFileName = 'php-elephant.jpg'; $fileData = fopen($localFileName, 'r'); -$container->uploadObject($remoteFileName, $fileData); +$object = $container->uploadObject($remoteFileName, $fileData); +/** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ ``` [ [Get the executable PHP script for this example](/samples/ObjectStore/upload-object.php) ] @@ -258,7 +259,10 @@ $objects = array( a ); -$container->uploadObjects($objects); +$responses = $container->uploadObjects($objects); +foreach ($responses as $response) { + /** @var $response \Guzzle\Http\Message\Response **/ +} ``` [ [Get the executable PHP script for this example](/samples/ObjectStore/upload-multiple-objects.php) ] @@ -266,7 +270,7 @@ In the above example, the contents of two files present on the local filesystem Instead of specifying the `path` key in an element of the `$objects` array, you can specify a `body` key whose value is a string or a stream representation. -Finally, you can pass headers as the second parameter to the `uploadObjects` method. These headers will be applied to every object that is uploaded. +You can pass headers as the second parameter to the `uploadObjects` method. These headers will be applied to every object that is uploaded. ``` $metadata = array('author' => 'Jane Doe'); @@ -281,6 +285,17 @@ $container->uploadObjects($objects, $allHeaders); In the example above, every object referenced within the `$objects` array will be uploaded with the same metadata. +Finally, if you want the `uploadObjects` method to return an array of `OpenCloud\ObjectStore\Resource\DataObject` objects instead of an array of `Guzzle\Http\Message\Response` objects, you can specify a third parameter to the `uploadObjects` method: + +``` +use OpenCloud\ObjectStore\Enum\ReturnType; + +$dataObjects = $container->uploadObjects($objects, $allHeaders, ReturnType::DATA_OBJECT_ARRAY); +foreach ($dataObjects as $dataObject) { + /** @var $dataObject OpenCloud\ObjectStore\Resource\DataObject **/ +} +``` + ### Large Objects If you want to upload objects larger than 5GB in size, you must use a different upload process. From 5bb0ae44ea676b37a9477c74fb6117f7f89c59db Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 26 Feb 2015 05:57:35 -0800 Subject: [PATCH 099/181] Adding more test data. --- .../ObjectStore/Resource/ContainerTest.php | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php index 5e3171e6e..e5e002eda 100644 --- a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php +++ b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php @@ -228,15 +228,38 @@ public function test_Upload_Multiple() public function test_Upload_Multiple_Return_DataObject_Array() { - $container = $this->container; + $tempFileName = tempnam(sys_get_temp_dir(), "php-opencloud-test-"); + echo $tempFileName; + try { + $tempFile = fopen($tempFileName, 'w+'); + fwrite($tempFile, 'BAZQUX'); + + $container = $this->container; + + $dataObjects = $container->uploadObjects(array( + array('name' => 'test1', 'body' => 'FOOBAR'), + array('name' => 'test2', 'path' => $tempFileName), + array('name' => 'test2', 'body' => 'BARBAR') + ), array(), ReturnType::DATA_OBJECT_ARRAY); + } finally { + fclose($tempFile); + unlink($tempFileName); + } - $dataObjects = $container->uploadObjects(array( - array('name' => 'test', 'body' => 'FOOBAR') - ), array(), ReturnType::DATA_OBJECT_ARRAY); $this->assertInstanceOf('OpenCloud\ObjectStore\Resource\DataObject', $dataObjects[0]); - $this->assertEquals('test', $dataObjects[0]->getName()); + $this->assertEquals('test1', $dataObjects[0]->getName()); $this->assertInstanceOf('Guzzle\Http\EntityBody', $dataObjects[0]->getContent()); $this->assertEquals('FOOBAR', (string) $dataObjects[0]->getContent()); + + $this->assertInstanceOf('OpenCloud\ObjectStore\Resource\DataObject', $dataObjects[1]); + $this->assertEquals('test2', $dataObjects[1]->getName()); + $this->assertInstanceOf('Guzzle\Http\EntityBody', $dataObjects[1]->getContent()); + $this->assertEquals('BAZQUX', (string) $dataObjects[1]->getContent()); + + $this->assertInstanceOf('OpenCloud\ObjectStore\Resource\DataObject', $dataObjects[2]); + $this->assertEquals('test2', $dataObjects[2]->getName()); + $this->assertInstanceOf('Guzzle\Http\EntityBody', $dataObjects[2]->getContent()); + $this->assertEquals('BARBAR', (string) $dataObjects[2]->getContent()); } public function test_Upload() From 928a810df3ca7ebaa90f69566c35f5651d4509d0 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 26 Feb 2015 06:14:30 -0800 Subject: [PATCH 100/181] Adding inline documentation. --- lib/OpenCloud/ObjectStore/Resource/Container.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/ObjectStore/Resource/Container.php b/lib/OpenCloud/ObjectStore/Resource/Container.php index ef8f27e68..edcea7397 100644 --- a/lib/OpenCloud/ObjectStore/Resource/Container.php +++ b/lib/OpenCloud/ObjectStore/Resource/Container.php @@ -472,9 +472,12 @@ public function uploadObject($name, $data, array $headers = array()) * `path' Path to an existing file, OR * `body' Either a string or stream representation of the file contents to be uploaded. * @param array $headers Optional headers that will be sent with the request (useful for object metadata). + * @param string $returnType One of OpenCloud\ObjectStore\Enum\ReturnType::RESPONSE_ARRAY (to return an array of + * Guzzle\Http\Message\Response objects) or OpenCloud\ObjectStore\Enum\ReturnType::DATA_OBJECT_ARRAY + * (to return an array of OpenCloud\ObjectStore\Resource\DataObject objects). * * @throws \OpenCloud\Common\Exceptions\InvalidArgumentError - * @return \Guzzle\Http\Message\Response + * @return Guzzle\Http\Message\Response[] or OpenCloud\ObjectStore\Resource\DataObject[] depending on $returnType */ public function uploadObjects(array $files, array $commonHeaders = array(), $returnType = ReturnType::RESPONSE_ARRAY) { From 5e42a91ca9b2dea3d9062d1098778a0e85b6f2aa Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 26 Feb 2015 06:14:52 -0800 Subject: [PATCH 101/181] Oops. Forgot to check-in this file! --- lib/OpenCloud/ObjectStore/Enum/ReturnType.php | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 lib/OpenCloud/ObjectStore/Enum/ReturnType.php diff --git a/lib/OpenCloud/ObjectStore/Enum/ReturnType.php b/lib/OpenCloud/ObjectStore/Enum/ReturnType.php new file mode 100644 index 000000000..ac9193ed4 --- /dev/null +++ b/lib/OpenCloud/ObjectStore/Enum/ReturnType.php @@ -0,0 +1,29 @@ + Date: Thu, 26 Feb 2015 06:15:57 -0800 Subject: [PATCH 102/181] Condensing to one line. --- lib/OpenCloud/ObjectStore/Resource/Container.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/OpenCloud/ObjectStore/Resource/Container.php b/lib/OpenCloud/ObjectStore/Resource/Container.php index edcea7397..0f7b0df08 100644 --- a/lib/OpenCloud/ObjectStore/Resource/Container.php +++ b/lib/OpenCloud/ObjectStore/Resource/Container.php @@ -527,11 +527,10 @@ public function uploadObjects(array $files, array $commonHeaders = array(), $ret // Convert responses to DataObjects before returning $dataObjects = array(); foreach ($responses as $index => $response) { - $dataObject = $this->dataObject() - ->populateFromResponse($response) - ->setName($files[$index]['name']) - ->setContent($entities[$index]); - $dataObjects[] = $dataObject; + $dataObjects[] = $this->dataObject() + ->populateFromResponse($response) + ->setName($files[$index]['name']) + ->setContent($entities[$index]); } return $dataObjects; } From 39309d302ca6bc9cb9de6024c13857f5d8706fdf Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 26 Feb 2015 06:16:09 -0800 Subject: [PATCH 103/181] Remove debugging statement. --- tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php index e5e002eda..12daa574f 100644 --- a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php +++ b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php @@ -229,7 +229,6 @@ public function test_Upload_Multiple() public function test_Upload_Multiple_Return_DataObject_Array() { $tempFileName = tempnam(sys_get_temp_dir(), "php-opencloud-test-"); - echo $tempFileName; try { $tempFile = fopen($tempFileName, 'w+'); fwrite($tempFile, 'BAZQUX'); From 8142bf208f1c537216566506a321d22d503d44bf Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 27 Feb 2015 06:22:06 -0800 Subject: [PATCH 104/181] Adding catch block so this works with PHP 5.4. --- tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php index 12daa574f..11786c4dc 100644 --- a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php +++ b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php @@ -240,6 +240,8 @@ public function test_Upload_Multiple_Return_DataObject_Array() array('name' => 'test2', 'path' => $tempFileName), array('name' => 'test2', 'body' => 'BARBAR') ), array(), ReturnType::DATA_OBJECT_ARRAY); + } catch (Exception $e) { + throw $e; } finally { fclose($tempFile); unlink($tempFileName); From 63118f19311913ea8811cb021b3671e4e5311172 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 27 Feb 2015 07:33:35 -0800 Subject: [PATCH 105/181] Adding directive to let Travis builds finish fast. --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index fe792bec4..bdd5f76af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,6 +11,7 @@ sudo: false matrix: allow_failures: - php: hhvm + fast_finish: true branches: only: From 9b98d2cd9ab92e7ed694425b43df673306a98831 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 27 Feb 2015 07:38:48 -0800 Subject: [PATCH 106/181] Duh! PHP5.4 and below don't support finally at all. Removing altogether :( --- .../ObjectStore/Resource/ContainerTest.php | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php index 11786c4dc..b5d2bc602 100644 --- a/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php +++ b/tests/OpenCloud/Tests/ObjectStore/Resource/ContainerTest.php @@ -229,23 +229,19 @@ public function test_Upload_Multiple() public function test_Upload_Multiple_Return_DataObject_Array() { $tempFileName = tempnam(sys_get_temp_dir(), "php-opencloud-test-"); - try { - $tempFile = fopen($tempFileName, 'w+'); - fwrite($tempFile, 'BAZQUX'); - - $container = $this->container; - - $dataObjects = $container->uploadObjects(array( - array('name' => 'test1', 'body' => 'FOOBAR'), - array('name' => 'test2', 'path' => $tempFileName), - array('name' => 'test2', 'body' => 'BARBAR') - ), array(), ReturnType::DATA_OBJECT_ARRAY); - } catch (Exception $e) { - throw $e; - } finally { - fclose($tempFile); - unlink($tempFileName); - } + + $tempFile = fopen($tempFileName, 'w+'); + fwrite($tempFile, 'BAZQUX'); + + $container = $this->container; + + $dataObjects = $container->uploadObjects(array( + array('name' => 'test1', 'body' => 'FOOBAR'), + array('name' => 'test2', 'path' => $tempFileName), + array('name' => 'test2', 'body' => 'BARBAR') + ), array(), ReturnType::DATA_OBJECT_ARRAY); + fclose($tempFile); + unlink($tempFileName); $this->assertInstanceOf('OpenCloud\ObjectStore\Resource\DataObject', $dataObjects[0]); $this->assertEquals('test1', $dataObjects[0]->getName()); From ac1233ee67c61a033e46e5e96e012b9656c87d97 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:02:14 +0100 Subject: [PATCH 107/181] Add gitignore to prevent builds from being pushed --- doc/.gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 doc/.gitignore diff --git a/doc/.gitignore b/doc/.gitignore new file mode 100644 index 000000000..69fa449dd --- /dev/null +++ b/doc/.gitignore @@ -0,0 +1 @@ +_build/ From 310d9c880f22ded01cd56e56da7da10792125518 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:02:47 +0100 Subject: [PATCH 108/181] Add basic config and make scripts --- doc/Makefile | 177 +++++++++++++++++++++++++++++++++++++ doc/conf.py | 63 ++++++++++++++ doc/make.bat | 242 +++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 482 insertions(+) create mode 100644 doc/Makefile create mode 100644 doc/conf.py create mode 100644 doc/make.bat diff --git a/doc/Makefile b/doc/Makefile new file mode 100644 index 000000000..b7805cd67 --- /dev/null +++ b/doc/Makefile @@ -0,0 +1,177 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# User-friendly check for sphinx-build +ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) +$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) +endif + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/php-opencloud.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/php-opencloud.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/php-opencloud" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/php-opencloud" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." diff --git a/doc/conf.py b/doc/conf.py new file mode 100644 index 000000000..7f9e29414 --- /dev/null +++ b/doc/conf.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# +# php-opencloud documentation build configuration file, created by +# sphinx-quickstart on Tue Mar 3 12:28:19 2015. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os +from sphinx.highlighting import lexers +from pygments.lexers.web import PhpLexer + +on_rtd = os.environ.get('READTHEDOCS', None) == 'True' + +lexers['php'] = PhpLexer(startinline=True, linenos=1) +lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1) +primary_domain = 'php' + +extensions = [] +templates_path = ['_templates'] +source_suffix = '.rst' +master_doc = 'index' +project = u'php-opencloud' +copyright = u'2015, Jamie Hannaford, Shaunak Kashyap' +version = '1.12' +release = '1.12.1' +exclude_patterns = ['_build'] +pygments_style = 'sphinx' +html_theme = 'default' + +if not on_rtd: + import sphinx_rtd_theme + html_theme = 'sphinx_rtd_theme' + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "_templates"] + +html_static_path = ['_static'] +html_use_index = True + +# Output file base name for HTML help builder. +htmlhelp_basename = 'php-openclouddoc' + +latex_documents = [ + ('index', 'php-opencloud.tex', u'php-opencloud Documentation', + u'Jamie Hannaford, Shaunak Kashyap', 'manual'), +] + +man_pages = [ + ('index', 'php-opencloud', u'php-opencloud Documentation', + [u'Jamie Hannaford, Shaunak Kashyap'], 1) +] + +texinfo_documents = [ + ('index', 'php-opencloud', u'php-opencloud Documentation', + u'Jamie Hannaford, Shaunak Kashyap', 'php-opencloud', 'One line description of project.', + 'Miscellaneous'), +] diff --git a/doc/make.bat b/doc/make.bat new file mode 100644 index 000000000..219d9213f --- /dev/null +++ b/doc/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\php-opencloud.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\php-opencloud.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end From 745b717d71ed09814f27cd9a0196ced0fc561648 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:03:16 +0100 Subject: [PATCH 109/181] Add initial AutoScale --- doc/services/autoscale/group-config.rst | 63 ++++++++++++++++ doc/services/autoscale/groups.rst | 90 +++++++++++++++++++++++ doc/services/autoscale/index.rst | 51 +++++++++++++ doc/services/autoscale/policies.rst | 83 +++++++++++++++++++++ doc/services/autoscale/service.sample.rst | 7 ++ doc/services/autoscale/webhooks.rst | 64 ++++++++++++++++ 6 files changed, 358 insertions(+) create mode 100644 doc/services/autoscale/group-config.rst create mode 100644 doc/services/autoscale/groups.rst create mode 100644 doc/services/autoscale/index.rst create mode 100644 doc/services/autoscale/policies.rst create mode 100644 doc/services/autoscale/service.sample.rst create mode 100644 doc/services/autoscale/webhooks.rst diff --git a/doc/services/autoscale/group-config.rst b/doc/services/autoscale/group-config.rst new file mode 100644 index 000000000..a0d7c98f7 --- /dev/null +++ b/doc/services/autoscale/group-config.rst @@ -0,0 +1,63 @@ +Group configurations +==================== + +.. contents:: + +Setup +----- + +.. include:: service.sample.rst + +Finally, in order to interact with the functionality of a group's configuration, +you must first retrieve the details of the group itself. To do this, you must +substitute `{groupId}` for your group's ID: + +.. code-block:: php + + $group = $service->group('{groupId}'); + + +Get group configuration +----------------------- + +.. code-block:: php + + /** @var */ + $groupConfig = $group->getGroupConfig(); + + +Edit group configuration +------------------------ + +.. code-block:: php + + $groupConfig->update(array( + 'name' => 'New name!' + )); + + +Get launch configuration +------------------------ + +.. code-block:: php + + /** @var */ + $launchConfig = $group->getLaunchConfig(); + + +Edit group/launch configuration +------------------------------- + +.. code-block:: php + + $launchConfig = $group->getLaunchConfig(); + + $server = $launchConfig->args->server; + $server->name = "BRAND NEW SERVER NAME"; + + $launchConfig->update(array + 'args' => array( + 'server' => $server, + 'loadBalancers' => $launchConfig->args->loadBalancers + ) + )); diff --git a/doc/services/autoscale/groups.rst b/doc/services/autoscale/groups.rst new file mode 100644 index 000000000..8e781a2aa --- /dev/null +++ b/doc/services/autoscale/groups.rst @@ -0,0 +1,90 @@ +Groups +====== + +.. contents:: + + +Setup +----- + +.. include:: service.sample.rst + + +List all groups +--------------- + +.. code-block:: php + + $groups = $service->groupList(); + foreach ($group as $group) { + /** @var $group OpenCloud\Autoscale\Resources\Group */ + } + +Please consult the `iterator guide `__ for more information about +iterators. + + +Retrieve group by ID +-------------------- + +.. code-block:: php + + $group = $service->group('{groupId}'); + + +Create a new group +------------------ + +.. code-block:: php + + // Set the config object for this autoscale group; contains all of properties + // which determine its behaviour + $groupConfig = array( + 'name' => 'new_autoscale_group', + 'minEntities' => 5, + 'maxEntities' => 25, + 'cooldown' => 60, + ); + + // We need specify what is going to be launched. For now, we'll launch a new server + $launchConfig = array( + 'type' => 'launch_server', + 'args' => array( + 'server' => array( + 'flavorRef' => 3, + 'name' => 'webhead', + 'imageRef' => '0d589460-f177-4b0f-81c1-8ab8903ac7d8' + ), + 'loadBalancers' => array( + array('loadBalancerId' => 2200, 'port' => 8081), + ) + ) + ); + + // Do we want particular scaling policies? + $policy = array( + 'name' => 'scale up by 10', + 'change' => 10, + 'cooldown' => 5, + 'type' => 'webhook', + ); + + $group->create(array( + 'groupConfiguration' => $groupConfig, + 'launchConfiguration' => $launchConfig, + 'scalingPolicies' => array($policy), + )); + +Delete a group +-------------- + +.. code-block:: php + + $group->delete(); + +Get the current state of the scaling group +------------------------------------------ + +.. code-block:: php + + $group->getState(); diff --git a/doc/services/autoscale/index.rst b/doc/services/autoscale/index.rst new file mode 100644 index 000000000..3077a0a2c --- /dev/null +++ b/doc/services/autoscale/index.rst @@ -0,0 +1,51 @@ +Auto Scale v2 +============= + +.. toctree:: + + groups + group-config + policies + webhooks + +Glossary +-------- + +.. glossary:: + + group + The scaling group is at the heart of an Auto Scale deployment. The scaling + group specifies the basic elements of the Auto Scale configuration. It + manages how many servers can participate in the scaling group. It also + specifies information related to load balancers if your configuration uses + a load balancer. + + group configuration + Outlines the basic elements of the Auto Scale configuration. The group + configuration manages how many servers can participate in the scaling group. + It sets a minimum and maximum limit for the number of entities that can be + used in the scaling process. It also specifies information related to load + balancers. + + launch configuration + Creates a blueprint for how new servers will be created. The launch + configuration specifies what type of server image will be started on + launch, what flavor the new server is, and which load balancer the new + server connects to. + + policy + Auto Scale uses policies to define the scaling activity that will take + place, as well as when and how that scaling activity will take place. + Scaling policies specify how to modify the scaling group and its behavior. + You can specify multiple policies to manage a scaling group. + + webhook + A webhook is a reachable endpoint that when visited will execute a scaling + policy for a particular scaling group. + +Further Links +------------- + + - `Getting Started Guide for the API `_ + - `API Developer Guide `_ + - `API release history `_ diff --git a/doc/services/autoscale/policies.rst b/doc/services/autoscale/policies.rst new file mode 100644 index 000000000..f5d2605f4 --- /dev/null +++ b/doc/services/autoscale/policies.rst @@ -0,0 +1,83 @@ +Scaling Policies +================ + +Setup +----- + +.. include:: service.sample.rst + +Finally, in order to interact with the functionality of a group's scaling +policies, you must first retrieve the details of the group itself. To do this, +you must substitute `{groupId}` for your group's ID: + +.. code-block:: php + + $group = $service->group('{groupId}'); + + +Get all policies +---------------- + +.. code-block:: php + + $policies = $group->getScalingPolicies(); + + foreach ($policies as $policy) { + printf("Name: %s Type: %s\n", $policy->name, $policy->type); + } + + +Create new scaling policies +--------------------------- + +Creating policies is achieved through passing an array to the ``create`` +method. + +.. code-block:: php + + $policies = array( + array( + 'name' => 'NEW NAME', + 'change' => 1, + 'cooldown' => 150, + 'type' => 'webhook', + ) + ); + + $group->createScalingPolicies($policies); + + +Get an existing scaling policy +------------------------------ + +.. code-block:: php + + $policy = $group->getScalingPolicy('{policyId}'); + + +Update a scaling policy +----------------------- + +.. code-block:: php + + $policy = $group->getScalingPolicy('{policyId}'); + $policy->update(array( + 'name' => 'More relevant name' + )); + + +Delete a scaling policy +----------------------- + +.. code-block:: php + + $policy = $group->getScalingPolicy('{policyId}'); + $policy->delete(); + +Execute a scaling policy +------------------------ + +.. code-block:: php + + $policy = $group->getScalingPolicy('{policyId}'); + $policy->execute(); diff --git a/doc/services/autoscale/service.sample.rst b/doc/services/autoscale/service.sample.rst new file mode 100644 index 000000000..7e5d166ab --- /dev/null +++ b/doc/services/autoscale/service.sample.rst @@ -0,0 +1,7 @@ +.. include:: ../common/rs-client.sample.rst + +Now, set up the Auto Scale service: + +.. code-block:: php + + $service = $client->autoscaleService(); diff --git a/doc/services/autoscale/webhooks.rst b/doc/services/autoscale/webhooks.rst new file mode 100644 index 000000000..68b16b0dc --- /dev/null +++ b/doc/services/autoscale/webhooks.rst @@ -0,0 +1,64 @@ +Webhooks +======== + +Setup +----- + +.. include:: service.sample.rst + +Finally, in order to interact with webhooks, you must first retrieve the +details of the group and scaling policy you want to execute: + +.. code-block:: php + + $group = $service->group('{groupId}'); + $policy = $group->getScalingPolicy('{policyId}'); + +Get all webhooks +---------------- + +.. code-block:: php + + $webhooks = $policy->getWebookList(); + +Create a new webhook +-------------------- + +.. code-block:: php + + $policy->createWebhooks(array( + array( + 'name' => 'Alice', + 'metadata' => array( + 'firstKey' => 'foo', + 'secondKey' => 'bar' + ) + ) + )); + +Get webhook +----------- + +.. code-block:: php + + $webhook = $policy->getWebhook('{webhookId}'); + +Update webhook +-------------- + +.. code-block:: php + + // Update the metadata + $metadata = $webhook->metadata; + $metadata->thirdKey = 'blah'; + $webhook->update(array( + 'metadata' => $metadata + )); + + +Delete webhook +-------------- + +.. code-block: php + + $webhook->delete(); From bed631529266a3ca6175b67218e6d75bfc4dfafc Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:03:38 +0100 Subject: [PATCH 110/181] Add initial Common and Compute --- doc/services/common/os-client.sample.rst | 13 ++ doc/services/common/rs-client.sample.rst | 15 ++ doc/services/compute/flavors.rst | 66 ++++++++ doc/services/compute/images.rst | 87 ++++++++++ doc/services/compute/index.rst | 36 ++++ doc/services/compute/keypairs.rst | 71 ++++++++ doc/services/compute/servers.rst | 202 +++++++++++++++++++++++ doc/services/compute/service.sample.rst | 24 +++ 8 files changed, 514 insertions(+) create mode 100644 doc/services/common/os-client.sample.rst create mode 100644 doc/services/common/rs-client.sample.rst create mode 100644 doc/services/compute/flavors.rst create mode 100644 doc/services/compute/images.rst create mode 100644 doc/services/compute/index.rst create mode 100644 doc/services/compute/keypairs.rst create mode 100644 doc/services/compute/servers.rst create mode 100644 doc/services/compute/service.sample.rst diff --git a/doc/services/common/os-client.sample.rst b/doc/services/common/os-client.sample.rst new file mode 100644 index 000000000..b4614474d --- /dev/null +++ b/doc/services/common/os-client.sample.rst @@ -0,0 +1,13 @@ +.. code-block:: php + + '{username}', + 'password' => '{apiKey}', + 'tenantId' => '{tenantId}', + )); diff --git a/doc/services/common/rs-client.sample.rst b/doc/services/common/rs-client.sample.rst new file mode 100644 index 000000000..e33983270 --- /dev/null +++ b/doc/services/common/rs-client.sample.rst @@ -0,0 +1,15 @@ +The first thing to do is pass in your credentials and instantiate a Rackspace +client: + +.. code-block:: php + + '{username}', + 'apiKey' => '{apiKey}', + )); diff --git a/doc/services/compute/flavors.rst b/doc/services/compute/flavors.rst new file mode 100644 index 000000000..f79caa171 --- /dev/null +++ b/doc/services/compute/flavors.rst @@ -0,0 +1,66 @@ +Flavors +======= + +Setup +----- + +.. include:: service.sample.rst + + +Get a flavor +------------ + +.. code-block:: php + + $flavor = $service->flavor('{flavorId}'); + + +List flavors +------------ + +.. code-block:: php + + $flavors = $service->flavorList(); + + foreach ($flavors as $flavor) { + /** @param $flavor OpenCloud\Common\Resource\FlavorInterface */ + } + + +Detailed results +~~~~~~~~~~~~~~~~ + +By default, the ``flavorList`` method returns full details on all flavors. +However, because of the overhead involved in retrieving all the details, this +function can be slower than might be expected. To disable this feature and +keep bandwidth at a minimum, just pass ``false`` as the first argument: + +.. code-block:: php + + // Name and ID only + $compute->flavorList(false); + + +Filtering +~~~~~~~~~ + +You can also refine the list of images returned by providing specific filters: + ++-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Array key | Description | ++=================+================================================================================================================================================================================================+ +| minDisk | Filters the list of flavors to those with the specified minimum number of gigabytes of disk storage. | ++-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| minRam | Filters the list of flavors to those with the specified minimum amount of RAM in megabytes. | ++-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| marker | The ID of the last item in the previous list. See the `official docs `__ for more information. | ++-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| limit | Sets the page size. See the `official docs `__ for more information. | ++-----------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +These are defined in an array and passed in as the second argument. For example, +to return all flavors over 4GB in RAM: + +.. code-block:: php + + $flavors = $service->flavorList(true, array('minRam' => 4)); diff --git a/doc/services/compute/images.rst b/doc/services/compute/images.rst new file mode 100644 index 000000000..b2aae4a65 --- /dev/null +++ b/doc/services/compute/images.rst @@ -0,0 +1,87 @@ +Images +====== + +.. note:: + + **Images on Rackspace servers:** with standard servers, the entire disk + (OS and data) is captured in the image. With Performance servers, only the s + ystem disk is captured in the image. The data disks should be backed up using + Cloud Backup or Cloud Block Storage to ensure availability in case you need + to rebuild or restore a server. + +Setup +----- + +.. include:: service.sample.rst + + +List images +----------- + +Below is the simplest usage for retrieving a list of images: + +.. code-block:: php + + $images = $service->imageList(); + + foreach ($images as $image) { + + } + +Detailed results +~~~~~~~~~~~~~~~~ + +By default, the only fields returned in a list call are `id` and `name`, but +you can enable more detailed information to be result by passing in `true` as +the first argument of the call, like so: + +.. code-block:: php + + $images = $service->imageList(true); + + +Filtering +~~~~~~~~~ + +You can also refine the list of images returned by providing specific filters: + ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Array key | Description | ++=================+====================================================================================================================================================================================================================================================================================================================================================+ +| server | Filters the list of images by server. Specify the server reference by ID or by full URL. | ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| name | Filters the list of images by image name. | ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| status | Filters the list of images by status. In-flight images have a status of ``SAVING`` and the conditional progress element contains a value from 0 to 100, which indicates the percentage completion. For a full list, please consult the ``OpenCloud\Compute\Constants\ImageState`` class. Images with an ``ACTIVE`` status are available for use. | ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| changes-since | Filters the list of images to those that have changed since the changes-since time. See the `official docs `__ for more information. | ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| marker | The ID of the last item in the previous list. See the `official docs `__ for more information. | ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| limit | Sets the page size. See the `official docs `__ for more information. | ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| type | Filters base Rackspace images or any custom server images that you have created. Can either be ``BASE`` or ``SNAPSHOT``. | ++-----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +These are defined in an array and passed in as the second argument. For example, +to filter images for a particular server: + +.. code-block:: php + + $images = $service->imageList(false, array('server' => '{serverId}')); + + +Retrieve details about an image +------------------------------- + +.. code-block:: php + + $image = $service->image('{imageId}'); + + +Delete an image +--------------- + +.. code-block:: php + + $image->delete(); diff --git a/doc/services/compute/index.rst b/doc/services/compute/index.rst new file mode 100644 index 000000000..94c41979f --- /dev/null +++ b/doc/services/compute/index.rst @@ -0,0 +1,36 @@ +Compute v2 +========== + +.. note:: + + This is a joint service that supports both Rackspace Cloud Servers v2 API, and + OpenStack Nova v2 API. + +.. toctree:: + + images + flavors + servers + keypairs + +Glossary +-------- + +.. glossary:: + + image + An image is a collection of files for a specific operating system that you + use to create or rebuild a server. Rackspace provides prebuilt images. You + can also create custom images from servers that you have launched. + + flavor + A flavor is a named definition of certain server parameters such as + the amount of RAM and disk space available. (There are other parameters + set via the flavor, such as the amount of disk space and the number of + virtual CPUs, but a discussion of those is too in-depth for a simple + Getting Started Guide like this one.) + + server + A server is a virtual machine instance in the Cloud Servers environment. + + keypair diff --git a/doc/services/compute/keypairs.rst b/doc/services/compute/keypairs.rst new file mode 100644 index 000000000..4040c0e65 --- /dev/null +++ b/doc/services/compute/keypairs.rst @@ -0,0 +1,71 @@ +Keypairs +======== + +Setup +----- + +.. include:: service.sample.rst + + +Generate a new keypair +---------------------- + +This operation creates a new keypair under a provided name; the public key +value is automatically generated for you. + +.. code-block:: php + + // Instantiate empty object + $keypair = $service->keypair(); + + // Send to API + $keypair->create(array( + 'name' => 'jamie_keypair_1' + )); + + // Save these! + $pubKey = $keypair->getPublicKey(); + $priKey = $keypair->getPrivateKey(); + + +Upload existing keypair +----------------------- + +This operation creates a new keypair according to a provided name and public +key value. This is useful when the public key already exists on your local +filesystem. + +.. code-block:: php + + $keypair = $service->keypair(); + + // $key needs to be the string content of the key file, not the filename + $content = file_get_contents('~/.ssh/id_rsa.pub'); + + $keypair->create(array( + 'name' => 'main_key', + 'publicKey' => $content + )); + +List keypairs +------------- + +To list all existing keypairs: + +.. code-block:: php + + $keys = $service->listKeypairs(); + + foreach ($keys as $key) { + + } + + +Delete keypairs +--------------- + +To delete a specific keypair: + +.. code-block:: php + + $keypair->delete(); diff --git a/doc/services/compute/servers.rst b/doc/services/compute/servers.rst new file mode 100644 index 000000000..4d2f2363c --- /dev/null +++ b/doc/services/compute/servers.rst @@ -0,0 +1,202 @@ +Servers +======= + +Setup +----- + +.. include:: service.sample.rst + +Get server +---------- + +The easiest way to retrieve a specific server is by its unique ID: + +.. code-block:: php + + $server = $service->server('{serverId}'); + + +List servers +------------ + +You can list servers in two different ways: + +- return an *overview* of each server (ID, name and links) +- return *detailed information* for each server + +Knowing which option to use might help save unnecessary bandwidth and +reduce latency. + +.. code-block:: php + + // overview + $servers = $service->serverList(); + + // detailed + $servers = $service->serverList(true); + +URL parameters for filtering servers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ++--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ +| Name | Description | Type | ++==========================+====================================================================================================================================================================================================================================================================================================================+=================================================+ +| image | The image ID | string | ++--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ +| flavor | The flavor ID | string | ++--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ +| name | The server name | string | ++--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ +| status | The server status. Servers contain a status attribute that indicates the current server state. You can filter on the server status when you complete a list servers request, and the server status is returned in the response body. For a full list, please consult ``OpenCloud\Compute\Constants\ServerState`` | string | ++--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ +| changes-since | Value for checking for changes since a previous request | A valid ISO 8601 dateTime (2011-01-24T17:08Z) | ++--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ +| RAX-SI:image_schedule | If scheduled images enabled or not. If the value is TRUE, the list contains all servers that have an image schedule resource set on them. If the value is set to FALSE, the list contains all servers that do not have an image schedule. | bool | ++--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ + +Create server +------------- + +Using an image +~~~~~~~~~~~~~~ + +Now we're ready to create our instance: + +.. code-block:: php + + $server = $compute->server(); + + $server->create(array( + 'name' => 'My lovely server', + 'imageId' => '{imageId}', + 'flavorId' => '{flavorId}', + )); + +It's always best to be defensive when executing functionality over HTTP; +you can achieve this best by wrapping calls in a try/catch block. It +allows you to debug your failed operations in a graceful and efficient +manner. + +Using a bootable volume +~~~~~~~~~~~~~~~~~~~~~~~ + +Firstly we need to find our volume using their IDs. + +.. code-block:: php + + $bootableVolume = $client->volumeService()->volume('{volumeId}'); + +Now we're ready to create our instance: + +.. code-block:: php + + $server = $compute->server(); + + $response = $server->create(array( + 'name' => 'My lovely server', + 'volume' => $bootableVolume, + 'flavorId' => '{flavorId}' + )); + +It's always best to be defensive when executing functionality over HTTP; +you can achieve this best by wrapping calls in a try/catch block. It +allows you to debug your failed operations in a graceful and efficient +manner. + +Create parameters +~~~~~~~~~~~~~~~~~ + ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| Name | Description | Type | Required | ++=============================+=================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================+===========+==============================+ +| name | The server name. The name that you specify in a create request becomes the initial host name of the server. After the server is built, if you change the server name in the API or change the host name directly, the names are not kept in sync. | string | Yes | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| flavor | A populated ``OpenCloud\Compute\Resource\Flavor`` object representing your chosen flavor | object | Yes | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| image | A populated ``OpenCloud\Compute\Resource\Image`` object representing your chosen image | object | No, if volume is specified | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| volume | A populated ``OpenCloud\Volume\Resource\Volume`` object representing your chosen bootable volume | object | No, if image is specified | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| volumeDeleteOnTermination | ``true`` if the bootable volume should be deleted when the server is terminated; ``false``, otherwise | boolean | No; default = ``false`` | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| OS-DCF:diskConfig | The disk configuration value. You can use two options: ``AUTO`` or ``MANUAL``. \ ``AUTO`` means the server is built with a single partition the size of the target flavor disk. The file system is automatically adjusted to fit the entire partition. This keeps things simple and automated. ``AUTO`` is valid only for images and servers with a single partition that use the EXT3 file system. This is the default setting for applicable Rackspace base images.\ ``MANUAL`` means the server is built using whatever partition scheme and file system is in the source image. If the target flavor disk is larger, the remaining disk space is left unpartitioned. This enables images to have non-EXT3 file systems, multiple partitions, and so on, and enables you to manage the disk configuration. | string | No | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| networks | An array of populated ``OpenCloud\Compute\Resource\Network`` objects that indicate which networks your instance resides in. | array | No | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| metadata | An array of arbitrary data (key-value pairs) that adds additional meaning to your server. | array | No | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| keypair | You can install a registered keypair onto your newly created instance, thereby providing scope for keypair-based authentication. | array | No | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ +| personality | Files that you can upload to your newly created instance's filesystem. | array | No | ++-----------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+------------------------------+ + +Creating a server with keypairs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In order to provision an instance with a saved keypair (allowing you to SSH +in without passwords), you create your server using the same operation +as usual, with one extra parameter: + +.. code-block:: php + + $server = $compute->server(); + + $server->create(array( + 'name' => 'New server', + 'imageId' => '{imageId}', + 'flavorId' => '{flavorId}', + 'keypair' => 'main_key' + )); + +So, as you can see, you specify the **name** of an existing keypair that +you previously created on the API. + + +Creating a server with personality files +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Before you execute the create operation, you can add "personality" files +to your ``OpenCloud\Compute\Resource\Server`` object. These files are +structured as a flat array. + +.. code-block:: php + + $server->addFile('/var/test_file', 'FILE CONTENT'); + +As you can see, the first parameter represents the filename, and the +second is a string representation of its content. When the server is +created these files will be created on its local filesystem. For more +information about server personality files, please consult the `official +documentation `__. + +Update server +------------- + +You can update certain attributes of an existing server instance. These +attributes are detailed in the next section. + +.. code-block:: php + + $server->update(array( + 'name' => 'NEW SERVER NAME' + )); + +Updatable attributes +~~~~~~~~~~~~~~~~~~~~ + ++--------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ +| name | description | ++==============+==================================================================================================================================================+ +| name | The name of the server. If you edit the server name, the server host name does not change. Also, server names are not guaranteed to be unique. | ++--------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ +| accessIPv4 | The IP version 4 address. | ++--------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ +| accessIPv6 | The IP version 6 address. | ++--------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ + +Delete server +------------- + +.. code-block:: php + + $server->delete(); diff --git a/doc/services/compute/service.sample.rst b/doc/services/compute/service.sample.rst new file mode 100644 index 000000000..c684caf9a --- /dev/null +++ b/doc/services/compute/service.sample.rst @@ -0,0 +1,24 @@ +.. include:: ../common/rs-client.sample.rst + +Now, set up the Auto Scale service: + +.. code-block:: php + + $service = $client->computeService('{catalogName}', '{region}', '{urlType}'); + + +``{catalogName}`` is the **name** of the service, as it appears in the service +catalog. For Rackspace users, this will default to `cloudServersOpenStack`; for +OpenStack users, you must set your own value since it can depend on your +environment setup. + +``{region}`` is the Compute region the service will operate in. For Rackspace +users, you can select one of the following from the `supported regions page`. + +``{urlType}`` is the type of URL to use, depending on what endpoints your +catalog provides. For Rackspace, you may use either `internalURL` or `publicURL`. +The former will execute HTTP transactions over the internal Rackspace network, +reducing latency and the overall bandwidth cost - the caveat is that all of your +resources must be in same region. `publicURL`, however, which is the default, +will operate over the public Internet and is to be used for multi-region +installations. From 6a3dacc72ad189a55b207da41660a294d9dc1816 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:04:00 +0100 Subject: [PATCH 111/181] Add databases and DNS --- doc/services/database/README.md.rst | 125 ++++++++++++ doc/services/database/index.rst | 0 doc/services/dns/Domains.md.rst | 290 ++++++++++++++++++++++++++++ doc/services/dns/Limits.md.rst | 70 +++++++ doc/services/dns/Records.md.rst | 111 +++++++++++ doc/services/dns/Reverse-DNS.md.rst | 96 +++++++++ doc/services/dns/Service.md.rst | 13 ++ doc/services/dns/index.rst | 0 8 files changed, 705 insertions(+) create mode 100644 doc/services/database/README.md.rst create mode 100644 doc/services/database/index.rst create mode 100644 doc/services/dns/Domains.md.rst create mode 100644 doc/services/dns/Limits.md.rst create mode 100644 doc/services/dns/Records.md.rst create mode 100644 doc/services/dns/Reverse-DNS.md.rst create mode 100644 doc/services/dns/Service.md.rst create mode 100644 doc/services/dns/index.rst diff --git a/doc/services/database/README.md.rst b/doc/services/database/README.md.rst new file mode 100644 index 000000000..3f6bdd3c2 --- /dev/null +++ b/doc/services/database/README.md.rst @@ -0,0 +1,125 @@ +Databases +========= + +A **cloud database** is a MySQL relational database service that allows +customers to programatically provision database instances of varying +virtual resource sizes without the need to maintain and/or update MySQL. + +Getting started +--------------- + +1. Instantiate a Rackspace client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + use OpenCloud\Rackspace; + use OpenCloud\Common\Constants\State; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +2. Create a database server instance. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $databaseService = $client->databaseService('cloudDatabases', 'DFW'); + + $twoGbFlavor = $databaseService->flavor(3); + + $dbInstance = $databaseService->instance(); + $dbInstance->name = 'Demo database instance'; + $dbInstance->volume = new stdClass(); + $dbInstance->volume->size = 20; // GB + $dbInstance->flavor = $twoGbFlavor; + $dbInstance->create(); + + $dbInstance->waitFor(State::ACTIVE, null, function ($dbInstance) { + + printf("Database instance build status: %s\n", $dbInstance->status); + + }); + +The example above creates a database server instance with 20GB of disk +space and 2GB of memory, then waits for it to become ACTIVE. + +3. Create a database on the database server instance. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $db = $dbInstance->database(); + $db->name = 'demo_db'; + + $db->create(); + +The example above creates a database named ``demo_db`` on the database +server instance created in the previous step. + +4. Create database user and give it access to database. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $user = $dbInstance->user(); + $user->name = 'demo_user'; + $user->password = 'h@X0r!'; + $user->databases = array('demo_db'); + + $user->create(); + +The example above creates a database user named ``demo_user``, sets its +password and gives it access to the ``demo_db`` database created in the +previous step. + +5. Optional step: Create a load balancer to allow access to the database from the Internet. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The database created in the previous step can only be accessed from the +Rackspace private network (aka ``SERVICENET``). If you have a cloud +server instance in the same region as the database server instance, you +will be able to connect to the database from that cloud server instance. + +If, however, you would like to access the database from the Internet, +you will need to create a load balancer with an IP address that is +routable from the Internet and attach the database server instance as a +back-end node of this load balancer. + +.. code:: php + + $loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); + + $loadBalancer = $loadBalancerService->loadBalancer(); + + $loadBalancer->name = 'Load balancer - DB'; + $loadBalancer->addNode($dbInstance->hostname, 3306); + $loadBalancer->port = 3306; + $loadBalancer->protocol = 'MYSQL'; + $loadBalancer->addVirtualIp('PUBLIC'); + + $loadBalancer->create(); + + $loadBalancer->waitFor(State::ACTIVE, null, function ($lb) { + printf("Load balancer build status: %s\n", $lb->status); + }); + + foreach ($loadBalancer->virtualIps as $vip) { + if ($vip->type == 'PUBLIC') { + printf("Load balancer public %s address: %s\n", $vip->ipVersion, $vip->address); + } + } + +In the example above, a load balancer is created with the database +server instance as its only back-end node. Further, this load balancer +is configured to listen for MySQL connections on port 3306. Finally a +virtual IP address (VIP) is configured in the ``PUBLIC`` network address +space so that this load balancer may receive connections from the +Internet. + +Once the load balancer is created and becomes ``ACTIVE``, it's +Internet-accessible IP addresses are printed out. If you connect to any +of these IP addresses on port 3306 using the MySQL protocol, you will be +connected to the database created in step 3. diff --git a/doc/services/database/index.rst b/doc/services/database/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/dns/Domains.md.rst b/doc/services/dns/Domains.md.rst new file mode 100644 index 000000000..824c05099 --- /dev/null +++ b/doc/services/dns/Domains.md.rst @@ -0,0 +1,290 @@ +Domains +======= + +A domain is an entity/container of all DNS-related information +containing one or more records. + +Setup +----- + +Limit methods will be called on the DNS service, an instance of +``OpenCloud\DNS\Service``. Please see the `DNS service `__ +documentation for setup instructions. + +Get domain +---------- + +To retrieve a specific domain, you will need the domain's **id**, not +its domain name. + +.. code:: php + + $domain = $service->domain(12345); + +If you are having trouble remembering or accessing the domain ID, you +can do a domain list search for your domain and then access its ID. + +List domains +------------ + +These calls provide a list of all DNS domains manageable by a given +account. The resulting list is flat, and does not break the domains down +hierarchically by subdomain. All representative domains are included in +the list, even if a domain is conceptually a subdomain of another domain +in the list. + +.. code:: php + + $domains = $service->domainList(); + + # Return detailed information for each domain + $domains = $service->domainList(true); + +Please consult the `iterator +documentation `__ for more information +about iterators. + +Filter parameters +~~~~~~~~~~~~~~~~~ + +You can filter the aforementioned search by using the ``name`` parameter +in a key/value array supplied as a method argument. For example, +providing ``array('name' => 'hoola.com')`` will return hoola.com and +similar names such as main.hoola.com and sub.hoola.com. + +.. code:: php + + $hoolaDomains = $service->domainList(array( + 'name' => 'hoola.com' + )); + +Filter criteria may consist of: + +- Any letter (A-Za-z) +- Numbers (0-9) +- Hyphen ("-") +- 1 to 63 characters + +Filter criteria should not include any of the following characters: + + ' + , \| ! " £ $ % & / ( ) = ? ^ \* ç ° § ; : \_ > ] [ @ à, é, ò + +Finding a domain ID +~~~~~~~~~~~~~~~~~~~ + +If you know a domain's name, but not its unique identifier, you can do +this: + +.. code:: php + + $domains = $service->domainList(array( + 'name' => 'foo.com' + )); + + foreach ($domains as $domain) { + $id = $domain->id; + } + +List domain changes +------------------- + +This call shows all changes to the specified domain since the specified +date/time. The since parameter is optional and defaults to midnight of +the current day. + +.. code:: php + + $changes = $domain->changes(); + + # Changes since last week + $since = date('c', strtotime('last week')); + $changes = $domain->changes($since); + + foreach ($changes->changes as $change) { + printf("Domain: %s\nAction: %s\nTarget: %s", $change->domain, $change->action, $change->targetType); + + foreach ($change->changeDetails as $detail) { + printf("Details: %s was changed from %s to %s", $detail->field, $detail->oldValue, $detail->newValue); + } + } + +Export domain +------------- + +This call provides the BIND (Berkeley Internet Name Domain) 9 formatted +contents of the requested domain. This call is for a single domain only, +and as such, does not traverse up or down the domain hierarchy for +details (that is, no subdomain information is provided). + +.. code:: php + + $asyncResponse = $domain->export(); + $body = $asyncResponse->waitFor('COMPLETED'); + echo $body['contents']; + +Create domain +------------- + +A domain is composed of DNS records (e.g. ``A``, ``CNAME`` or ``MX`` +records) and an optional list of sub-domains. You will need to specify +these before creating the domain itself: + +.. code:: php + + // get empty object + $domain = $service->domain(); + + // add A record + $aRecord = $domain->record(array( + 'type' => 'A', + 'name' => 'example.com', + 'data' => '192.0.2.17', + 'ttl' => 3600 + )); + $domain->addRecord($aRecord); + + // add optional C record + $cRecord = $domain->record(array( + 'type' => 'CNAME', + 'name' => 'www.example.com', + 'data' => 'example.com', + 'ttl' => 3600 + )); + $domain->addRecord($cRecord); + + // add optional MX record + $mxRecord = $domain->record(array( + 'type' => 'MX', + 'data' => 'mail.example.com', + 'name' => 'example.com', + 'ttl' => 3600, + 'priority' => 5 + )); + $domain->addRecord($mxRecord); + + // add optional NS records + $nsRecord1 = $domain->record(array( + 'type' => 'NS', + 'data' => 'dns1.stabletransit.com', + 'name' => 'example.com', + 'ttl' => 5400 + )); + $domain->addRecord($nsRecord1); + + $nsRecord2 = $domain->record(array( + 'type' => 'NS', + 'data' => 'dns2.stabletransit.com', + 'name' => 'example.com', + 'ttl' => 5400 + )); + $domain->addRecord($nsRecord2); + + // add optional subdomains + $sub1 = $domain->subdomain(array( + 'emailAddress' => 'foo@example.com', + 'name' => 'dev.example.com', + 'comment' => 'Dev portal' + )); + $domain->addSubdomain($sub1); + + // send to API + $domain->create(array( + 'emailAddress' => 'webmaster@example.com', + 'ttl' => 3600, + 'name' => 'example.com', + 'comment' => 'Optional comment' + )); + +Clone domain +------------ + +This call will duplicate a single existing domain configuration with a +new domain name for the specified Cloud account. By default, all records +and, optionally, subdomain(s) are duplicated as well. + +The method signature you will need to use is: + +.. code:: php + + cloneDomain ( string $newDomainName [, bool $subdomains [, bool $comments [, bool $email [, bool $records ]]]] ) + ++----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Name | Data type | Default | Description | ++======================+==============+============+====================================================================================================================================================================================+ +| ``$newDomainName`` | ``string`` | - | The new name for your cloned domain | ++----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``$subdomains`` | ``bool`` | ``true`` | Set to ``TRUE`` to clone all the subdomains for this domain | ++----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``$comments`` | ``bool`` | ``true`` | Set to ``TRUE`` to replace occurrences of the reference domain name with the new domain name in comments on the cloned (new) domain. | ++----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``$email`` | ``bool`` | ``true`` | Set to ``TRUE`` to replace occurrences of the reference domain name with the new domain name in data fields (of records) on the cloned (new) domain. Does not affect NS records. | ++----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +For example: + +.. code:: php + + $asyncResponse = $domain->cloneDomain('new-name.com', true); + +Import domain +------------- + +This call provisions a new DNS domain under the account specified by the +BIND 9 formatted file configuration contents defined in the request +object. + +You will need to ensure that the BIND 9 formatted file configuration +contents are valid by adhering to the following rules: + +- Each record starts on a new line and on the first column. If a record + will not fit on one line, use the BIND\_9 line continuation + convention where you put a left parenthesis and continue the one + record on the next line and put a right parenthesis when the record + ends. For example, + + example2.net. 3600 IN SOA dns1.stabletransit.com. ( + sample@rackspace.com. 1308874739 3600 3600 3600 3600) + +- The attribute values of a record must be separated by a single blank + or tab. No other white space characters. + +- If there are any NS records, the data field should not be + dns1.stabletransit.com or dns2.stabletransit.com. They will result in + "duplicate record" errors. + +For example: + +.. code:: php + + $bind9Data = <<import($bind9Data); + +Modify domain +------------- + +This call modifies DNS domain(s) attributes only. Only the TTL, email +address and comment attributes of a domain can be modified. Records +cannot be added, modified, or removed through this API operation - you +will need to use the `add +records `__, `modify +records `__ or `remove +records `__ operations +respectively. + +.. code:: php + + $domain->update(array( + 'ttl' => ($domain->ttl + 100), + 'emailAddress' => 'new_dev@foo.com' + )); + +Remove domain +------------- + +.. code:: php + + $domain->delete(); + diff --git a/doc/services/dns/Limits.md.rst b/doc/services/dns/Limits.md.rst new file mode 100644 index 000000000..72f8219a0 --- /dev/null +++ b/doc/services/dns/Limits.md.rst @@ -0,0 +1,70 @@ +Limits +====== + +Setup +----- + +Limit methods will be called on the DNS service, an instance of +``OpenCloud\DNS\Service``. Please see the `DNS service `__ +documentation for setup instructions. + +List all limits +--------------- + +This call provides a list of all applicable limits for the specified +account. + +.. code:: php + + $limits = $service->limits(); + +Absolute limits +~~~~~~~~~~~~~~~ + +There are some absolute limits imposed on your account - such as how +many domains you can create and how many records you can create for each +domain: + +.. code:: php + + $absoluteLimits = $limits->absolute; + + # Domain limit + echo $absoluteLimits->domains; + + # Record limit per domain + echo $absoluteLimits->{'records per domain'}; + +List limit types +---------------- + +To find out the different limit types you can query, run: + +.. code:: php + + $limitTypes = $service->limitTypes(); + +will return: + +:: + + array(3) { + [0] => + string(10) "RATE_LIMIT" + [1] => + string(12) "DOMAIN_LIMIT" + [2] => + string(19) "DOMAIN_RECORD_LIMIT" + } + +Query a specific limit +---------------------- + +.. code:: php + + $limit = $service->limits('DOMAIN_LIMIT'); + + echo $limit->absolute->limits->value; + + >>> 500 + diff --git a/doc/services/dns/Records.md.rst b/doc/services/dns/Records.md.rst new file mode 100644 index 000000000..4e492e8ef --- /dev/null +++ b/doc/services/dns/Records.md.rst @@ -0,0 +1,111 @@ +Records +======= + +A DNS record belongs to a particular domain and is used to specify +information about the domain. + +There are several types of DNS records. Examples include mail exchange +(MX) records, which specify the mail server for a particular domain, and +name server (NS) records, which specify the authoritative name servers +for a domain. + +It is represented by the ``OpenCloud\DNS\Resource\Record`` class. +Records belong to a `Domain `__. + +Get record +---------- + +In order to retrieve details for a specific DNS record, you will need +its **id**: + +.. code:: php + + $record = $domain->record('NS-1234567'); + +If you do not have this ID at your disposal, you can traverse the record +collection and do a string comparison (detailed below). + +List records +------------ + +This call lists all records configured for the specified domain. + +.. code:: php + + $records = $domain->recordList(); + + foreach ($records as $record) { + printf("Record name: %s, ID: %s, TTL: %s\n", $record->name, $record->id, $record->ttl); + } + +Please consult the `iterator +documentation `__ for more information +about iterators. + +Query parameters +~~~~~~~~~~~~~~~~ + +You can pass in an array of query parameters for greater control over +your search: + ++------------+--------------+------------------------+---------------+ +| Name | Data type | Default | Description | ++============+==============+========================+===============+ +| ``type`` | ``string`` | The record type | ++------------+--------------+------------------------+---------------+ +| ``name`` | ``string`` | The record name | ++------------+--------------+------------------------+---------------+ +| ``data`` | ``string`` | Data for this record | ++------------+--------------+------------------------+---------------+ + +Find a record ID from its name +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For example: + +.. code:: php + + $records = $domain->recordList(array( + 'name' => 'imap.example.com', + 'type' => 'MX' + )); + + foreach ($records as $record) { + $recordId = $record->id; + } + +Add record +---------- + +This call adds a new record to the specified domain: + +.. code:: php + + $record = $domain->record(array( + 'type' => 'A', + 'name' => 'example.com', + 'data' => '192.0.2.17', + 'ttl' => 3600 + )); + + $record->create(); + +Please be aware that records that are added with a different hostname +than the parent domain might fail silently. + +Modify record +------------- + +.. code:: php + + $record = $domain->record(123456); + $record->ttl -= 100; + $record->update(); + +Delete record +------------- + +.. code:: php + + $record->delete(); + diff --git a/doc/services/dns/Reverse-DNS.md.rst b/doc/services/dns/Reverse-DNS.md.rst new file mode 100644 index 000000000..b8a5c0e76 --- /dev/null +++ b/doc/services/dns/Reverse-DNS.md.rst @@ -0,0 +1,96 @@ +Reverse DNS +=========== + +DNS usually determines an IP address associated with a domain name. +Reverse DNS is the opposite process: resolving a domain name from an IP +address. This is usually achieved with a domain name pointer. + +Get PTR record +-------------- + +PTR records refer to a parent device: either a Cloud Server or a Cloud +Load Balancer with a public virtual IP address. You must supply a fully +formed resource object in order to retrieve either one's PTR record: + +.. code:: php + + /** @param $parent OpenCloud\DNS\Resource\HasPtrRecordsInterface */ + + $ptr = $service->ptrRecord(array( + 'parent' => $parent + )); + +So, in the above example, a ``$parent`` could be an instance of +``OpenCloud\Compute\Resource\Server`` or +``OpenCloud\LoadBalancer\Resource\LoadBalancer`` - because they both +implement ``OpenCloud\DNS\Resource\HadPtrRecordsInterface``. Please +consult the `server documentation <../Compute/Server.md>`__ and `load +balancer documentation <../LoadBalancer/USERGUIDE.md>`__ for more +detailed usage instructions. + +List PTR records +---------------- + +.. code:: php + + /** @param $parent OpenCloud\DNS\Resource\HasPtrRecordsInterface */ + + $ptrRecords = $service->ptrRecordList($parent); + + foreach ($ptrRecords as $ptrRecord) { + + } + +Please consult the `iterator +documentation `__ for more information +about iterators. + +Add PTR record +-------------- + +.. code:: php + + $parent = $computeService->server('foo-server-id'); + + $ptr = $dnsService->ptrRecord(array( + 'parent' => $parent, + 'ttl' => 3600, + 'name' => 'example.com', + 'type' => 'PTR', + 'data' => '192.0.2.7' + )); + + $ptr->create(); + +Here is a table that explains the above attributes: + ++-----------+------------------------------------------------------------------------------------+------------+ +| Name | Description | Required | ++===========+====================================================================================+============+ +| type | Specifies the record type as "PTR". | Yes | ++-----------+------------------------------------------------------------------------------------+------------+ +| name | Specifies the name for the domain or subdomain. Must be a valid domain name. | Yes | ++-----------+------------------------------------------------------------------------------------+------------+ +| data | The data field for PTR records must be a valid IPv4 or IPv6 IP address. | Yes | ++-----------+------------------------------------------------------------------------------------+------------+ +| ttl | If specified, must be greater than 300. Defaults to 3600 if no TTL is specified. | No | ++-----------+------------------------------------------------------------------------------------+------------+ +| comment | If included, its length must be less than or equal to 160 characters. | No | ++-----------+------------------------------------------------------------------------------------+------------+ + +Modify PTR record +----------------- + +.. code:: php + + $ptr->update(array( + 'ttl' => $ptr->ttl * 2 + )); + +Delete PTR record +----------------- + +.. code:: php + + $ptr->delete(); + diff --git a/doc/services/dns/Service.md.rst b/doc/services/dns/Service.md.rst new file mode 100644 index 000000000..29ea79193 --- /dev/null +++ b/doc/services/dns/Service.md.rst @@ -0,0 +1,13 @@ +DNS Service +=========== + +To instantiate a Compute service object, you first need to setup a +Rackspace/OpenStack client. To do this, or for more information, please +consult the `Clients documentation <../Clients.md>`__. + +You will then need to run: + +.. code:: php + + $service = $client->dnsService(); + diff --git a/doc/services/dns/index.rst b/doc/services/dns/index.rst new file mode 100644 index 000000000..e69de29bb From b2276a9883f50ac7d6ab67db4232e8ac6cacaad8 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:04:13 +0100 Subject: [PATCH 112/181] Add Identity and Images --- doc/services/identity/Roles.md.rst | 92 +++++++++++++++ doc/services/identity/Service.md.rst | 35 ++++++ doc/services/identity/Tenants.md.rst | 29 +++++ doc/services/identity/Tokens.md.rst | 105 +++++++++++++++++ doc/services/identity/Users.md.rst | 170 +++++++++++++++++++++++++++ doc/services/identity/index.rst | 0 doc/services/image/Images.md.rst | 107 +++++++++++++++++ doc/services/image/Schemas.md.rst | 170 +++++++++++++++++++++++++++ doc/services/image/Sharing.md.rst | 129 ++++++++++++++++++++ doc/services/image/Tags.md.rst | 28 +++++ doc/services/image/index.rst | 0 11 files changed, 865 insertions(+) create mode 100644 doc/services/identity/Roles.md.rst create mode 100644 doc/services/identity/Service.md.rst create mode 100644 doc/services/identity/Tenants.md.rst create mode 100644 doc/services/identity/Tokens.md.rst create mode 100644 doc/services/identity/Users.md.rst create mode 100644 doc/services/identity/index.rst create mode 100644 doc/services/image/Images.md.rst create mode 100644 doc/services/image/Schemas.md.rst create mode 100644 doc/services/image/Sharing.md.rst create mode 100644 doc/services/image/Tags.md.rst create mode 100644 doc/services/image/index.rst diff --git a/doc/services/identity/Roles.md.rst b/doc/services/identity/Roles.md.rst new file mode 100644 index 000000000..96a56488f --- /dev/null +++ b/doc/services/identity/Roles.md.rst @@ -0,0 +1,92 @@ +Roles +===== + +Intro +----- + +A role is a personality that a user assumes when performing a specific +set of operations. A role includes a set of rights and privileges. A +user assuming a role inherits the rights and privileges associated with +the role. A token that is issued to a user includes the list of roles +the user can assume. When a user calls a service, that service +determines how to interpret a user's roles. A role that grants access to +a list of operations or resources within one service may grant access to +a completely different list when interpreted by a different service. + +Setup +----- + +Role objects are instantiated from the Identity service. For more +details, see the `Service `__ docs. + +Useful object properties/methods +-------------------------------- + ++---------------+------------------------+------------------------+ +| Property | Getter | Setter | ++===============+========================+========================+ +| id | ``getId()`` | ``setId()`` | ++---------------+------------------------+------------------------+ +| name | ``getName()`` | ``setName()`` | ++---------------+------------------------+------------------------+ +| description | ``getDescription()`` | ``setDescription()`` | ++---------------+------------------------+------------------------+ + +List roles +---------- + +This call lists the global roles available within a specified service. + +.. code:: php + + $roles = $service->getRoles(); + + foreach ($roles as $role) { + // ... + } + +For more information about how to use iterators, see the +`documentation <../Iterators.md>`__. + +Get role +-------- + +This call lists detailed information (id, name, description) for a +specified role. + +.. code:: php + + $roleId = '123abc'; + $role = $service->getRole($roleId); + +Add/delete user roles +--------------------- + +To add/remove user roles, you must first instantiate a +`user `__ object: + +.. code:: php + + $roleId = '123abc'; + + // add role to user + $user->addRole($roleId); + + // remove role from user + $user->removeRole($roleId); + +List user global roles +---------------------- + +This call returns a list of global roles associated with a user: + +.. code:: php + + $roles = $user->getRoles(); + + foreach ($roles as $role) { + // ... + } + +For more information about how to use iterators, see the +`documentation <../Iterators.md>`__. diff --git a/doc/services/identity/Service.md.rst b/doc/services/identity/Service.md.rst new file mode 100644 index 000000000..f7e8e12ba --- /dev/null +++ b/doc/services/identity/Service.md.rst @@ -0,0 +1,35 @@ +Identity service +================ + +Intro +----- + +The Identity service is regionless, so you do not need to specify a +region when instantiating the service object. Although this was +primarily based on Rackspace's implementation of Cloud Identity, it +should also work for OpenStack Keystone. + +A note on object creation +------------------------- + +Normally, when services are created the client handles authenticates +automatically. But because Keystone/Identity is fundamental to the +authentication process itself, it proves difficult to do this procedure +as its normally done. For this reason, you have two options when +creating the service object: + +1: Use the client's factory method + +.. code:: php + + $identity = $client->identityService(); + +2: Authenticate manually + +.. code:: php + + use OpenCloud\Identity\Service as IdentityService; + + $identity = IdentityService::factory($client); + $identity->getClient()->authenticate(); + diff --git a/doc/services/identity/Tenants.md.rst b/doc/services/identity/Tenants.md.rst new file mode 100644 index 000000000..9b58efd1a --- /dev/null +++ b/doc/services/identity/Tenants.md.rst @@ -0,0 +1,29 @@ +Tenants +======= + +Intro +----- + +A tenant is a container used to group or isolate resources and/or +identity objects. Depending on the service operator, a tenant may map to +a customer, account, organization, or project. + +Setup +----- + +Tenant objects are instantiated from the Identity service. For more +details, see the `Service `__ docs. + +List tenants +------------ + +.. code:: php + + $tenants = $service->getTenants(); + + foreach ($tenants as $tenant) { + // ... + } + +For more information about how to use iterators, see the +`documentation <../Iterators.md>`__. diff --git a/doc/services/identity/Tokens.md.rst b/doc/services/identity/Tokens.md.rst new file mode 100644 index 000000000..c42ce1573 --- /dev/null +++ b/doc/services/identity/Tokens.md.rst @@ -0,0 +1,105 @@ +Tokens +====== + +Intro +----- + +A token is an opaque string that represents an authorization to access +cloud resources. Tokens may be revoked at any time and are valid for a +finite duration. + +Setup +----- + +Token objects are instantiated from the Identity service. For more +details, see the `Service `__ docs. + +Useful object properties/methods +-------------------------------- + ++------------+-------------------------------------------+----------------------------------------+--------------------+ +| Property | Description | Getter | Setter | ++============+===========================================+========================================+====================+ +| id | The unique ID of the token | ``getId()`` | ``setId()`` | ++------------+-------------------------------------------+----------------------------------------+--------------------+ +| expires | Timestamp of when the token will expire | ``getExpires()`` or ``hasExpired()`` | ``setExpires()`` | ++------------+-------------------------------------------+----------------------------------------+--------------------+ + +Create token (authenticate) +--------------------------- + +In order to generate a token, you must pass in the JSON template that is +sent to the API. This is because Rackspace's operation expects a +slightly different entity body than OpenStack Keystone. + +Request body for Rackspace's generate token operation: + +.. code:: json + + { + "auth": { + "RAX-KSKEY:apiKeyCredentials": { + "username": "foo", + "apiKey": "aaaaa-bbbbb-ccccc-12345678" + }, + "tenantId": "1100111" + } + } + +Request body for Keystone's generate token operation: + +.. code:: json + + { + "auth": { + "passwordCredentials":{ + "username":"demoauthor", + "password":"theUsersPassword" + }, + "tenantId": "12345678" + } + } + +The only real differences you'll notice is the name of the object key +(``RAX-KSKEY:apiKeyCredentials``/``passwordCredentials``) and the secret +(``apiKey``/``password``). The ``tenantId`` property in both templates +are optional. You can also add ``tenantName`` too. + +.. code:: php + + use OpenCloud\Common\Http\Message\Formatter; + + $template = sprintf( + '{"auth": {"RAX-KSKEY:apiKeyCredentials":{"username": "%s", "apiKey": "%s"}}}', + 'my_username', + 'my_api_key' + ); + + $response = $service->generateToken($template); + + $body = Formatter::decode($response); + + // service catalog + $catalog = $body->access->serviceCatalog; + + // token + $token = $body->access->token; + + // user + $user = $body->access->user; + +As you will notice, these variables will be stdClass objects - for fully +fledged functionality, let the client authenticate by itself because it +ends up stocking the necessary models for you. + +To see the response body structure, consult the `official +docs `__. + +Revoke token (destroy session) +------------------------------ + +.. code:: php + + $tokenId = '1234567'; + $service->revokeToken($tokenId); + diff --git a/doc/services/identity/Users.md.rst b/doc/services/identity/Users.md.rst new file mode 100644 index 000000000..e8c2e6d63 --- /dev/null +++ b/doc/services/identity/Users.md.rst @@ -0,0 +1,170 @@ +Users +===== + +Intro +----- + +A user is a digital representation of a person, system, or service who +consumes cloud services. Users have credentials and may be assigned +tokens; based on these credentials and tokens, the authentication +service validates that incoming requests are being made by the user who +claims to be making the request, and that the user has the right to +access the requested resources. Users may be directly assigned to a +particular tenant and behave as if they are contained within that +tenant. + +Setup +----- + +User objects are instantiated from the Identity service. For more +details, see the `Service `__ docs. + +Useful object properties/methods +-------------------------------- + ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ +| Property | Description | Getter | Setter | ++=================+===============================================================================================================================================================================================================================================================================================================================+============================================+===============================================================================================================+ +| id | The unique ID for this user | ``getId()`` | ``setId()`` | ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ +| username | Username for this user | ``getUsername()`` | ``setUsername()`` | ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ +| email | User's email address | ``getEmail()`` | ``setEmail()`` | ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ +| enabled | Whether or not this user can consume API functionality | ``getEnabled()`` or ``isEnabled()`` | ``setEnabled()`` | ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ +| password | Either a user-defined string, or an automatically generated one, that provides security when authenticating. | ``getPassword()`` only valid on creation | ``setPassword()`` to set local property only. To set password on API (retention), use ``updatePassword()``. | ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ +| defaultRegion | Default region associates a user with a specific regional datacenter. If a default region has been assigned for this user and that user has **NOT** explicitly specified a region when creating a service object, the user will obtain the service from the default region. | ``getDefaultRegion()`` | ``setDefaultRegion()`` | ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ +| domainId | Domain ID associates a user with a specific domain which was assigned when the user was created or updated. A domain establishes an administrative boundary for a customer and a container for a customer's tenants (accounts) and users. Generally, a domainId is the same as the primary tenant id of your cloud account. | ``getDomainId()`` | ``setDomainId()`` | ++-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ + +List users +---------- + +.. code:: php + + $users = $service->getUsers(); + + foreach ($users as $user) { + // ... + } + +For more information about how to use iterators, see the +`documentation <../Iterators.md>`__. + +Get user +-------- + +There are various ways to get a specific user: by name, ID and email +address. + +.. code:: php + + use OpenCloud\Identity\Constants\User as UserConst; + + // Get user by name + $user1 = $service->getUser('jamie'); + + // Get user by ID + $user2 = $service->getUser(123456, UserConst::MODE_ID); + + // Get user by email + $user3 = $service->getUser('jamie.hannaford@rackspace.com', UserConst::MODE_EMAIL); + +Create user +----------- + +There are a few things to remember when creating a user: + +- This operation is available only to users who hold the + ``identity:user-admin`` role. This admin can create a user who holds + the ``identity:default`` user role. + +- The created user **will** have access to APIs but **will not** have + access to the Cloud Control Panel. + +- Within an account, a maximum of 100 account users can be added. + +- If you attempt to add a user who already exists, an HTTP error 409 + results. + +The ``username`` and ``email`` properties are required for creating a +user. Providing a ``password`` is optional; if omitted, one will be +automatically generated and provided in the response. + +.. code:: php + + use Guzzle\Http\Exception\ClientErrorResponseException; + + try { + // execute operation + $user = $service->createUser(array( + 'username' => 'newUser', + 'email' => 'foo@bar.com' + )); + } catch (ClientErrorResponseException $e) { + // catch 4xx HTTP errors + echo $e->getResponse()->toString(); + } + + // show generated password + echo $user->getPassword(); + +Update user +----------- + +When updating a user, specify which attribute/property you want to +update: + +.. code:: php + + $user->update(array( + 'email' => 'new_email@bar.com' + )); + +Updating a user password +~~~~~~~~~~~~~~~~~~~~~~~~ + +Updating a user password requires calling a distinct method: + +.. code:: php + + $user->updatePassword('password123'); + +Delete user +----------- + +.. code:: php + + $user->delete(); + +List credentials +---------------- + +This operation allows you to see your non-password credential types for +all authentication methods available. + +.. code:: php + + $creds = $user->getOtherCredentials(); + +Get user API key +---------------- + +.. code:: php + + echo $user->getApiKey(); + +Reset user API key +------------------ + +When resetting an API key, a new one will be automatically generated for +you: + +.. code:: php + + $user->resetApiKey(); + echo $user->getApiKey(); + diff --git a/doc/services/identity/index.rst b/doc/services/identity/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/image/Images.md.rst b/doc/services/image/Images.md.rst new file mode 100644 index 000000000..ef187f083 --- /dev/null +++ b/doc/services/image/Images.md.rst @@ -0,0 +1,107 @@ +Images +====== + +A virtual machine image is a single file which contains a virtual disk +that has an installed bootable operating system. In the Cloud Images +API, an image is represented by a JSON-encoded data structure (the image +schema) and its raw binary data (the image file). + +An Image is represented by the ``OpenCloud\Image\Resource\Image`` class. + +Setup +----- + +You instantiate an Image object from its ``OpenCloud\Image\Service`` +class, which is available from the OpenStack/Rackspace client: + +.. code:: php + + $service = $client->imageService('cloudImages', 'IAD'); + +View the guides for more information about `clients <../Clients.md>`__ +or `services <../Services.md>`__. + +List images +----------- + +.. code:: php + + $images = $service->listImages(); + + foreach ($images as $image) { + /** @param $image OpenCloud\Image\Resource\Image */ + } + +For more information about working with iterators, please see the +`iterators documentation <../Iterators.md>`__. + +Get image details +----------------- + +.. code:: php + + /** @param $image OpenCloud\Image\Resource\Image */ + $image = $service->getImage(''); + +A note on schema classes +~~~~~~~~~~~~~~~~~~~~~~~~ + +Both ``OpenCloud\Image\Resource\Image`` and +``OpenCloud\Image\Resource\Member`` extend the +``AbstractSchemaResource`` abstract class, which offers some unique +functionality. + +Because these resources are inherently dynamic - i.e. they are modelled +on dynamic JSON schema - you need to access their state in a way +different than conventional getter/setter methods, and even class +properties. For this reason, they implement SPL's native +```ArrayAccess`` `__ +interface which allows you to access their state as a conventional +array: + +.. code:: php + + $image = $service->getImage(''); + + $id = $image['id']; + $tags = $image['tags']; + +Update image +------------ + +You can only update your own custom images - you cannot update or delete +base images. The way in which you may update your image is dictated by +its `schema `__. + +Although you should be able to add new and replace existing properties, +always prepare yourself for a situation where it might be forbidden: + +.. code:: php + + use OpenCloud\Common\Exceptions\ForbiddenOperationException; + + try { + $image->update(array( + 'name' => 'foo', + 'newProperty' => 'bar' + )); + } catch (ForbiddenOperationException $e) { + // A 403 Forbidden was returned + } + +There are three operations that can take place for each Image property: + +- If a ``false`` or ``null`` value is provided, a ``REMOVE`` operation + will occur, removing the property from the JSON document +- If a non-false value is provided and the property does not exist, an + ``ADD`` operation will add it to the document +- If a non-false value is provided and the property does exist, a + ``REPLACE`` operation will modify the property in the document + +Delete image +------------ + +.. code:: php + + $image->delete(); + diff --git a/doc/services/image/Schemas.md.rst b/doc/services/image/Schemas.md.rst new file mode 100644 index 000000000..8f792c4c0 --- /dev/null +++ b/doc/services/image/Schemas.md.rst @@ -0,0 +1,170 @@ +JSON schemas +============ + +The Cloud Images API supplies json documents describing the JSON-encoded +data structures that represent domain objects, so that a client knows +exactly what to expect in an API response. + +A JSON Schema is represented by the +``OpenCloud\Image\Resource\Schema\Schema`` class. + +Schema types +------------ + +There are currently four types of schema: Images schema, Image schema, +Members schema, and Member schema. + +Example response from the API +----------------------------- + +A sample response from the API, for an Images schema might be: + +.. code:: json + + { + "name": "images", + "properties": { + "images": { + "items": { + "type": "array", + "name": "image", + "properties": { + "id": {"type": "string"}, + "name": {"type": "string"}, + "visibility": {"enum": ["public", "private"]}, + "status": {"type": "string"}, + "protected": {"type": "boolean"}, + "tags": { + "type": "array", + "items": {"type": "string"} + }, + "checksum": {"type": "string"}, + "size": {"type": "integer"}, + "created_at": {"type": "string"}, + "updated_at": {"type": "string"}, + "file": {"type": "string"}, + "self": {"type": "string"}, + "schema": {"type": "string"} + }, + "additionalProperties": {"type": "string"}, + "links": [ + {"href": "{self}", "rel": "self"}, + {"href": "{file}", "rel": "enclosure"}, + {"href": "{schema}", "rel": "describedby"} + ] + } + }, + "schema": {"type": "string"}, + "next": {"type": "string"}, + "first": {"type": "string"} + }, + "links": [ + {"href": "{first}", "rel": "first"}, + {"href": "{next}", "rel": "next"}, + {"href": "{schema}", "rel": "describedby"} + ] + } + +The top-level schema is called ``images``, and contains an array of +links and a properties object. Inside this properties object we see the +structure of this top-level ``images`` object. So we know that it will +take this form: + +.. code:: json + + { + "images": [something...] + } + +Within this object, we can see that it contains an array of anonymous +objects, each of which is called ``image`` and has its own set of nested +properties: + +.. code:: json + + { + "images": [ + { + [object 1...] + }, + { + [object 2...] + }, + { + [object 3...] + } + ] + } + +The structure of these nested objects are defined as another schema - +i.e. a *subschema*. We know that each object has an ID property +(string), a name property (string), a visibility property (can either be +``private`` or ``public``), etc. + +.. code:: json + + { + "images": [ + { + "id": "foo", + "name": "bar", + "visibility": "private", + // etc. + }, + { + "id": "foo", + "name": "bar", + "visibility": "private", + // etc. + }, + { + "id": "foo", + "name": "bar", + "visibility": "private", + // etc. + } + ] + } + +Each nested property of a schema is represented by the +``OpenCloud\Image\Resource\Schema\Property`` class. + +If you would like to find out more about schemas, Guzzle has good +documentation about `service +descriptions `__, +which is fairly analogous. + +JSON Patch +---------- + +The Glance API has a unique way of updating certain dynamic resources: +they use JSON Patch method, as outlined in `RFC +6902 `__. + +Requests need to use the +``application/openstack-images-v2.1-json-patch`` content-type. + +In order for the operation to occur, the request entity body needs to +contain a very particular structure: + +:: + + [ + {"op": "replace", "path": "/name", "value": "Fedora 17"}, + {"op": "replace", "path": "/tags", "value": ["fedora", "beefy"]} + ] + +The ``op`` key refers to the type of Operation (see +``OpenCloud\Image\Enum\OperationType`` for a full list). + +The ``path`` key is a JSON pointer to the document property you want to +modify or insert. JSON pointers are defined in `RFC +6901 `__. + +The ``value`` key is the value. + +Because this is all handled for you behind the scenes, we will not go +into exhaustive depth about how this operation is handled. You can +browse the source code, consult the various RFCs and the `official +documentation `__ +for additional information. diff --git a/doc/services/image/Sharing.md.rst b/doc/services/image/Sharing.md.rst new file mode 100644 index 000000000..b1a1ea382 --- /dev/null +++ b/doc/services/image/Sharing.md.rst @@ -0,0 +1,129 @@ +Sharing images +============== + +Images can be created and deleted by image producers, updated by image +consumers, and listed by both image producers and image consumers: + ++-------------+-----------------+-----------------+ +| Operation | Producer can? | Consumer can? | ++=============+=================+=================+ +| Created | Yes | No | ++-------------+-----------------+-----------------+ +| Deleted | Yes | No | ++-------------+-----------------+-----------------+ +| Updated | No | Yes | ++-------------+-----------------+-----------------+ +| Listed | Yes | Yes | ++-------------+-----------------+-----------------+ + +The producer shares an image with the consumer by making the consumer a +*member* of that image. The consumer then accepts or rejects the image +by changing the member status. Once accepted, the image appears in the +consumer's image list. + +Typical workflow +---------------- + +1. The producer posts the availability of specific images on a public + website. + +2. A potential consumer provides the producer with his/her tenant ID and + email address. + +3. The producer `creates a new Image Member <>`__ with the consumer's + details + +4. The producer notifies the consumer via email that the image has been + shared and provides the image's ID. + +5. If the consumer wishes the image to appear in his/her image list, the + consumer `updates their own Member status <>`__ to ``ACCEPTED``. + +Additional notes +~~~~~~~~~~~~~~~~ + +- If the consumer subsequently wishes to hide the image, the consumer + can change their Member status to ``REJECTED``. + +- If the consumer wishes to hide the image, but is open to the + possibility of being reminded by the producer that the image is + available, the consumer can change their Member status to + ``PENDING``. + +- Image producers add or remove image members, but may not modify the + member status of an image member. + +- Image consumers change their own member status, but may not add or + remove themselves as an image member. + +- Image consumers can boot from any image shared by the image producer, + regardless of the member status, as long as the image consumer knows + the image ID. + +Setup +----- + +All member operations are executed against an `Image `__, so +you will need to set this up first. + +List image members +------------------ + +This operation is available for both producers and consumers. + +.. code:: php + + $members = $image->listMembers(); + + foreach ($members as $member) { + /** @param $member OpenCloud\Image\Resource\Member */ + } + +For more information about working with iterators, please see the +`iterators documentation <../Iterators.md>`__. + +Create image member +------------------- + +This operation is only available for producers. + +.. code:: php + + $tenantId = 12345; + + /** @param $response Guzzle\Http\Message\Response */ + $response = $image->createMember($tenantId); + +Delete image member +------------------- + +This operation is only available for producers. + +.. code:: php + + $tenantId = 12345; + + /** @param $member OpenCloud\Image\Resource\Member */ + $member = $image->getMember($tenantId); + + $member->delete(); + +Update image member status +-------------------------- + +This operation is only available for consumers. + +.. code:: php + + use OpenCloud\Images\Enum\MemberStatus; + + $tenantId = 12345; + + /** @param $member OpenCloud\Image\Resource\Member */ + $member = $image->getMember($tenantId); + + $member->updateStatus(MemberStatus::ACCEPTED); + +The acceptable states you may pass in are made available to you through +the constants defined in the ``OpenCloud\Images\Enum\MemberStatus`` +class. diff --git a/doc/services/image/Tags.md.rst b/doc/services/image/Tags.md.rst new file mode 100644 index 000000000..af5baf157 --- /dev/null +++ b/doc/services/image/Tags.md.rst @@ -0,0 +1,28 @@ +Image tags +========== + +An image tag is a string of characters used to identify a specific image +or images. + +Setup +----- + +All member operations are executed against an `Image `__, so +you will need to set this up first. + +Add image tag +------------- + +.. code:: php + + /** @param $response Guzzle\Http\Message\Response */ + $response = $image->addTag('jamie_dev'); + +Delete image tag +---------------- + +.. code:: php + + /** @param $response Guzzle\Http\Message\Response */ + $response = $image->deleteTag('jamie_dev'); + diff --git a/doc/services/image/index.rst b/doc/services/image/index.rst new file mode 100644 index 000000000..e69de29bb From 686a5bf839ee5b768051535e5905dab5d833345f Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:04:26 +0100 Subject: [PATCH 113/181] Add remaining --- doc/services/load-balancer/README.md.rst | 92 ++ doc/services/load-balancer/USERGUIDE.md.rst | 840 ++++++++++++++++ doc/services/load-balancer/index.rst | 0 doc/services/monitoring/Agents.md.rst | 202 ++++ doc/services/monitoring/Alarms.md.rst | 81 ++ doc/services/monitoring/Changelogs.md.rst | 21 + doc/services/monitoring/Checks.md.rst | 211 ++++ doc/services/monitoring/Entities.md.rst | 77 ++ doc/services/monitoring/Metrics.md.rst | 131 +++ doc/services/monitoring/Notifications.md.rst | 281 ++++++ doc/services/monitoring/Service.md.rst | 23 + doc/services/monitoring/Views.md.rst | 27 + doc/services/monitoring/Zones.md.rst | 67 ++ doc/services/monitoring/index.rst | 0 doc/services/networking/README.md.rst | 108 +++ doc/services/networking/USERGUIDE.md.rst | 582 +++++++++++ doc/services/networking/index.rst | 0 doc/services/object-store/Access.md.rst | 75 ++ doc/services/object-store/Account.md.rst | 33 + .../object-store/Container.md.cdn.rst | 90 ++ .../object-store/Container.md.storage.rst | 218 +++++ .../object-store/Migrating.md.storage.rst | 101 ++ doc/services/object-store/Object.md.cdn.rst | 25 + .../object-store/Object.md.storage.rst | 330 +++++++ doc/services/object-store/README.md.rst | 86 ++ doc/services/object-store/USERGUIDE.md.rst | 900 ++++++++++++++++++ doc/services/object-store/index.rst | 0 doc/services/orchestration/README.md.rst | 98 ++ doc/services/orchestration/USERGUIDE.md.rst | 672 +++++++++++++ doc/services/orchestration/index.rst | 0 doc/services/queues/Claim.md.rst | 164 ++++ doc/services/queues/Message.md.rst | 257 +++++ doc/services/queues/Queue.md.rst | 197 ++++ doc/services/queues/index.rst | 0 doc/services/volume/index.rst | 0 35 files changed, 5989 insertions(+) create mode 100644 doc/services/load-balancer/README.md.rst create mode 100644 doc/services/load-balancer/USERGUIDE.md.rst create mode 100644 doc/services/load-balancer/index.rst create mode 100644 doc/services/monitoring/Agents.md.rst create mode 100644 doc/services/monitoring/Alarms.md.rst create mode 100644 doc/services/monitoring/Changelogs.md.rst create mode 100644 doc/services/monitoring/Checks.md.rst create mode 100644 doc/services/monitoring/Entities.md.rst create mode 100644 doc/services/monitoring/Metrics.md.rst create mode 100644 doc/services/monitoring/Notifications.md.rst create mode 100644 doc/services/monitoring/Service.md.rst create mode 100644 doc/services/monitoring/Views.md.rst create mode 100644 doc/services/monitoring/Zones.md.rst create mode 100644 doc/services/monitoring/index.rst create mode 100644 doc/services/networking/README.md.rst create mode 100644 doc/services/networking/USERGUIDE.md.rst create mode 100644 doc/services/networking/index.rst create mode 100644 doc/services/object-store/Access.md.rst create mode 100644 doc/services/object-store/Account.md.rst create mode 100644 doc/services/object-store/Container.md.cdn.rst create mode 100644 doc/services/object-store/Container.md.storage.rst create mode 100644 doc/services/object-store/Migrating.md.storage.rst create mode 100644 doc/services/object-store/Object.md.cdn.rst create mode 100644 doc/services/object-store/Object.md.storage.rst create mode 100644 doc/services/object-store/README.md.rst create mode 100644 doc/services/object-store/USERGUIDE.md.rst create mode 100644 doc/services/object-store/index.rst create mode 100644 doc/services/orchestration/README.md.rst create mode 100644 doc/services/orchestration/USERGUIDE.md.rst create mode 100644 doc/services/orchestration/index.rst create mode 100644 doc/services/queues/Claim.md.rst create mode 100644 doc/services/queues/Message.md.rst create mode 100644 doc/services/queues/Queue.md.rst create mode 100644 doc/services/queues/index.rst create mode 100644 doc/services/volume/index.rst diff --git a/doc/services/load-balancer/README.md.rst b/doc/services/load-balancer/README.md.rst new file mode 100644 index 000000000..862cf20d2 --- /dev/null +++ b/doc/services/load-balancer/README.md.rst @@ -0,0 +1,92 @@ +Load Balancers +============== + +A **load balancer** is a device that distributes incoming network +traffic amongst multiple back-end systems. These back-end systems are +called the **nodes** of the load balancer. + +Getting started +--------------- + +1. Instantiate a Rackspace client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +2. Retrieve the server instances you want to add as nodes of the load balancer. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $computeService = $client->computeService('cloudServersOpenStack', 'DFW'); + + $serverOne = $computeService->server('e836fc4e-056d-4447-a80e-fefcaa640216'); + $serverTwo = $computeService->server('5399cd36-a23f-41a6-bdf7-20902aec0e74'); + +The example above uses two server instances that have already been +created. It retrieves the server instances using their IDs. See also: +`creating server instances <>`__. + +3. Obtain a Load Balancer service object from the client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This object will be used to first define the load balancer nodes and +later create the load balancer itself. + +.. code:: php + + $loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); + +4. Define a load balancer node for each server. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $loadBalancer = $loadBalancerService->loadBalancer(); + + $serverOneNode = $loadBalancer->node(); + $serverOneNode->address = $serverOne->addresses->private[0]->addr; + $serverOneNode->port = 8080; + $serverOneNode->condition = 'ENABLED'; + + $serverTwoNode = $loadBalancer->node(); + $serverTwoNode->address = $serverTwo->addresses->private[0]->addr; + $serverTwoNode->port = 8080; + $serverTwoNode->condition = 'ENABLED'; + +In the example above, each node runs a service that listens on port +8080. Further, each node will start out as ``ENABLED``, which means it +will be ready to receive network traffic from the load balancer as soon +as it is created. + +5. Create the load balancer with the two nodes. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $loadBalancer->addVirtualIp('PUBLIC'); + $loadBalancer->create(array( + 'name' => 'My smart load balancer', + 'port' => 80, + 'protocol' => 'HTTP', + 'nodes' => array($serverOneNode, $serverTwoNode) + )); + +In the example above, the load balancer will have a virtual IP address +accessible from the public Internet. Also notice that the port the load +balancer listens on (80) does not need to match the ports of its nodes +(8080). + +Next steps +---------- + +Once you have created a load balancer, there is a lot you can do with +it. See the `complete user guide for load balancers `__. diff --git a/doc/services/load-balancer/USERGUIDE.md.rst b/doc/services/load-balancer/USERGUIDE.md.rst new file mode 100644 index 000000000..788651f2b --- /dev/null +++ b/doc/services/load-balancer/USERGUIDE.md.rst @@ -0,0 +1,840 @@ +The Complete User Guide to Load Balancers +========================================= + +Prerequisites +------------- + +Client +~~~~~~ + +To use the load balancers service, you must first instantiate a +``Rackspace`` client object. + +.. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +Load Balancer Service +~~~~~~~~~~~~~~~~~~~~~ + +All operations on load balancers are done via a load balancer service +object. + +.. code:: php + + $loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); + +Cloud Servers +~~~~~~~~~~~~~ + +Many of the examples in this document use two cloud servers as nodes for +the load balancer. The variables ``$serverOne`` and ``$serverTwo`` refer +to these two cloud servers. + +Load Balancers +-------------- + +A **load balancer** is a device that distributes incoming network +traffic amongst multiple back-end systems. These back-end systems are +called the **nodes** of the load balancer. + +Create Load Balancer +~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $loadBalancer = $loadBalancerService->loadBalancer(); + + $serverOneNode = $loadBalancer->node(); + $serverOneNode->address = $serverOne->addresses->private[0]->addr; + $serverOneNode->port = 8080; + $serverOneNode->condition = 'ENABLED'; + + $serverTwoNode = $loadBalancer->node(); + $serverTwoNode->address = $serverTwo->addresses->private[0]->addr; + $serverTwoNode->port = 8080; + $serverTwoNode->condition = 'ENABLED'; + + $loadBalancer->addVirtualIp('PUBLIC'); + $loadBalancer->create(array( + 'name' => 'My smart load balancer', + 'port' => 80, + 'protocol' => 'HTTP', + 'nodes' => array($serverOneNode, $serverTwoNode) + )); + +List Load Balancer Details +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can retrieve a single load balancer's details by using its ID. + +.. code:: php + + $loadBalancer = $loadBalancerService->loadBalancer('254889'); + + /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ + +List Load Balancers +~~~~~~~~~~~~~~~~~~~ + +You can retrieve a list of all your load balancers. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $loadBalancers = $loadBalancerService->loadBalancerList(); + foreach ($loadBalancers as $loadBalancer) { + /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ + } + +Update Load Balancer Attributes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can update one or more of the following load balancer attributes: + +- ``name``: The name of the load balancer +- ``algorithm``: The algorithm used by the load balancer to distribute + traffic amongst its nodes. See also: `Load balancing + algorithms <#algorithms>`__. +- ``protocol``: The network protocol used by traffic coming in to the + load balancer. See also: `Protocols <#protocols>`__. +- ``port``: The network port on which the load balancer listens for + incoming traffic. +- ``halfClosed``: Enable or Disable Half-Closed support for the load + balancer. +- ``timeout``: The timeout value for the load balancer to communicate + with its nodes. +- ``httpsRedirect``: Enable or disable HTTP to HTTPS redirection for + the load balancer. When enabled, any HTTP request will return status + code 301 (Moved Permanently), and the requestor will be redirected to + the requested URL via the HTTPS protocol on port 443. For example, + http://example.com/page.html would be redirected to https:// + example.com/page.html. Only available for HTTPS protocol (``port`` = + 443), or HTTP Protocol with a properly configured SSL Termination + (\`secureTrafficOnly=true, securePort=443). See also: `SSL + Termination <#ssl-termination>`__. + +Updating a single attribute of a load balancer +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + $loadBalancer->update(array( + 'name' => 'New name' + )); + +Updating multiple attributes of a load balancer +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + $loadBalancer->update(array( + 'name' => 'New name', + 'algorithm' => 'ROUND_ROBIN' + )); + +Remove Load Balancer +~~~~~~~~~~~~~~~~~~~~ + +When you no longer have a need for the load balancer, you can remove it. + +.. code:: php + + $loadBalancer->delete(); + +Nodes +----- + +A **node** is a backend device that provides a service on specified IP +and port. An example of a load balancer node might be a web server +serving HTTP traffic on port 8080. + +A load balancer typically has multiple nodes attached to it so it can +distribute incoming network traffic amongst them. + +List Nodes +~~~~~~~~~~ + +You can list the nodes attached to a load balancer. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $nodes = $loadBalancer->nodeList(); + foreach ($nodes as $node) { + /** @var $node OpenCloud\LoadBalancer\Resource\Node **/ + } + +Add Nodes +~~~~~~~~~ + +You can attach additional nodes to a load balancer. Assume +``$loadBalancer`` already has two nodes attached to it - ``$serverOne`` +and ``$serverTwo`` - and you want to attach a third node to it, say +``$serverThree``, which provides a service on port 8080. + +**Important:** Remember to call ``$loadBalancer->addNodes()`` after all +the calls to ``$loadBalancer->addNode()`` as shown below. + +.. code:: php + + $address = $serverThree->addresses->private[0]->addr; + $loadBalancer->addNode($address, 8080); + $loadBalancer->addNodes(); + +The ``addNode`` method accepts three more optional parameters, in +addition to the two shown above: + +| Position \| Description \| Data type \| Required? \| Default value \| +| ----------- \| --------------- \| --------------\| -------------- \| +----------------- \| +|  1 \| IP address of node \| String \| Yes \| - \| +|  2 \| Port used by node's service \| Integer \| Yes \| - \| +|  3 \| Starting condition of node: +|  4 \| Type of node to add: +|  5 \| Weight, between 1 and 100, given to node when distributing +traffic using either the ``WEIGHTED_ROUND_ROBIN`` or the +``WEIGHTED_LEAST_CONNECTIONS`` load balancing algorithm. \| Integer \| +No \| 1 \| + +Modify Nodes +~~~~~~~~~~~~ + +You can modify one or more of the following node attributes: + +- ``condition``: The condition of the load balancer: + + - ``ENABLED`` – Node is ready to receive traffic from the load + balancer. + - ``DISABLED`` – Node should not receive traffic from the load + balancer. + - ``DRAINING`` – Node should process any traffic it is already + receiving but should not receive any further traffic from the load + balancer. + +- ``type``: The type of the node: + + - ``PRIMARY`` – Nodes defined as PRIMARY are in the normal rotation + to receive traffic from the load balancer. + - ``SECONDARY`` – Nodes defined as SECONDARY are only in the + rotation to receive traffic from the load balancer when all the + primary nodes fail. + +- ``weight``: The weight, between 1 and 100, given to node when + distributing traffic using either the ``WEIGHTED_ROUND_ROBIN`` or the + ``WEIGHTED_LEAST_CONNECTIONS`` load balancing algorithm. + +Modifying a single attribute of a node +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + use OpenCloud\LoadBalancer\Enum\NodeCondition; + + $node->update(array( + 'condition' => NodeCondition::DISABLED + )); + +Modifying multiple attributes of a node +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + use OpenCloud\LoadBalancer\Enum\NodeCondition; + use OpenCloud\LoadBalancer\Enum\NodeType; + + $node->update(array( + 'condition' => NodeCondition::DISABLED, + 'type' => NodeType::SECONDARY + )); + +Remove Nodes +~~~~~~~~~~~~ + +There are two ways to remove a node. + +Given an ``OpenCloud\LoadBalancer\Resource\Node`` instance +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + $node->delete(); + +Given an ``OpenCloud\LoadBalancer\Resource\LoadBalancer`` instance and a node ID +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: php + + $loadBalancer->removeNode(490639); + +The ``removeNode`` method, as shown above, accepts the following +arguments: + ++------------+---------------+-------------+-------------+-----------------+ +| Position | Description | Data type | Required? | Default value | ++============+===============+=============+=============+=================+ +| 1 | ID of node | Integer | Yes | - | ++------------+---------------+-------------+-------------+-----------------+ + +View Node Service Events +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can view events associated with the activity between a node and a +load balancer. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $nodeEvents = $loadBalancer->nodeEventList(); + foreach ($nodeEvents as $nodeEvent) { + /** @var $nodeEvent OpenCloud\LoadBalancer\Resource\NodeEvent **/ + } + +Virtual IPs +----------- + +A **virtual IP (VIP)** makes a load balancer accessible by clients. The +load balancing service supports either a public VIP address +(``PUBLIC``), routable on the public Internet, or a ServiceNet VIP +address (``SERVICENET``), routable only within the region in which the +load balancer resides. + +List Virtual IPs +~~~~~~~~~~~~~~~~ + +You can list the VIPs associated with a load balancer. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $vips = $loadBalancer->virtualIpList(); + foreach ($vips as $vip) { + /** @var $vip of OpenCloud\LoadBalancer\Resource\VirtualIp **/ + } + +Add Virtual IPv6 +~~~~~~~~~~~~~~~~ + +You can add additional IPv6 VIPs to a load balancer. + +.. code:: php + + use OpenCloud\LoadBalancer\Enum\IpType; + + $loadBalancer->addVirtualIp(IpType::PUBLIC, 6); + +The ``addVirtualIp`` method, as shown above, accepts the following +arguments: + +| Position \| Description \| Data type \| Required? \| Default value \| +| ----------- \| --------------- \| -------------- \|-------------- \| +----------------- \| +|  1 \| Type of VIP: +|  2 \| IP version: Must be ``6`` \| Integer \| Yes \| - \| + +Remove Virtual IPs +~~~~~~~~~~~~~~~~~~ + +You can remove a VIP from a load balancer. + +.. code:: php + + $vip->remove(); + +Please note that a load balancer must have at least one VIP associated +with it. If you try to remove a load balancer's last VIP, a +``ClientErrorResponseException`` will be thrown. + +Algorithms +---------- + +Load balancers use an **algorithm** to determine how incoming traffic is +distributed amongst the back-end nodes. + +List Load Balancing Algorithms +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can list all supported load balancing algorithms using a load +balancer service object. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $algorithms = $loadBalancerService->algorithmList(); + foreach ($algorithms as $algorithm) { + /** @var $algorithm OpenCloud\LoadBalancer\Resource\Algorithm **/ + } + +Protocols +--------- + +When a load balancer is created a network protocol must be specified. +This network protocol should be based on the network protocol of the +back-end service being load balanced. + +List Load Balancing Protocols +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can list all supported network protocols using a load balancer +service object. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $protocols = $loadBalancerService->protocolList(); + foreach ($protocols as $protocol) { + /** @var $protocol OpenCloud\LoadBalancer\Resource\Protocol **/ + } + +Session Persistence +------------------- + +**Session persistence** is a feature of the load balancing service that +forces multiple requests, of the same protocol, from clients to be +directed to the same node. This is common with many web applications +that do not inherently share application state between back-end servers. + +There are two types (or modes) of session persistence: + ++-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Name | Description | ++===================+===================================================================================================================================================================================================================================+ +| ``HTTP_COOKIE`` | A session persistence mechanism that inserts an HTTP cookie and is used to determine the destination back-end node. This is supported for HTTP load balancing only. | ++-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SOURCE_IP`` | A session persistence mechanism that will keep track of the source IP address that is mapped and is able to determine the destination back-end node. This is supported for HTTPS pass-through and non-HTTP load balancing only. | ++-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +List Session Persistence Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $sessionPersistence = $loadBalancer->sessionPersistence(); + $sessionPersistenceType = $sessionPersistence->persistenceType; + + /** @var $sessionPersistenceType null | 'HTTP_COOKIE' | 'SOURCE_IP' **/ + +In the example above: + +- If session persistence is enabled, the value of + ``$sessionPersistenceType`` is the type of session persistence: + either ``HTTP_COOKIE`` or ``SOURCE_IP``. +- If session persistence is disabled, the value of + ``$sessionPersistenceType`` is ``null``. + +Enable Session Persistence +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $sessionPersistence = $loadBalancer->sessionPersistence(); + $sessionPersistence->update(array( + 'persistenceType' => 'HTTP_COOKIE' + )); + +Disable Session Persistence +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $sessionPersistence = $loadBalancer->sessionPersistence(); + $sessionPersistence->delete(); + +Connection Logging +------------------ + +The **connection logging** feature allows logs to be delivered to a +Cloud Files account every hour. For HTTP-based protocol traffic, these +are Apache-style access logs. For all other traffic, this is connection +and transfer logging. + +Check Logging Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + /** @var $connectionLogging bool **/ + + $connectionLogging = $loadBalancer->hasConnectionLogging(); + +In the example above: + +- If connection logging is enabled, the value of ``$connectionLogging`` + is ``true``. +- If connection logging is disabled, the value of + ``$connectionLogging`` is ``false``. + +Enable Connection Logging +~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $loadBalancer->enableConnectionLogging(true); + +Disable Connection Logging +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $loadBalancer->enableConnectionLogging(false); + +Error Page +---------- + +An **error page** is the html file that is shown to the end user when an +error in the service has been thrown. By default every virtual server is +provided with the default error file. It is also possible to set a +custom error page for a load balancer. + +View Error Page Content +~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $errorPage = $loadBalancer->errorPage(); + $errorPageContent = $errorPage->content; + + /** @var $errorPageContent string **/ + +In the example above the value of ``$errorPageContent`` is the HTML for +that page. This could either be the HTML of the default error page or of +your custom error page. + +Set Custom Error Page +~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $errorPage = $loadBalancer->errorPage(); + $errorPage->update(array( + 'content' => '' + )); + +Delete Custom Error Page +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $errorPage = $loadBalancer->errorPage(); + $errorPage->delete(); + +Allowed Domains +--------------- + +**Allowed domains** are a restricted set of domain names that are +allowed to add load balancer nodes. + +List Allowed Domains +~~~~~~~~~~~~~~~~~~~~ + +You can list all allowed domains using a load balancer service object. +An instance of ``OpenCloud\Common\Collection\PaginatedIterator`` is +returned. + +.. code:: php + + $allowedDomains = $loadBalancerService->allowedDomainList(); + foreach ($allowedDomains as $allowedDomain) { + /** @var $allowedDomain OpenCloud\LoadBalancer\Resource\AllowedDomain **/ + } + +Access Lists +------------ + +**Access Lists** allow fine-grained network access to a load balancer's +VIP. Using access lists, network traffic to a load balancer's VIP can be +allowed or denied from a single IP address, multiple IP addresses or +entire network subnets. + +Note that ``ALLOW`` network items will take precedence over ``DENY`` +network items in an access list. + +To reject traffic from all network items except those with the ``ALLOW`` +type, add a ``DENY`` network item with the address of ``0.0.0.0/0``. + +View Access List +~~~~~~~~~~~~~~~~ + +You can view a load balancer's access list. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $accessList = $loadBalancer->accessList(); + foreach ($accessList as $networkItem) { + /** @var $networkItem OpenCloud\LoadBalancer\Resource\Access **/ + } + +Add Network Items To Access List +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can add network items to a load balancer's access list very easily: + +.. code:: php + + $loadBalancer->createAccessList(array( + (object) array( + 'type' => 'ALLOW', + 'address' => '206.160.165.1/24' + ), + (object) array( + 'type' => 'DENY', + 'address' => '0.0.0.0/0' + ) + )); + +In the above example, we allowed access for 1 IP address, and used the +"0.0.0.0" wildcard to blacklist all other traffic. + +Remove Network Item From Access List +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You an remove a network item from a load balancer's access list. + +.. code:: php + + $networkItem->delete(); + +Content Caching +--------------- + +When **content caching** is enabled on a load balancer, +recently-accessed files are stored on the load balancer for easy +retrieval by web clients. Requests to the load balancer for these files +are serviced by the load balancer itself, which reduces load off its +back-end nodes and improves response times as well. + +Check Content Caching Configuration +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + /** @var $contentCaching bool **/ + + $contentCaching = $loadBalancer->hasContentCaching(); + +In the example above: + +- If content caching is enabled, the value of ``$contentCaching`` is + ``true``. +- If content caching is disabled, the value of ``$contentCaching`` is + ``false``. + +Enable Content Caching +~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $loadBalancer->enableContentCaching(true); + +Disable Content Caching +~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $loadBalancer->enableContentCaching(false); + +SSL Termination +--------------- + +The SSL Termination feature allows a load balancer user to terminate SSL +traffic at the load balancer layer versus at the web server layer. A +user may choose to configure SSL Termination using a key and an SSL +certificate or an (Intermediate) SSL certificate. + +When SSL Termination is configured on a load balancer, a secure shadow +server is created that listens only for secure traffic on a +user-specified port. This shadow server is only visible to and +manageable by the system. Existing or updated attributes on a load +balancer with SSL Termination will also apply to its shadow server. For +example, if Connection Logging is enabled on an SSL load balancer, it +will also be enabled on the shadow server and Cloud Files logs will +contain log files for both. + +View current SSL termination config +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + /** @var $sslConfig OpenCloud\LoadBalancer\Resource\SSLTermination **/ + + $sslConfig = $loadBalancer->SSLTermination(); + +Update SSL termination config +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $sslConfig->update(array( + 'enabled' => true, + 'securePort' => 443, + 'privateKey' => $key, + 'certificate' => $cert + )); + +For a full list, with explanations, of required and optional attributes, +please consult the `official +documentation `__ + +Delete SSL termination config +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $sslConfig->delete(); + +Metadata +-------- + +Metadata can be associated with each load balancer and each node for the +client's personal use. It is defined using key-value pairs where the key +and value consist of alphanumeric characters. A key is unique per load +balancer. + +List metadata +~~~~~~~~~~~~~ + +.. code:: php + + $metadataList = $loadBalancer->metadataList(); + + foreach ($metadataList as $metadataItem) { + printf("Key: %s, Value: %s", $metadataItem->key, $metadataItem->value); + } + +Please consult the `iterator +documentation `__ for more information +about iterators. + +Add metadata +~~~~~~~~~~~~ + +.. code:: php + + $metadataItem = $loadBalancer->metadata(); + $metadataItem->create(array( + 'key' => 'foo', + 'value' => 'bar' + )); + +Modify metadata +~~~~~~~~~~~~~~~ + +.. code:: php + + $metadataItem = $loadBalancer->metadata('foo'); + $metadataItem->update(array( + 'value' => 'baz' + )); + +Remove metadata +~~~~~~~~~~~~~~~ + +.. code:: php + + $metadataItem->delete(); + +Monitors +-------- + +The load balancing service includes a health monitoring operation which +periodically checks your back-end nodes to ensure they are responding +correctly. If a node is not responding, it is removed from rotation +until the health monitor determines that the node is functional. In +addition to being performed periodically, the health check also is +performed against every node that is added to ensure that the node is +operating properly before allowing it to service traffic. Only one +health monitor is allowed to be enabled on a load balancer at a time. + +.. code:: php + + /** @var $healthMonitor OpenCloud\LoadBalancer\Resource\HealthMonitor **/ + + $healthMonitor = $loadBalancer->healthMonitor(); + + printf( + "Monitoring type: %s, delay: %s, timeout: %s, attempts before deactivation: %s", + $healthMonitor->type, $healthMonitor->delay, $healthMonitor->timeout + ); + +For a full list, with explanations, of required and optional attributes, +please consult the `official +documentation `__ + +Update or delete +~~~~~~~~~~~~~~~~ + +.. code:: php + + // Update + $healthMonitor->update(array( + 'delay' => 120, + 'timeout' => 60, + 'type' => 'CONNECT' + 'attemptsBeforeDeactivation' => 3 + )); + + // Delete + $healthMonitor->delete(); + +Statistics +---------- + +You can retrieve detailed stats about your load balancer, including the +following information: + +- ``connectTimeOut`` – Connections closed by this load balancer because + the 'connect\_timeout' interval was exceeded. +- ``connectError`` – Number of transaction or protocol errors in this + load balancer. +- ``connectFailure`` – Number of connection failures in this load + balancer. +- ``dataTimedOut`` – Connections closed by this load balancer because + the 'timeout' interval was exceeded. +- ``keepAliveTimedOut`` – Connections closed by this load balancer + because the 'keepalive\_timeout' interval was exceeded. +- ``maxConn`` – Maximum number of simultaneous TCP connections this + load balancer has processed at any one time. + +.. code:: php + + /** @var $stats OpenCloud\LoadBalancer\Resource\Stats **/ + + $stats = $loadBalancer->stats(); + +Usage Reports +------------- + +The load balancer usage reports provide a view of all transfer activity, +average number of connections, and number of virtual IPs associated with +the load balancing service. Current usage represents all usage recorded +within the preceding 24 hours. Values for both incomingTransfer and +outgoingTransfer are expressed in bytes transferred. + +The optional startTime and endTime parameters can be used to filter all +usage. If the startTime parameter is supplied but the endTime parameter +is not, then all usage beginning with the startTime will be provided. +Likewise, if the endTime parameter is supplied but the startTime +parameter is not, then all usage will be returned up to the endTime +specified. + +.. code:: php + + # View billable LBs + $billable = $service->billableLoadBalancerList(); + + foreach ($billable as $loadBalancer) { + /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ + + # View usage + /** @var $usage OpenCloud\LoadBalancer\Resource\UsageRecord **/ + $usage = $loadBalancer->usage(); + + echo $usage->averageNumConnections, PHP_EOL; + } + diff --git a/doc/services/load-balancer/index.rst b/doc/services/load-balancer/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/monitoring/Agents.md.rst b/doc/services/monitoring/Agents.md.rst new file mode 100644 index 000000000..943983f7e --- /dev/null +++ b/doc/services/monitoring/Agents.md.rst @@ -0,0 +1,202 @@ +Agents +====== + +Intro +----- + +The Monitoring Agent resides on the host server being monitored. The +agent allows you to gather on-host metrics based on agent checks and +push them to Cloud Monitoring where you can analyze them, use them with +the Cloud Monitoring infrastructure (such as alarms), and archive them. + +For more information about this feature, including a brief overview of +its core design principles and security layers, see the `official API +documentation `__. + +Setup +----- + +.. code:: php + + $agentId = '00-agent.example.com'; + $agent = $service->getAgent($agentId); + +You can view the `service page `__ for more information +about setting up the Cloud Monitoring service. + +List agents +----------- + +.. code:: php + + $agents = $service->getAgents(); + + foreach ($agents as $agent) { + echo $agent->getLastConnected(); + } + +Please consult the `iterator doc `__ for +more information about iterators. + +List connections +---------------- + +.. code:: php + + $connections = $agent->getConnections(); + +Please consult the `iterator doc `__ for +more information about iterators. + +Get connection +-------------- + +.. code:: php + + /** @var \OpenCloud\CloudMonitoring\Resource\AgentConnection */ + $connection = $agent->getConnection('cntl4qsIbA'); + +Agent Connection properties +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ++--------------------+---------------+--------+---------------------------+ +| Name | Description | Type | Method | ++====================+===============+========+===========================+ +| id | - | - | ``getId()`` | ++--------------------+---------------+--------+---------------------------+ +| guid | - | - | ``getGuid()`` | ++--------------------+---------------+--------+---------------------------+ +| agent\_id | - | - | ``getAgentId()`` | ++--------------------+---------------+--------+---------------------------+ +| endpoint | - | - | ``getEndpoint()`` | ++--------------------+---------------+--------+---------------------------+ +| process\_version | - | - | ``getProcessVersion()`` | ++--------------------+---------------+--------+---------------------------+ +| bundle\_version | - | - | ``getBundleVersion()`` | ++--------------------+---------------+--------+---------------------------+ +| agent\_ip | - | - | ``getAgentIp()`` | ++--------------------+---------------+--------+---------------------------+ + +Agent tokens +============ + +Intro +----- + +Agent tokens are used to authenticate Monitoring agents to the +Monitoring Service. Multiple agents can share a single token. + +Setup +----- + +.. code:: php + + $tokenId = '4c5e28f0-0b3f-11e1-860d-c55c4705a286:1234'; + $agentToken = $service->getAgentToken($tokenId); + +Create agent token +------------------ + +.. code:: php + + $newToken = $service->getAgentToken(); + $newToken->create(array('label' => 'Foobar')); + +List agent tokens +----------------- + +.. code:: php + + $agentTokens = $service->getAgentTokens(); + + foreach ($agentTokens as $token) { + echo $token->getLabel(); + } + +Please consult the `iterator doc `__ for +more information about iterators. + +Update and delete Agent Token +----------------------------- + +.. code:: php + + // Update + $token->update(array( + 'label' => 'New label' + )); + + // Delete + $token->delete(); + +Agent Host Information +====================== + +Info +---- + +An agent can gather host information, such as process lists, network +configuration, and memory usage, on demand. You can use the +host-information API requests to gather this information for use in +dashboards or other utilities. + +Setup +----- + +.. code:: php + + $host = $monitoringService->getAgentHost(); + +Get some metrics +---------------- + +.. code:: php + + $cpuInfo = $host->info('cpus'); + $diskInfo = $host->info('disks'); + $filesystemInfo = $host->info('filesystems'); + $memoryInfo = $host->info('memory'); + $networkIntInfo = $host->info('network_interfaces'); + $processesInfo = $host->info('processes'); + $systemInfo = $host->info('system'); + $userInfo = $host->info('who'); + + // What CPU models do we have? + foreach ($cpuInfo as $cpuMetric) { + echo $cpuMetric->model, PHP_EOL; + } + + // How many disks do we have? + echo $diskInfo->count(); + + // What's the available space on our ext4 filesystem? + foreach ($filesystemInfo as $filesystemMetric) { + if ($filesystemMetric->sys_type_name == 'ext4') { + echo $filesystemMetric->avail; + } + } + +Agent targets +============= + +Info +---- + +Each agent check type gathers data for a related set of target devices +on the server where the agent is installed. For example, +``agent.network`` gathers data for network devices. The actual list of +target devices is specific to the configuration of the host server. By +focusing on specific targets, you can efficiently narrow the metric data +that the agent gathers. + +List agent targets +~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $targets = $service->getAgentTargets(); + + foreach ($targets as $target) { + echo $target->getType(); + } + diff --git a/doc/services/monitoring/Alarms.md.rst b/doc/services/monitoring/Alarms.md.rst new file mode 100644 index 000000000..2918637e9 --- /dev/null +++ b/doc/services/monitoring/Alarms.md.rst @@ -0,0 +1,81 @@ +Alarms +====== + +Info +---- + +Alarms bind alerting rules, entities, and notification plans into a +logical unit. Alarms are responsible for determining a state (``OK``, +``WARNING`` or ``CRITICAL``) based on the result of a Check, and +executing a notification plan whenever that state changes. You create +alerting rules by using the alarm DSL. For information about using the +alarm language, refer to the `reference +documentation `__. + +Setup +----- + +Alarms are sub-resources of Entities: + +.. code:: php + + $alarmId = 'alAAAA'; + $alarm = $check->getAlarm(); + +For more information about working with Checks, please see the +`appropriate documentation `__. + +Attributes +---------- + ++--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ +| Name | Description | Required? | Method | ++==========================+=============================================================================+=============+=================================+ +| check\_id | The ID of the check to alert on. | Required | ``getCheckId()`` | ++--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ +| notification\_plan\_id | The ID of the notification plan to execute when the state changes. | Optional | ``getNotificationPlanId()`` | ++--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ +| criteria | The alarm DSL for describing alerting conditions and their output states. | Optional | ``getCriteria()`` | ++--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ +| disabled | Disable processing and alerts on this alarm | Optional | ``isDisabled()`` <``bool``\ > | ++--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ +| label | A friendly label for an alarm. | Optional | ``getLabel()`` | ++--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ +| metadata | Arbitrary key/value pairs. | Optional | ``getMetadata()`` | ++--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ + +Create Alarm +------------ + +.. code:: php + + $alarm->create(array( + 'check_id' => 'chAAAA', + 'criteria' => 'if (metric["duration"] >= 2) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);', + 'notification_plan_id' => 'npAAAAA' + )); + +List Alarms +----------- + +.. code:: php + + $alarms = $entity->getAlarms(); + + foreach ($alarms as $alarm) { + echo $alarm->getId(); + } + +Update and delete Alarm +----------------------- + +.. code:: php + + // Update + $alarm->update(array( + 'criteria' => 'if (metric["duration"] >= 5) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);' + )); + + // Delete + $alarm->delete(); + diff --git a/doc/services/monitoring/Changelogs.md.rst b/doc/services/monitoring/Changelogs.md.rst new file mode 100644 index 000000000..2e9059e26 --- /dev/null +++ b/doc/services/monitoring/Changelogs.md.rst @@ -0,0 +1,21 @@ +Changelogs +========== + +Info +---- + +The monitoring service records changelogs for alarm statuses. Changelogs +are accessible as a Time Series Collection. By default the API queries +the last 7 days of changelog information. + +Working with Changelogs +----------------------- + +.. code:: php + + $changelog = $service->getChangelog(); + + foreach ($changelog as $item) { + $entity = $item->getEntityId(); + } + diff --git a/doc/services/monitoring/Checks.md.rst b/doc/services/monitoring/Checks.md.rst new file mode 100644 index 000000000..0e8e902a5 --- /dev/null +++ b/doc/services/monitoring/Checks.md.rst @@ -0,0 +1,211 @@ +Checks +====== + +Info +---- + +A check is one of the foundational building blocks of the monitoring +system. The check determines the parts or pieces of the entity that you +want to monitor, the monitoring frequency, how many monitoring zones are +originating the check, and so on. When you create a new check in the +monitoring system, you specify the following information: + +- A name for the check +- The check's parent entity +- The type of check you're creating +- Details of the check +- The monitoring zones that will launch the check + +The check, as created, will not trigger alert messages until you create +an alarm to generate notifications, to enable the creation of a single +alarm that acts upon multiple checks (e.g. alert if any of ten different +servers stops responding) or multiple alarms off of a single check. +(e.g. ensure both that a HTTPS server is responding and that it has a +valid certificate). + +Setup +----- + +Checks are sub-resources of Entities: + +.. code:: php + + $checkId = 'chAAAA'; + $check = $entity->getCheck($checkId); + +Attributes +---------- + ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ +| Name | Description | Required? | Data type | ++============+=============================================================================================================+=============+==========================================+ +| type | The type of check. | Required | Valid check type. String (1..25 chars) | ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ +| details | Details specific to the check type. | Optional | Array | ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ +| disabled | Disables the check. | Optional | Boolean | ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ +| label | A friendly label for a check. | Optional | String (1..255 chars) | ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ +| metadata | Arbitrary key/value pairs. | Optional | Array | ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ +| period | The period in seconds for a check. The value must be greater than the minimum period set on your account. | Optional | Integer (30..1800) | ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ +| timeout | The timeout in seconds for a check. This has to be less than the period. | Optional | Integer (2..1800) | ++------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ + +Attributes used for remote Checks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ++---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ +| Name | Description | Required? | Data type | ++===========================+========================================================================================================================================================+=============+============================================================+ +| monitoring\_zones\_poll | List of monitoring zones to poll from. Note: This argument is only required for remote (non-agent) checks | Optional | Array | ++---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ +| target\_alias | A key in the entity's ``ip_addresses`` hash used to resolve this check to an IP address. This parameter is mutually exclusive with target\_hostname. | Optional | String (1..64 chars) | ++---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ +| target\_hostname | The hostname this check should target. This parameter is mutually exclusive with ``target_alias``. | Optional | Valid FQDN, IPv4 or IPv6 address. String (1..256 chars). | ++---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ +| target\_resolver | Determines how to resolve the check target. | Optional | ``IPv4`` or ``IPv6`` | ++---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ + +Test parameters (before create) +------------------------------- + +.. code:: php + + $params = array( + 'type' => 'remote.http', + 'details' => array( + 'url' => 'http://example.com', + 'method' => 'GET' + ), + 'monitoring_zones_poll' => array('mzlon'), + 'period' => '100', + 'timeout' => '30', + 'target_alias' => 'default', + 'label' => 'Website check 1' + ); + + // You can do a test to see what would happen + // if a Check is launched with these params + $response = $entity->testNewCheckParams($params); + + echo $response->timestamp; // When was it executed? + echo $response->available; // Was it available? + echo $response->status; // Status code + +Create a Check +-------------- + +.. code:: php + + $entity->createCheck($params); + +Test existing Check +------------------- + +.. code:: php + + // Set arg to TRUE for debug information + $response = $check->test(true); + + echo $response->debug_info; + +List Checks +----------- + +.. code:: php + + $checks = $entity->getChecks(); + + foreach ($checks as $check) { + echo $check->getId(); + } + +Update and delete Check +~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + // Update + $check->update(array('period' => 500)); + + // Delete + $check->delete(); + +Check types +=========== + +Info +---- + +Each check within the Rackspace Cloud Monitoring has a designated check +type. The check type instructs the monitoring system how to check the +monitored resource. **Note:** Users cannot create, update or delete +check types. + +Check types for commonly encountered web protocols, such as HTTP +(``remote.http``), IMAP (``remote.imap-banner``) , SMTP +(``remote.stmp``), and DNS (``remote.dns``) are provided. Monitoring +commonly encountered infrastructure servers like MySQL +(``remote.mysql-banner``) and PostgreSQL (``remote.postgresql-banner``) +are also available. Monitoring custom server uptime can be accomplished +with the remote.tcp banner check to check for a protocol-defined banner +at the beginning of a connection. Gathering metrics from server software +to create alerts against can be accomplished using the remote.http check +type and the 'extract' attribute to define the format. + +In addition to the standard Cloud Monitoring check types, you can also +use agent check types if the Monitoring Agent is installed on the server +you are monitoring. For a list of available check types, see the +`official API +documentation `__. + +Checks generate metrics that alarms will alert based upon. The metrics +generated often times depend on the check's parameters. For example, +using the 'extract' attribute on the remote.http check, however the +default metrics will always be present. To determine the exact metrics +available, the Test Check API is provided. + +Setup +----- + +If you want to see the type for an existing Check: + +.. code:: php + + /** @var \OpenCloud\CloudMonitoring\Resource\CheckType */ + $checkType = $check->getCheckType(); + +Alternatively, you can retrieve a specific type based on its ID: + +.. code:: php + + $checkTypeId = 'remote.dns'; + $checkType = $service->getCheckType($checkTypeId); + +Attributes +---------- + ++------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ +| Name | Description | Data type | Method | ++========================+==========================================================================================================================================================================================+=============+===============================+ +| type | The name of the supported check type. | String | ``getType()`` | ++------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ +| fields | Check type fields. | Array | ``getFields()`` | ++------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ +| supported\_platforms | Platforms on which an agent check type is supported. This is advisory information only - the check may still work on other platforms, or report that check execution failed at runtime | Array | ``getSupportedPlatforms()`` | ++------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ + +List all possible check types +----------------------------- + +.. code:: php + + $checkTypes = $service->getCheckTypes(); + + foreach ($checkTypes as $checkType) { + echo $checkType->getId(); + } + diff --git a/doc/services/monitoring/Entities.md.rst b/doc/services/monitoring/Entities.md.rst new file mode 100644 index 000000000..068aec122 --- /dev/null +++ b/doc/services/monitoring/Entities.md.rst @@ -0,0 +1,77 @@ + Entities +========= + +Info +---- + +An entity is the target of what you are monitoring. For example, you can +create an entity to monitor your website, a particular web service, or +your Rackspace server. Note that an entity represents only one item in +the monitoring system -- if you wanted to monitor each server in a +cluster, you would create an entity for each of the servers. You would +not create a single entity to represent the entire cluster. + +An entity can have multiple checks associated with it. This allows you +to check multiple services on the same host by creating multiple checks +on the same entity, instead of multiple entities each with a single +check. + +Setup +----- + +.. code:: php + + $entity = $service->getEntity(); + +For more information about setting up the ``$service`` object, please +see the userguide tutorial for `services `__. + +Attributes +---------- + ++-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ +| Name | Description | Required? | Data type | Method | ++=================+=========================================================================+=============+=====================================================+========================+ +| label | Defines a name for the entity. | Required | String (1..255 chars) | ``getLabel()`` | ++-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ +| agent\_id | Agent to which this entity is bound to. | Optional | String matching the regex: ``/^[-\.\w]{1,255}$/`` | ``getAgentId()`` | ++-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ +| ip\_addresses | Hash of IP addresses that can be referenced by checks on this entity. | Optional | Array | ``getIpAddresses()`` | ++-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ +| metadata | Arbitrary key/value pairs that are passed during the alerting phase. | Optional | ``OpenCloud\Common\Metadata`` | ``getMetadata()`` | ++-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ + +Create Entity +------------- + +.. code:: php + + $service->createEntity(array( + 'label' => 'Brand New Entity', + 'ip_addresses' => array( + 'default' => '127.0.0.4', + 'b' => '127.0.0.5', + 'c' => '127.0.0.6', + 'test' => '127.0.0.7' + ), + 'metadata' => array( + 'all' => 'kinds', + 'of' => 'stuff', + 'can' => 'go', + 'here' => 'null is not a valid value' + ) + )); + +Update and delete Entity +------------------------ + +.. code:: php + + // Update + $entity->update(array( + 'label' => 'New label for my entity' + )); + + // Delete + $entity->delete(); + diff --git a/doc/services/monitoring/Metrics.md.rst b/doc/services/monitoring/Metrics.md.rst new file mode 100644 index 000000000..4231cf914 --- /dev/null +++ b/doc/services/monitoring/Metrics.md.rst @@ -0,0 +1,131 @@ + Metrics +======== + +Info +---- + +When Monitoring checks run, they generate metrics. These metrics are +stored as full resolution data points in the Cloud Monitoring system. +Full resolution data points are periodically rolled up (condensed) into +coarser data points. + +Depending on your needs, you can use the metrics API to fetch individual +data points (fine-grained) or rolled up data points (coarse-grained) +over a period of time. + +Data Granularity +---------------- + +Cloud Monitoring supports several granularities of data: full resolution +data and rollups computed at 5, 20, 60, 240 and 1440 minute intervals. + +When you fetch metrics data points, you specify several parameters to +control the granularity of data returned: + +- A time range for the points +- Either the number of points you want returned OR the resolution of + the data you want returned + +When you query by points, the API selects the resolution that will +return you the number of points you requested. The API makes the +assumption of a 30 second frequency, performs the calculation, and +selects the appropriate resolution. + +**Note:** Because the API performs calculations to determine the points +returned for a particular resolution, the number of points returned may +differ from the specific number of points you request. + +Consider that you want to query data for a 48-hour time range between +the timestamps ``from=1354647221000`` and ``to=1358794421000`` ( +**specified in Unix time, based on the number of milliseconds that have +elapsed since January 1, 1970** ). The following table shows the number +of points that the API returns for a given resolution. + +Specifying resolution to retrieve data in 48 hour period +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ++-----------------------------+-------------------------+ +| You specify resolution... | API returns points... | ++=============================+=========================+ +| FULL | 5760 | ++-----------------------------+-------------------------+ +| MIN5 | 576 | ++-----------------------------+-------------------------+ +| MIN20 | 144 | ++-----------------------------+-------------------------+ +| MIN60 | 48 | ++-----------------------------+-------------------------+ +| MIN240 | 12 | ++-----------------------------+-------------------------+ +| MIN1440 | 2 | ++-----------------------------+-------------------------+ + +Specifying number of points to retrieve data in 48 hour period +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + ++--------------------------------------+-----------------------------+ +| You specify points in the range... | API calculates resolution | ++======================================+=============================+ +| 3168-∞ | FULL | ++--------------------------------------+-----------------------------+ +| 360-3167 | MIN5 | ++--------------------------------------+-----------------------------+ +| 96-359 | MIN20 | ++--------------------------------------+-----------------------------+ +| 30-95 | MIN60 | ++--------------------------------------+-----------------------------+ +| 7-29 | MIN240 | ++--------------------------------------+-----------------------------+ +| 0-6 | MIN1440 | ++--------------------------------------+-----------------------------+ + +Data Point Expiration +^^^^^^^^^^^^^^^^^^^^^ + +Cloud Monitoring expires data points according to the following +schedule: + ++--------------+--------------+ +| Resolution | Expiration | ++==============+==============+ +| FULL | 2 days | ++--------------+--------------+ +| MIN5 | 7 days | ++--------------+--------------+ +| MIN20 | 15 days | ++--------------+--------------+ +| MIN60 | 30 days | ++--------------+--------------+ +| MIN240 | 60 days | ++--------------+--------------+ +| MIN1440 | 365 days | ++--------------+--------------+ + + Setup +------ + +Metrics are sub-resources of Checks. For more information about working +with Checks, please see the `relevant documentation `__. + +List all metrics +---------------- + +.. code:: php + + $metrics = $check->getMetrics(); + + foreach ($metrics as $metric) { + echo $metric->getName(); + } + +Fetch data points +----------------- + +.. code:: php + + $data = $check->fetchDataPoints('mzdfw.available', array( + 'resolution' => 'FULL', + 'from' => 1369756378450, + 'to' => 1369760279018 + )); + diff --git a/doc/services/monitoring/Notifications.md.rst b/doc/services/monitoring/Notifications.md.rst new file mode 100644 index 000000000..f361e3c9c --- /dev/null +++ b/doc/services/monitoring/Notifications.md.rst @@ -0,0 +1,281 @@ +Notifications +============= + +Info +---- + +A notification is a destination to send an alarm; it can be a variety of +different types, and will evolve over time. + +For instance, with a webhook type notification, Cloud Monitoring posts +JSON formatted data to a user-specified URL on an alert condition (Check +goes from ``OK`` -> ``CRITICAL`` and so on). + +Setup +----- + +.. code:: php + + $id = 'ntAAAA'; + $notification = $service->getNotification($id); + +Attributes +---------- + ++-----------+---------------------------------------------------------------------------+-----------------------------------------------------------+--------------------+ +| Name | Description | Data type | Method | ++===========+===========================================================================+===========================================================+====================+ +| details | A hash of notification specific details based on the notification type. | Array | ``getDetails()`` | ++-----------+---------------------------------------------------------------------------+-----------------------------------------------------------+--------------------+ +| label | Friendly name for the notification. | String (1..255 chars) | ``getLabel()`` | ++-----------+---------------------------------------------------------------------------+-----------------------------------------------------------+--------------------+ +| type | The notification type to send. | String. Either ``webhook``, ``email``, or ``pagerduty`` | ``getType()`` | ++-----------+---------------------------------------------------------------------------+-----------------------------------------------------------+--------------------+ + +Test parameters +--------------- + +.. code:: php + + $params = array( + 'label' => 'My webhook #1', + 'type' => 'webhook', + 'details' => array( + 'url' => 'http://example.com' + ) + ); + + // Test it + $response = $notification->testParams($params); + + if ($response->status == 'Success') { + echo $response->message; + } + +Create Notification +------------------- + +.. code:: php + + $notification->create($params); + +Test existing notification +-------------------------- + +.. code:: php + + $response = $notification->testExisting(true); + echo $response->debug_info; + +List Notifications +------------------ + +.. code:: php + + $notifications = $service->getNotifications(); + + foreach ($notifications as $notification) { + echo $notification->getId(); + } + +Update and delete Notifications +------------------------------- + +.. code:: php + + // Update + $notification->update(array( + 'label' => 'New notification label' + )); + + // Delete + $notification->delete(); + +Notification types +================== + +Info +---- + +Pretty self-explanatory. Rackspace Cloud Monitoring currently supports +the following notification types: + +Webhook +^^^^^^^ + +Industry-standard web hooks, where JSON is posted to a configurable URL. +It has these attributes: + ++-----------+------------------------------------------+---------------+ +| Name | Description | Data type | ++===========+==========================================+===============+ +| address | Email address to send notifications to | Valid email | ++-----------+------------------------------------------+---------------+ + +Email +^^^^^ + +Email alerts where the message is delivered to a specified address. It +has these attributes: + ++--------+-----------------------------------+-------------+ +| Name | Description | Data type | ++========+===================================+=============+ +| url | An HTTP or HTTPS URL to POST to | Valid URL | ++--------+-----------------------------------+-------------+ + +Setup +----- + +If you've already set up a main Notification object, and want to access +functionality for this Notification's particular Notification Type, you +can access its property: + +.. code:: php + + $type = $notification->getNotificationType(); + +Alternatively, you can retrieve an independent resource using the ID: + +.. code:: php + + $typeId = 'pagerduty'; + $type = $service->getNotificationType($typeId); + +List all possible notification types +------------------------------------ + +.. code:: php + + $types = $service->getNotificationTypes(); + + foreach ($types as $type) { + echo sprintf('%s %s', $type->getName(), $type->getDescription()); + } + +Notification plans +================== + +Info +---- + +A notification plan contains a set of notification actions that +Rackspace Cloud Monitoring executes when triggered by an alarm. +Rackspace Cloud Monitoring currently supports webhook and email +notifications. + +Each notification state can contain multiple notification actions. For +example, you can create a notification plan that hits a webhook/email to +notify your operations team if a warning occurs. However, if the warning +escalates to an Error, the notification plan could be configured to hit +a different webhook/email that triggers both email and SMS messages to +the operations team. The notification plan supports the following +states: + +- Critical +- Warning +- OK + +A notification plan, ``npTechnicalContactsEmail``, is provided by +default which will email all of the technical contacts on file for an +account whenever there is a state change. + +Setup +----- + +.. code:: php + + $planId = 'npAAAA'; + $plan = $service->getNotificationPlan(); + +Attributes +---------- + ++-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ +| Name | Description | Required? | Data type | Method | ++===================+====================================================================+=============+=========================+==========================+ +| label | Friendly name for the notification plan. | Required | String (1..255 chars) | ``getLabel()`` | ++-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ +| critical\_state | The notification list to send to when the state is ``CRITICAL``. | Optional | Array | ``getCriticalState()`` | ++-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ +| ok\_state | The notification list to send to when the state is ``OK``. | Optional | Array | ``getOkState()`` | ++-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ +| warning\_state | The notification list to send to when the state is ``WARNING``. | Optional | Array | ``getWarningState()`` | ++-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ + +Create Notification Plan +------------------------ + +.. code:: php + + $plan->create(array( + 'label' => 'New Notification Plan', + 'critical_state' => array('ntAAAA'), + 'ok_state' => array('ntBBBB'), + 'warning_state' => array('ntCCCC') + )); + +Update and delete Notification Plan +----------------------------------- + +.. code:: php + + // Update + $plan->update(array( + 'label' => 'New label for my plan' + )); + + // Delete + $plan->delete(); + +Alarm Notification History +========================== + +Info +---- + +The monitoring service keeps a record of notifications sent for each +alarm. This history is further subdivided by the check on which the +notification occurred. Every attempt to send a notification is recorded, +making this history a valuable tool in diagnosing issues with unreceived +notifications, in addition to offering a means of viewing the history of +an alarm's statuses. + +Alarm notification history is accessible as a Time Series Collection. By +default alarm notification history is stored for 30 days and the API +queries the last 7 days of information. + + Setup +------ + +Notification History is a sub-resource of an Alarm. For more information +about working with Alarms, please consult the relevant +`documentation `__. + +Discover which Checks have a Notification History +------------------------------------------------- + +This operation list checks for which alarm notification history is +available: + +.. code:: php + + $checks = $alarm->getRecordedChecks(); + +List Alarm Notification History for a particular Check +------------------------------------------------------ + +.. code:: php + + $checkHistory = $alarm->getNotificationHistoryForCheck('chAAAA'); + +Get a particular Notification History item +------------------------------------------ + +.. code:: php + + $checkId = 'chAAAA'; + $itemUuid = '646ac7b0-0b34-11e1-a0a1-0ff89fa2fa26'; + + $singleItem = $history->getNotificationHistoryItem($checkId, $itemUuid); + diff --git a/doc/services/monitoring/Service.md.rst b/doc/services/monitoring/Service.md.rst new file mode 100644 index 000000000..09c25c21d --- /dev/null +++ b/doc/services/monitoring/Service.md.rst @@ -0,0 +1,23 @@ +Cloud Monitoring Service +======================== + +Initializing the Cloud Monitoring is easy - and can be done in a similar +way to all other Rackspace services: + +1. Create client and pass in auth details. For more information about + creating clients, please consult the `Client + documentation <../Clients.md>`__. +2. Use the factory method, specifying additional parameters where + necessary: + +.. code:: php + + $service = $client->cloudMonitoringService('cloudMonitoring', 'ORD', 'publicURL'); + +All three parameters are optional - if not specified, it will revert to +the service's default values which are: + +- Name = ``cloudMonitoring`` +- Region = ``DFW`` +- URL type = ``publicURL`` + diff --git a/doc/services/monitoring/Views.md.rst b/doc/services/monitoring/Views.md.rst new file mode 100644 index 000000000..a5b7245fa --- /dev/null +++ b/doc/services/monitoring/Views.md.rst @@ -0,0 +1,27 @@ +Views +===== + +Info +---- + +Views contain a combination of data that usually includes multiple, +different objects. The primary purpose of a view is to save API calls +and make data retrieval more efficient. Instead of doing multiple API +calls and then combining the result yourself, you can perform a single +API call against the view endpoint. + +List all Views +-------------- + +\`\`\`php $views = $service->getViews(); + +foreach ($views as $view) { $entity = $view->getEntity(); + +:: + + echo $view->getTimestamp(); + +} \`\`\` + +Please consult the `iterator doc `__ for +more information about iterators. diff --git a/doc/services/monitoring/Zones.md.rst b/doc/services/monitoring/Zones.md.rst new file mode 100644 index 000000000..ffe4bba1e --- /dev/null +++ b/doc/services/monitoring/Zones.md.rst @@ -0,0 +1,67 @@ +Zones +===== + +Info +---- + +A monitoring zone is a location that Rackspace Cloud Monitoring collects +data from. Examples of monitoring zones are "US West", "DFW1" or "ORD1". +It is an abstraction for a general location from which data is +collected. + +An "endpoint," also known as a "collector," collects data from the +monitoring zone. The endpoint is mapped directly to an individual +machine or a virtual machine. A monitoring zone contains many endpoints, +all of which will be within the IP address range listed in the response. +The opposite is not true, however, as there may be unallocated IP +addresses or unrelated machines within that IP address range. + +A check references a list of monitoring zones it should be run from. + + Setup +------ + +.. code:: php + + $zoneId = 'mzAAAAA'; + $zone = $monitoringService->getMonitoringZone($zoneId); + +Attributes +---------- + ++-----------------+------------------+-----------------------------------+------------------------+ +| Name | Description | Data type | Method | ++=================+==================+===================================+========================+ +| country\_code | Country Code | String longer than 2 characters | ``getCountryCode()`` | ++-----------------+------------------+-----------------------------------+------------------------+ +| label | Label | String | ``getLabel()`` | ++-----------------+------------------+-----------------------------------+------------------------+ +| source\_ips | Source IP list | Array | ``getSourceIps()`` | ++-----------------+------------------+-----------------------------------+------------------------+ + + List all zones +--------------- + +.. code:: php + + $zones = $service->getMonitoringZones(); + +Please consult the `iterator doc `__ for +more information about iterators. + +Perform a traceroute +-------------------- + +.. code:: php + + $traceroute = $zone->traceroute(array( + 'target' => 'http://test.com', + 'target_resolver' => 'IPv4' + )); + + // How many hops? + echo count($traceroute); + + // What was the first hop's IP? + echo $traceroute[0]->ip; + diff --git a/doc/services/monitoring/index.rst b/doc/services/monitoring/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/networking/README.md.rst b/doc/services/networking/README.md.rst new file mode 100644 index 000000000..605805fe1 --- /dev/null +++ b/doc/services/networking/README.md.rst @@ -0,0 +1,108 @@ +Networking +========== + +**Networking** is a service that you can use to create virtual networks +and attach cloud devices such as servers to these networks. + +Concepts +-------- + +Concepts +-------- + +To use the Networking service effectively, you should understand the +following key concepts: + +- **Network**: A network is an isolated virtual layer-2 broadcast + domain that is typically reserved for the tenant who created it + unless you configure the network to be shared. The network is the + main entity in the Networking service. Ports and subnets are always + associated with a network. + +- **Subnet**: A subnet represents an IP address block that can be used + to assign IP addresses to virtual instances (such as servers created + using the Compute service). Each subnet must have a CIDR and must be + associated with a network. + +- **Port**: A port represents a virtual switch port on a logical + network switch. Virtual instances (such as servers created using the + Compute service) attach their interfaces into ports. The port also + defines the MAC address and the IP address(es) to be assigned to the + interfaces plugged into them. When IP addresses are associated to a + port, this also implies the port is associated with a subet, as the + IP address is taken from the allocation pool for a specific subnet. + +Getting started +--------------- + +1. Instantiate an OpenStack or Rackspace client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use the Networking service, you must first instantiate a +``OpenStack`` or ``Rackspace`` client object. + +- If you are working with an OpenStack cloud, instantiate an + ``OpenCloud\OpenStack`` client as follows: + + .. code:: php + + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'password' => '' + )); + +- If you are working with the Rackspace cloud, instantiate a + ``OpenCloud\Rackspace`` client as follows: + + .. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +2. Obtain an Networking service object from the client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +All Networking operations are done via an *networking service object*. +To instantiate this object, call the ``networkingService`` method on the +``$client`` object. This method takes two arguments: + ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ +| Position | Description | Data type | Required? | Default value | Example value | ++============+=============================================================+=============+=============+====================================================+=====================+ +| 1 | Name of the service, as it appears in the service catalog | String | No | ``null``; automatically determined when possible | ``cloudNetworks`` | ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ +| 2 | Cloud region | String | Yes | - | ``DFW`` | ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ + +.. code:: php + + $region = ''; + $networkingService = $client->networkingService(null, $region); + +Any networks, subnets, and ports created with this +``$networkingService`` instance will be stored in the cloud region +specified by ``$region``. + +3. Create a network. +~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $network = $networkingService->createNetwork(array( + 'name' => 'My private backend network' + )); + +[ `Get the executable PHP script for this +example `__ ] + +Next steps +---------- + +Once you have created a network, there is more you can do with it. See +`complete user guide for networking `__. diff --git a/doc/services/networking/USERGUIDE.md.rst b/doc/services/networking/USERGUIDE.md.rst new file mode 100644 index 000000000..bfeb27774 --- /dev/null +++ b/doc/services/networking/USERGUIDE.md.rst @@ -0,0 +1,582 @@ +Complete User Guide for the Networking Service +============================================== + +Networking is a service that you can use to create virtual networks and +attach cloud devices such as servers to these networks. + +This user guide introduces you the entities in the Networking service — +networks, subnets, and ports — and shows you how to create and manage +these entities. + +Table of contents +----------------- + +- `Concepts <#concepts>`__ +- `Prerequisites <#prerequisites>`__ + + - `Client <#client>`__ + - `Networking service <#networking-service>`__ + +- `Networks <#networks>`__ + + - `Create a network <#create-a-network>`__ + - `Create multiple networks <#create-multiple-networks>`__ + - `List networks <#list-networks>`__ + - `Get a network <#get-a-network>`__ + - `Update a network <#update-a-network>`__ + - `Delete a network <#delete-a-network>`__ + +- `Subnets <#subnets>`__ + + - `Create a subnet <#create-a-subnet>`__ + - `Create multiple subnets <#create-multiple-subnets>`__ + - `List subnets <#list-subnets>`__ + - `Get a subnet <#get-a-subnet>`__ + - `Update a subnet <#update-a-subnet>`__ + - `Delete a subnet <#delete-a-subnet>`__ + +- `Ports <#ports>`__ + + - `Create a port <#create-a-port>`__ + - `Create multiple ports <#create-multiple-ports>`__ + - `List ports <#list-ports>`__ + - `Get a port <#get-a-port>`__ + - `Update a port <#update-a-port>`__ + - `Delete a port <#delete-a-port>`__ + +Concepts +-------- + +To use the Networking service effectively, you should understand the +following key concepts: + +- **Network**: An isolated virtual layer-2 broadcast domain that is + typically reserved for the tenant who created it unless it is + configured to be shared. The network is the main entity in the + Networking service. Ports and subnets are always associated with a + network. + +- **Subnet**: An IP address block that can be used to assign IP + addresses to virtual instances (such as servers created using the + Compute service). Each subnet must have a CIDR and must be associated + with a network. + +- **Port**: A virtual switch port on a logical network switch. Virtual + instances (such as servers created using the Compute service) attach + their interfaces into ports. The port also defines the MAC address + and the IP address or addresses to be assigned to the interfaces + plugged into them. When IP addresses are associated with a port, this + also implies the port is associated with a subnet because the IP + address is taken from the allocation pool for a specific subnet. + +Prerequisites +------------- + +Client +~~~~~~ + +To use the Networking service, you must first instantiate a +``OpenStack`` or ``Rackspace`` client object. + +- If you are working with an OpenStack cloud, instantiate an + ``OpenCloud\OpenStack`` client as follows: + + .. code:: php + + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'password' => '' + )); + +- If you are working with the Rackspace cloud, instantiate an + ``OpenCloud\Rackspace`` client as follows: + + .. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +Networking service +~~~~~~~~~~~~~~~~~~ + +All Networking operations are done via a *networking service object*. To +instantiate this object, call the ``networkingService`` method on the +``$client`` object. This method takes the following arguments: + ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ +| Position | Description | Data type | Required? | Default value | Example value | ++============+=============================================================+=============+=============+====================================================+=====================+ +| 1 | Name of the service, as it appears in the service catalog | String | No | ``null``; automatically determined when possible | ``cloudNetworks`` | ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ +| 2 | Cloud region | String | Yes | - | ``DFW`` | ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ + +.. code:: php + + $region = ''; + $networkingService = $client->networkingService(null, $region); + +Any networks, subnets, and ports created with this +``$networkingService`` instance are stored in the cloud region specified +by ``$region``. + +Networks +-------- + +A network is an isolated virtual layer-2 broadcast domain that is +typically reserved for the tenant who created it unless it is configured +to be shared. The network is the main entity in the Networking service. +Ports and subnets are always associated with a network. + +Create a network +~~~~~~~~~~~~~~~~ + +This operation takes one parameter, an associative array, with the +following keys: + ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++====================+===================================================================================================+=============+=============+=======================================+==================================+ +| ``name`` | A human-readable name for the network. This name might not be unique. | String | No | ``null`` | ``My private backend network`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| ``adminStateUp`` | The administrative state of network. If ``false`` (down), the network does not forward packets. | Boolean | No | ``true`` | ``true`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| ``shared`` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | ``false`` | ``false`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| ``tenantId`` | Owner of network. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the network | ``123456`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ + +You can create a network as shown in the following example: + +.. code:: php + + $network = $networkingService->createNetwork(array( + 'name' => 'My private backend network' + )); + /** @var $network OpenCloud\Networking\Resource\Network **/ + +[ `Get the executable PHP script for this +example `__ ] + +Create multiple networks +~~~~~~~~~~~~~~~~~~~~~~~~ + +This operation takes one parameter, an indexed array. Each element of +this array must be an associative array with the keys shown in `the +preceding table <#create-a-network>`__. + +You can create multiple networks as shown in the following example: + +.. code:: php + + $networks = $networkingService->createNetworks(array( + array( + 'name' => 'My private backend network #1' + ), + array( + 'name' => 'My private backend network #2' + ) + )); + + foreach ($networks as $network) { + /** @var $network OpenCloud\Networking\Resource\Network **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +List networks +~~~~~~~~~~~~~ + +You can list all the networks to which you have access as shown in the +following example: + +.. code:: php + + $networks = $networkingService->listNetworks(); + foreach ($networks as $network) { + /** @var $network OpenCloud\Networking\Resource\Network **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Get a network +~~~~~~~~~~~~~ + +You can retrieve a specific network by using that network's ID, as shown +in the following example: + +.. code:: php + + $network = $networkingService->getNetwork('eb60583c-57ea-41b9-8d5c-8fab2d22224c'); + /** @var $network OpenCloud\Networking\Resource\Network **/ + +[ `Get the executable PHP script for this +example `__ ] + +Update a network +~~~~~~~~~~~~~~~~ + +This operation takes one parameter, an associative array, with the +following keys: + ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++====================+===================================================================================================+=============+=============+=================+==========================================+ +| ``name`` | A human-readable name for the network. This name might not be unique. | String | No | ``null`` | ``My updated private backend network`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ +| ``adminStateUp`` | The administrative state of network. If ``false`` (down), the network does not forward packets. | Boolean | No | ``true`` | ``true`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ +| ``shared`` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | ``false`` | ``false`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ + +You can update a network as shown in the following example: + +.. code:: php + + $network->update(array( + 'name' => 'My updated private backend network' + )); + +[ `Get the executable PHP script for this +example `__ ] + +Delete a network +~~~~~~~~~~~~~~~~ + +You can delete a network as shown in the following example: + +.. code:: php + + $network->delete(); + +[ `Get the executable PHP script for this +example `__ ] + +Subnets +------- + +A subnet represents an IP address block that can be used to assign IP +addresses to virtual instances (such as servers created using the +Compute service). Each subnet must have a CIDR and must be associated +with a network. + +Create a subnet +~~~~~~~~~~~~~~~ + +This operation takes one parameter, an associative array, with the +following keys: + ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++=======================+===================================================================================================================+=======================================+=============+========================================================================+=================================================================================+ +| ``networkId`` | Network this subnet is associated with | String | Yes | - | ``eb60583c-57ea-41b9-8d5c-8fab2d22224c`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``ipVersion`` | IP version | Integer (``4`` or ``6``) | Yes | - | ``4`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``cidr`` | CIDR representing the IP address range for this subnet | String (CIDR) | Yes | - | ``192.168.199.0/25`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``name`` | A human-readable name for the subnet. This name might not be unique. | String | No | ``null`` | ``My subnet`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``gatewayIp`` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | ``192.168.199.128`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``dnsNameservers`` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | ``array('4.4.4.4', '8.8.8.8')`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``allocationPools`` | Subranges of the CIDR available for dynamic allocation to ports | Indexed array of associative arrays | No | Every IP address in CIDR, excluding gateway IP address if configured | ``array(array('start' => '192.168.199.2', 'end' => '192.168.199.127'))`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``hostRoutes`` | Routes that should be used by devices with IP addresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | ``array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.19.20'))`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``enableDhcp`` | Specifies whether DHCP is enabled for this subnet | Boolean | No | ``true`` | ``false`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``tenantId`` | Owner of the subnet. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the subnet | ``123456`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ + +You can create a subnet as shown in the following example: + +.. code:: php + + $subnet = $networkingService->createSubnet(array( + 'name' => 'My subnet', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c', + 'ipVersion' => 4, + 'cidr' => '192.168.199.0/25' + )); + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + +[ `Get the executable PHP script for this +example `__ ] + +Create multiple subnets +~~~~~~~~~~~~~~~~~~~~~~~ + +This operation takes one parameter, an indexed array. Each element of +this array must be an associative array with the keys shown in `the +preceding table <#create-a-subnet>`__. + +You can create multiple subnets as shown in the following example: + +.. code:: php + + $subnets = $networkingService->createSubnets(array( + array( + 'name' => 'My subnet #1' + ), + array( + 'name' => 'My subnet #2' + ) + )); + + foreach ($subnets as $subnet) { + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +List subnets +~~~~~~~~~~~~ + +You can list all the subnets to which you have access as shown in the +following example: + +.. code:: php + + $subnets = $networkingService->listSubnets(); + foreach ($subnets as $subnet) { + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Get a subnet +~~~~~~~~~~~~ + +You can retrieve a specific subnet by using that subnet's ID, as shown +in the following example: + +.. code:: php + + $subnet = $networkingService->getSubnet('d3f15879-fb11-49bd-a30b-7704fb98ab1e'); + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + +[ `Get the executable PHP script for this +example `__ ] + +Update a subnet +~~~~~~~~~~~~~~~ + +This operation takes one parameter, an associative array, with the +following keys: + ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++======================+==================================================================================================================+=======================================+=============+============================+=================================================================================+ +| ``name`` | A human-readable name for the subnet. This name might not be unique. | String | No | ``null`` | ``My updated subnet`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``gatewayIp`` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | ``192.168.62.155`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``dnsNameservers`` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | ``array('4.4.4.4', '8.8.8.8')`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``hostRoutes`` | Routes that should be used by devices with IP adresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | ``array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.17.19'))`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``enableDhcp`` | Specifies whether DHCP is enabled for this subnet | Boolean | No | ``true`` | ``false`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ + +You can update a subnet as shown in the following example: + +.. code:: php + + $subnet->update(array( + 'name' => 'My updated subnet', + 'hostRoutes' => array( + array( + 'destination' => '1.1.1.0/24', + 'nexthop' => '192.168.17.19' + ) + ), + 'gatewayIp' => '192.168.62.155' + )); + +[ `Get the executable PHP script for this +example `__ ] + +Delete a subnet +~~~~~~~~~~~~~~~ + +You can delete a subnet as shown in the following example: + +.. code:: php + + $subnet->delete(); + +[ `Get the executable PHP script for this +example `__ ] + +Ports +----- + +A port represents a virtual switch port on a logical network switch. +Virtual instances (such as servers created using the Compute service) +attach their interfaces into ports. The port also defines the MAC +address and the IP address or addresses to be assigned to the interfaces +plugged into them. When IP addresses are associated with a port, this +also implies the port is associated with a subnet because the IP address +is taken from the allocation pool for a specific subnet. + +Create a port +~~~~~~~~~~~~~ + +This operation takes one parameter, an associative array, with the +following keys: + ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++======================+=============================================================================================+============================================================+=============+=========================================+===========================================================================================================+ +| ``networkId`` | Network this port is associated with | String | Yes | - | ``eb60583c-57ea-41b9-8d5c-8fab2d22224c`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``name`` | A human-readable name for the port. This name might not be unique. | String | No | ``null`` | ``My port`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``adminStateUp`` | The administrative state of port. If ``false`` (down), the port does not forward packets. | Boolean | No | ``true`` | ``true`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``macAddress`` | MAC address to use on this port | String (MAC address in 6-octet form separated by colons) | No | Generated | ``0F:5A:6F:70:E9:5C`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``fixedIps`` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | ``array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.17'))`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceId`` | Identifies the device (for example, virtual server) using this port | String | No | ``null`` | ``5e3898d7-11be-483e-9732-b2f5eccd2b2e`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceOwner`` | Identifies the entity (for example, DHCP agent) using this port | String | No | ``null`` | ``network:router_interface`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``securityGroups`` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | ``array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``tenantId`` | Owner of the port. Only admin users can specify a tenant ID other than their own. | String | No | Same as the tenant creating the port | ``123456`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ + +You can create a port as shown in the following example: + +.. code:: php + + $port = $networkingService->createPort(array( + 'name' => 'My port', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' + )); + /** @var $port OpenCloud\Networking\Resource\Port **/ + +[ `Get the executable PHP script for this +example `__ ] + +Create multiple ports +~~~~~~~~~~~~~~~~~~~~~ + +This operation takes one parameter, an indexed array. Each element of +this array must be an associative array with the keys shown in `the +preceding table <#create-a-port>`__. + +You can create multiple ports as shown in the following example: + +.. code:: php + + $ports = $networkingService->createPorts(array( + array( + 'name' => 'My port #1', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' + ), + array( + 'name' => 'My port #2', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' + ) + )); + + foreach ($ports as $port) { + /** @var $port OpenCloud\Networking\Resource\Port **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +List ports +~~~~~~~~~~ + +You can list all the ports to which you have access as shown in the +following example: + +.. code:: php + + $ports = $networkingService->listPorts(); + foreach ($ports as $port) { + /** @var $port OpenCloud\Networking\Resource\Port **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Get a port +~~~~~~~~~~ + +You can retrieve a specific port by using that port's ID, as shown in +the following example: + +.. code:: php + + $port = $networkingService->getPort('75906d20-6625-11e4-9803-0800200c9a66'); + /** @var $port OpenCloud\Networking\Resource\Port **/ + +[ `Get the executable PHP script for this +example `__ ] + +Update a port +~~~~~~~~~~~~~ + +This operation takes one parameter, an associative array, with the +following keys: + ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++======================+=============================================================================================+=======================================+=============+=========================================+===========================================================================================================+ +| ``name`` | A human-readable name for the port. This name might not be unique. | String | No | ``null`` | ``My port`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``adminStateUp`` | The administrative state of port. If ``false`` (down), the port does not forward packets. | Boolean | No | ``true`` | ``true`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``fixedIps`` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | ``array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.59'))`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceId`` | Identifies the device (for example, virtual server) using this port | String | No | ``null`` | ``5e3898d7-11be-483e-9732-b2f5eccd2b2e`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceOwner`` | Identifies the entity (for example, DHCP agent) using this port | String | No | ``null`` | ``network:router_interface`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``securityGroups`` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | ``array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ + +You can update a port as shown in the following example: + +.. code:: php + + $port->update(array( + 'fixedIps' => array( + array( + 'subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', + 'ipAddress' => '192.168.199.59' + ) + ) + )); + +[ `Get the executable PHP script for this +example `__ ] + +Delete a port +~~~~~~~~~~~~~ + +You can delete a port as shown in the following example: + +.. code:: php + + $port->delete(); + +[ `Get the executable PHP script for this +example `__ ] diff --git a/doc/services/networking/index.rst b/doc/services/networking/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/object-store/Access.md.rst b/doc/services/object-store/Access.md.rst new file mode 100644 index 000000000..ee85a938e --- /dev/null +++ b/doc/services/object-store/Access.md.rst @@ -0,0 +1,75 @@ +Setup +----- + +.. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(RACKSPACE_US, array( + + )); + + $service = $client->objectStoreService('cloudFiles', 'IAD'); # Second argument is the region you want + +Temporary URLs +-------------- + +Temporary URLs allow you to create time-limited Internet addresses that +allow you to grant access to your Cloud Files account. Using Temporary +URL, you may allow others to retrieve or place objects in your +containers - regardless of whether they're CDN-enabled. + +Set "temporary URL" metadata key +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You must set this "secret" value on your account, where it can be used +in a global state: + +.. code:: php + + $account = $service->getAccount(); + $account->setTempUrlSecret('my_secret'); + + echo $account->getTempUrlSecret(); + +The string argument of ``setTempUrlSecret()`` is optional - if left out, +the SDK will generate a random hashed secret for you. + +Create a temporary URL +~~~~~~~~~~~~~~~~~~~~~~ + +Once you've set an account secret, you can create a temporary URL for +your object. To allow GET access to your object for 1 minute: + +.. code:: php + + $object->getTemporaryUrl(60, 'GET'); + +To allow PUT access for 1 hour: + +.. code:: php + + $object->getTemporaryUrl(360, 'PUT'); + +Hosting websites on CloudFiles +------------------------------ + +To host a static (i.e. HTML) website on CloudFiles, you must follow +these steps: + +1. CDN-enable a container +2. Upload all HTML content. You can use nested directory structures. +3. Tell CloudFiles what to use for your default index page like this: + +.. code:: php + + $container->setStaticIndexPage('index.html'); + +4. (Optional) Tell CloudFiles which error page to use by default: + +.. code:: php + + $container->setStaticErrorPage('error.html'); + +Bear in mind that steps 3 & 4 do not upload content, but rather specify +a reference to an existing page/CloudFiles object. diff --git a/doc/services/object-store/Account.md.rst b/doc/services/object-store/Account.md.rst new file mode 100644 index 000000000..a2d380b2a --- /dev/null +++ b/doc/services/object-store/Account.md.rst @@ -0,0 +1,33 @@ +Setup +----- + +.. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(RACKSPACE_US, array( + + )); + + $service = $client->objectStoreService('cloudFiles'); + +View Account Details +-------------------- + +To see how many containers you have in your account +(X-Account-Container-Count), how many objects are in your account +(X-Account-Object-Count), and how many total bytes your account uses +(X-Account-Bytes-Used): + +.. code:: php + + $account = $service->getAccount(); + + // Either return the full Metadata object + $details = $account->getDetails(); + + // or individual values + $account->getContainerCount(); + $account->getObjectCount(); + $account->getBytesUsed(); + diff --git a/doc/services/object-store/Container.md.cdn.rst b/doc/services/object-store/Container.md.cdn.rst new file mode 100644 index 000000000..2f1c8ea68 --- /dev/null +++ b/doc/services/object-store/Container.md.cdn.rst @@ -0,0 +1,90 @@ +Setup +----- + +.. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(RACKSPACE_US, array( + + )); + + $service = $client->objectStoreService('cloudFiles'); + +To access the CDN functionality of a particular container: + +.. code:: php + + $container = $service->getContainer('foo_bar'); + + $cdn = $container->getCdn(); + +List CDN-enabled container +-------------------------- + +To list CDN-only containers, follow the same operation for Storage which +lists all containers. The only difference is which service object you +execute the method on: + +.. code:: php + + $cdnService = $service->getCdnService(); + $cdnContainers = $cdnService->listContainers(); + + foreach ($cdnContainers as $cdnContainer) { + + } + +CDN-enable and -disable a container +----------------------------------- + +Before a container can be CDN-enabled, it must exist in the storage +system. When a container is CDN-enabled, any objects stored in it are +publicly accessible over the Content Delivery Network by combining the +container's CDN URL with the object name. + +Any CDN-accessed objects are cached in the CDN for the specified amount +of time called the TTL. The default TTL value is 259200 seconds, or 72 +hours. Each time the object is accessed after the TTL expires, the CDN +refetches and caches the object for the TTL period. + +.. code:: php + + $container->enableCdn(); + $container->disableCdn(); + +Serving containers through SSL +------------------------------ + +.. code:: php + + $cdn->getCdnSslUri(); + +Streaming CDN-enabled containers +-------------------------------- + +.. code:: php + + $cdn->getCdnStreamingUri(); + +iOS streaming +------------- + +The Cloud Files CDN allows you to stream video to iOS devices without +needing to convert your video. Once you CDN-enable your container, you +have the tools necessary for streaming media to multiple devices. + +.. code:: php + + $cdn->getIosStreamingUri(); + +CDN logging +----------- + +To enable and disable logging for your CDN: + +.. code:: php + + $cdn->enableCdnLogging(); + $cdn->disableCdnLogging(); + diff --git a/doc/services/object-store/Container.md.storage.rst b/doc/services/object-store/Container.md.storage.rst new file mode 100644 index 000000000..89798fdd0 --- /dev/null +++ b/doc/services/object-store/Container.md.storage.rst @@ -0,0 +1,218 @@ +Setup +----- + +.. code:: php + + use OpenCloud\Rackspace; + + // Create a client object to communicate with various Rackspace Cloud services. + $client = new Rackspace(RACKSPACE_US, array( + 'username' => 'Replace this with your Rackspace Cloud user name', + 'apiKey' => 'Replace this with your Rackspace Cloud API key' + )); + + // Create a service object to use the object store service. The sample code + // creates the object store in the 'DFW' region. + $service = $client->objectStoreService('cloudFiles', 'DFW'); + +Create container +---------------- + +To create a new container, you just need to define its name: + +.. code:: php + + $container = $service->createContainer('my_amazing_container'); + +If the response returned is ``FALSE``, there was an API error - most +likely due to the fact you have a naming collision. + +Container names must be valid strings between 0 and 256 characters. +Forward slashes are not currently permitted. + + **Note:** when working with names that contain non-standard + alphanumerical characters (such as spaces or non-English + characters), you must ensure they are encoded with + ```urlencode`` `__ before passing them in + +List containers +--------------- + +Return a list of containers +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $containerList = $service->listContainers(); + + while ($container = $containerList->next()) { + // Do stuff; some examples below + printf("Container name: %s\n", $container->name); + printf("Number of objects within container: %d\n", $container->getObjectCount()); + } + +Container names are sorted based on a binary comparison, a single +built-in collating sequence that compares string data using SQLite's +memcmp() function, regardless of text encoding. + +The list is limited to 10,000 containers at a time. See 1.3 for ways to +limit and navigate this list. + +Return a formatted list of containers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Currently, the SDK only supports JSON-formatted responses. + +Controlling a large list of containers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You may limit and control this list of results by using the ``marker`` +and ``end_marker`` parameters. The former parameter (``marker``) tells +the API where to begin the list, and the latter (``end_marker``) tells +it where to end the list. You may use either of them independently or +together. You may also use the ``limit`` parameter to fix the number of +containers returned. + +To list a set of containers between two fixed points: + +.. code:: php + + $someContainers = $service->listContainers(array( + 'marker' => 'container_55', + 'end_marker' => 'container_2001' + )); + +Or to return a limited set: + +.. code:: php + + $someContainers = $service->listContainers(array('limit' => 560)); + +Get container +------------- + +To retrieve a certain container, either to access its object or +metadata: + +.. code:: php + + $container = $service->getContainer('container_name'); + + echo $container->getObjectCount(); + echo $container->getBytesUsed(); + +Delete container +---------------- + +Deleting a container is easy: + +.. code:: php + + $container->delete(); + +Please bear mind that you must delete all objects inside a container +before deleting it. This is done for you if you set the +``$deleteObjects`` parameter to ``TRUE`` like so: + +.. code:: php + + $container->delete(TRUE); + +You can also do it manually: + +.. code:: php + + $container->deleteAllObjects(); + $container->delete(); + +Create or update container metadata +----------------------------------- + +.. code:: php + + $container->saveMetadata(array( + 'Author' => 'Virginia Woolf', + 'Published' => '1931' + )); + +Please bear in mind that this action will set metadata to this array - +overriding existing values and wiping those left out. To *append* values +to the current metadata: + +.. code:: php + + $metadata = $container->appendToMetadata(array( + 'Publisher' => 'Hogarth' + )); + +If you only want to set the metadata to the local object, and not +immediately retain these values on the API, you can use a standard +setter method - which can contribute to eventual actions like an update: + +.. code:: php + + $container->setMetadata(array('Foo' => 'Bar')); + +Container quotas +---------------- + +The container\_quotas middleware implements simple quotas that can be +imposed on Cloud Files containers by a user. Setting container quotas +can be useful for limiting the scope of containers that are delegated to +non-admin users, exposed to formpost uploads, or just as a self-imposed +sanity check. + +To set quotas for a container: + +.. code:: php + + use OpenCloud\Common\Constants\Size; + + $container->setCountQuota(1000); + $container->setBytesQuota(2.5 * Size::GB); + +And to retrieve them: + +.. code:: php + + echo $container->getCountQuota(); + echo $container->getBytesQuota(); + +Access log delivery +------------------- + +To view your object access, turn on Access Log Delivery. You can use +access logs to analyze the number of people who access your objects, +where they come from, how many requests for each object you receive, and +time-based usage patterns (such as monthly or seasonal usage). + +.. code:: php + + $container->enableLogging(); + $container->disableLogging(); + +Syncing containers +------------------ + +You can synchronize local directories with your CloudFiles/Swift +containers very easily. When you do this, the container will mirror +exactly the nested file structure within your local directory: + +.. code:: php + + $container->uploadDirectory('/home/Jamie/blog'); + +There are four scenarios you should be aware of: + ++------------------------+-----------------------+----------------------+--------------------------------+ +| Local | Remote | Comparison | Action | ++========================+=======================+======================+================================+ +| File exists | File exists | Identical checksum | No action | ++------------------------+-----------------------+----------------------+--------------------------------+ +| File exists | File exists | Different checksum | Local file overwrites remote | ++------------------------+-----------------------+----------------------+--------------------------------+ +| File exists | File does not exist | - | Local file created in Swift | ++------------------------+-----------------------+----------------------+--------------------------------+ +| Files does not exist | File exists | - | Remote file deleted | ++------------------------+-----------------------+----------------------+--------------------------------+ + diff --git a/doc/services/object-store/Migrating.md.storage.rst b/doc/services/object-store/Migrating.md.storage.rst new file mode 100644 index 000000000..99738554b --- /dev/null +++ b/doc/services/object-store/Migrating.md.storage.rst @@ -0,0 +1,101 @@ +Migrating containers (across regions) +===================================== + +Introduction +------------ + +Currently, there exists no single API operation to copy containers +across geographic endpoints. Although the API offers a ``COPY`` +operation for individual files, this does not work for cross-region +copying. The SDK, however, does offer this functionality. + +You **will** be charged for bandwidth between regions, so it's advisable +to use ServiceNet where possible (which is free). + +Requirements +------------ + +- You must install the full Guzzle package, so that the process can + take advantage of Guzzle's batching functionality (it allows parallel + requests to be batched for greater efficiency). You can do this by + running: + +.. code:: bash + + php composer.phar install --dev + +- Depending on the size and number of transfer items, you will need to + raise PHP's memory limit: + +.. code:: php + + ini_set('memory_limit', '512M'); + +- You will need to enact some kind of backoff/retry strategy for rate + limits. Guzzle comes with a convenient feature that just needs to be + added as a normal subscriber: + +.. code:: php + + use Guzzle\Plugin\Backoff\BackoffPlugin; + + $client->addSubscriber(BackoffPlugin::getExponentialBackoff(10, array(500, 503, 408))); + +This tells the client to retry up to ``10`` times for failed requests +have resulted in these HTTP status codes: ``500``, ``503`` or ``408``. + +Setup +----- + +You can access all this functionality by executing: + +.. code:: php + + $ordService = $client->objectStoreService('cloudFiles', 'ORD'); + $iadService = $client->objectStoreService('cloudFiles', 'IAD'); + + $oldContainer = $ordService->getContainer('old_container'); + $newContainer = $iadService->getContainer('new_container'); + + $iadService->migrateContainer($oldContainer, $newContainer); + +It's advisable to do this process in a Cloud Server in one of the two +regions you're migrating to/from. This allows you to use ``privateURL`` +as the third argument in the ``objectStoreService`` methods like this: + +.. code:: php + + $client->objectStoreService('cloudFiles', 'IAD', 'privateURL'); + +This will ensure that traffic between your server and your new IAD +container will be held over the internal Rackspace network which is +free. + +Options +------- + +You can pass in an array of arguments to the method: + +.. code:: php + + $options = array( + 'read.batchLimit' => 100, + 'read.pageLimit' => 100, + 'write.batchLimit' => 50 + ); + + $iadService->migrateContainer($oldContainer, $newContainer, $options); + +Options explained +~~~~~~~~~~~~~~~~~ + ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ +| Name | Description | Default | ++========================+===============================================================================================================================================================================================================================================================================================================================================+===========+ +| ``read.pageLimit`` | When the process begins, it has to collect all the files that exist in the old container. It does this through a conventional ``objectList`` method, which calls the ``PaginatedIterator``. This iterator has the option to specify the page size for the collection (i.e. how many items are contained per page in responses from the API) | 10,000 | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ +| ``read.batchLimit`` | After the data objects are collected, the process needs to send an individual GET request to ascertain more information. In order to make this process faster, these individual GET requests are batched together and sent in parallel. This limit refers to how many of these GET requests are batched together. | 1,000 | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ +| ``write.batchLimit`` | Once each file has been retrieved from the API, a PUT request is executed against the new container. Similar to above, these PUT requests are batched - and this number refers to the amount of PUT requests batched together. | 100 | ++------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ + diff --git a/doc/services/object-store/Object.md.cdn.rst b/doc/services/object-store/Object.md.cdn.rst new file mode 100644 index 000000000..64ac143b3 --- /dev/null +++ b/doc/services/object-store/Object.md.cdn.rst @@ -0,0 +1,25 @@ +Setup +----- + +You will need to instantiate the container object and access its CDN +functionality as `documented +here `__. + +Purge CDN-enabled objects +------------------------- + +To remove a CDN object from public access: + +.. code:: php + + $object->purge(); + +You can also provide an optional e-mail address (or comma-delimeted list +of e-mails), which the API will send a confirmation message to once the +object has been completely purged: + +.. code:: php + + $object->purge('jamie.hannaford@rackspace.com'); + $object->purge('hello@example.com,hallo@example.com'); + diff --git a/doc/services/object-store/Object.md.storage.rst b/doc/services/object-store/Object.md.storage.rst new file mode 100644 index 000000000..16dab18f4 --- /dev/null +++ b/doc/services/object-store/Object.md.storage.rst @@ -0,0 +1,330 @@ +Setup +----- + +Conceptually, a container contains objects (also known as files). In +order to work with objects, you will need to instantiate a container +object first as `documented +here `__. + +Note on object properties +------------------------- + +Please be aware that you cannot directly access the properties of +DataObject anymore, you **must** use appropriate getter/ setter methods: + ++----------------------+------------------------+ +| Property | Method | ++======================+========================+ +| Parent container | ``getContainer`` | ++----------------------+------------------------+ +| Name | ``getName`` | ++----------------------+------------------------+ +| Body of file | ``getContent`` | ++----------------------+------------------------+ +| Size of file | ``getContentLength`` | ++----------------------+------------------------+ +| Type of file | ``getContentType`` | ++----------------------+------------------------+ +| ETag checksum | ``getEtag`` | ++----------------------+------------------------+ +| Last modified date | ``getLastModified`` | ++----------------------+------------------------+ + +Create an object +---------------- + +There are three ways to upload a new file, each of which has different +business needs. + + **Note:** Unlike previous versions, you do not need to manually + specify your object's content type. The API will do this for you. + + **Note:** when working with names that contain non-standard + alphanumerical characters (such as spaces or non-English + characters), you must ensure they are encoded with + ```urlencode`` `__ before passing them in + +To upload a single/basic file: +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + use OpenCloud\ObjectStore\Resource\DataObject; + + $data = fopen('/path/to/sample.mp3', 'r+'); + + // alternatively, you can pass in a string as the file contents `$data` argument (instead of a resource) + + $meta = array( + 'Author' => 'Camera Obscura', + 'Origin' => 'Glasgow' + ); + + $metaHeaders = DataObject::stockHeaders($meta); + $customHeaders = array(); + $allHeaders = $metaHeaders + $customHeaders; + + $container->uploadObject('sample.mp3', $data, $allHeaders); + +To upload multiple small-to-mid sized files: +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $files = array( + array( + 'name' => 'apache.log', + 'path' => '/etc/httpd/logs/error_log' + ), + array( + 'name' => 'mysql.log', + 'body' => fopen('/tmp/mysql.log', 'r+') + ), + array( + 'name' => 'to_do_list.txt', + 'body' => 'PHONE HOME' + ) + ); + + $container->uploadObjects($files); + +As you can see, the ``name`` key is required for every file. You must +also specify *either* a path key (to an existing file), or a ``body``. +The ``body`` can either be a PHP resource or a string representation of +the content you want to upload. + +To upload large files +~~~~~~~~~~~~~~~~~~~~~ + +For files over 5GB, you will need to use the +``OpenCloud\ObjectStore\Upload\TransferBuilder`` factory to build your +transfer, upon which you can execute your upload functionality. For your +convenience, the Container resource object contains a simple method to +do this heavy lifting for you: + +.. code:: php + + $transfer = $container->setupObjectTransfer(array( + 'name' => 'video.mov', + 'path' => '/home/jamie/video.mov', + 'metadata' => array( + 'Author' => 'Jamie' + ), + 'concurrency' => 4, + 'partSize' => 1.5 * Size::GB + )); + + $transfer->upload(); + +You can specify how many concurrent cURL connections are used to upload +parts of your file. The file is fragmented into chunks, each of which is +uploaded individually as a separate file (the filename of each part will +indicate that it's a segment rather than the full file). After all parts +are uploaded, a manifest is uploaded. When the end-user accesses the 5GB +by its true filename, it actually references the manifest file which +concatenates each segment into a streaming download. + +List objects in a container +--------------------------- + +To return a list of objects: + +.. code:: php + + $files = $container->objectList(); + + foreach ($files as $file) { + // ... do something + } + +By default, 10,000 objects are returned as a maximum. To get around +this, you can construct a query which refines your result set. For a +full specification of query parameters relating to collection filtering, +see the `official +docs `__. + +.. code:: php + + $container->objectList(array('prefix' => 'logFile_')); + +Get object +---------- + +To retrieve a specific file from Cloud Files: + +.. code:: php + + $file = $container->getObject('summer_vacation.mp4'); + +Conditional requests +~~~~~~~~~~~~~~~~~~~~ + +You can also perform conditional requests according to `RFC 2616 +specification `__ (§§ 14.24-26). +Supported headers are ``If-Match``, ``If-None-Match``, +``If-Modified-Since`` and ``If-Unmodified-Since``. + +So, to retrieve a file's contents only if it's been recently changed + +.. code:: php + + $file = $container->getObject('error_log.txt', array( + 'If-Modified-Since' => 'Tue, 15 Nov 1994 08:12:31 GMT' + )); + + if ($file->getContentLength()) { + echo 'Has been changed since the above date'; + } else { + echo 'Has not been changed'; + } + +Retrieve a file only if it has NOT been modified (and expect a 412 on +failure): + +:: + + use Guzzle\Http\Exception\ClientErrorResponseException; + + try { + $oldImmutableFile = $container->getObject('payroll_2001.xlsx', array( + 'If-Unmodified-Since' => 'Mon, 31 Dec 2001 23:00:00 GMT' + )); + } catch (ClientErrorResponseException $e) { + echo 'This file has been modified...'; + } + +Finally, you can specify a range - which will return a subset of bytes +from the file specified. To return the last 20B of a file: + +.. code:: php + + $snippet = $container->getObject('output.log', array('range' => 'bytes=-20')); + +Update an existing object +------------------------- + +Updating content is easy: + +.. code:: php + + $file->setContent(fopen('/path/to/new/content', 'r+')); + $file->update(); + +Bear in mind that updating a file name will result in a new file being +generated (under the new name). You will need to delete the old file. + +Copy object +----------- + +To copy a file to another location, you need to specify a string-based +destination path: + +.. code:: php + + $object->copy('/container_2/new_object_name'); + +Delete object +------------- + +.. code:: php + + $object->delete(); + +Get object metadata +------------------- + +You can fetch just the object metadata without fetching the full +content: + +.. code:: php + + $container->getPartialObject('summer_vacation.mp4'); + +In order to access the metadata on a partial or complete object, use: + +.. code:: php + + $object->getMetadata(); + +You can turn a partial object into a full object to get the content +after looking at the metadata: + +.. code:: php + + $object->refresh(); + +You can also update to get the latest metadata: + +.. code:: php + + $object->retrieveMetadata(); + +Update object metadata +---------------------- + +Similarly, with setting metadata there are two options: you can update +the metadata values of the local object (i.e. no HTTP request) if you +anticipate you'll be executing one soon (an update operation for +example): + +.. code:: php + + // There's no need to execute a HTTP request, because we'll soon do one anyway for the update operation + $object->setMetadata(array( + 'Author' => 'Hemingway' + )); + + // ... code here + + $object->update(); + +Alternatively, you can update the API straight away - so that everything +is retained: + +.. code:: php + + $object->saveMetadata(array( + 'Author' => 'Hemingway' + )); + +Please be aware that these methods override and wipe existing values. If +you want to append values to your metadata, use the correct method: + +.. code:: php + + $metadata = $object->appendToMetadata(array( + 'Author' => 'Hemingway' + )); + + $object->saveMetadata($metadata); + +Extract archive +--------------- + +CloudFiles provides you the ability to extract uploaded archives to +particular destinations. The archive will be extracted and its contents +will populate the particular area specified. To upload file (which might +represent a directory structure) into a particular container: + +.. code:: php + + use OpenCloud\ObjectStore\Constants\UrlType; + + $service->bulkExtract('container_1', fopen('/home/jamie/files.tar.gz','r'), UrlType::TAR_GZ); + +You can also omit the container name (i.e. provide an empty string as +the first argument). If you do this, the API will create the containers +necessary to house the extracted files - this is done based on the +filenames inside the archive. + +Bulk delete +----------- + +Bulk delete a set of paths: + +.. code:: php + + $pathsToBeDeleted = array('/container_1/old_file', '/container_2/notes.txt', '/container_1/older_file.log'); + + $service->bulkDelete($pathsToBeDeleted); + diff --git a/doc/services/object-store/README.md.rst b/doc/services/object-store/README.md.rst new file mode 100644 index 000000000..01cf26733 --- /dev/null +++ b/doc/services/object-store/README.md.rst @@ -0,0 +1,86 @@ +Object Store +============ + +**Object Store** is an object-based storage system that stores content +and metadata as objects in a cloud. + +Specifically, a cloud is made up of one or more regions. Each region can +have several **containers**, created by a user. Each container can +container several **objects** (sometimes referred to as files), uploaded +by the user. + +Getting started +--------------- + +1. Instantiate an OpenStack or Rackspace client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Choose one of the following two options: + +- If you are working with a vanilla OpenStack cloud, instantiate an + ``OpenCloud\OpenStack`` client as shown below. + + .. code:: php + + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'password' => '' + )); + +- If you are working with the Rackspace cloud, instantiate a + ``OpenCloud\Rackspace`` client as shown below. + + .. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +2. Obtain an Object Store service object from the client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $region = 'DFW'; + $objectStoreService = $client->objectStoreService(null, $region); + +In the example above, you are connecting to the ``DFW`` region of the +cloud. Any containers and objects created with this +``$objectStoreService`` instance will be stored in that cloud region. + +3. Create a container for your objects (also referred to as files). +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $container = $objectStoreService->createContainer('logos'); + + **Note:** when working with names that contain non-standard + alphanumerical characters (such as spaces or non-English + characters), you must ensure they are encoded with + ```urlencode`` `__ before passing them in + +4. Upload an object to the container. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $localFileName = '/path/to/local/php-elephant.jpg'; + $remoteFileName = 'php-elephant.jpg'; + + $fileData = fopen($localFileName, 'r'); + $container->uploadObject($remoteFileName, $fileData); + +[ `Get the executable PHP script for this +example `__ ] + +Next steps +---------- + +There is a lot more you can do with containers and objects. See the +`complete user guide to the Object Store service `__. diff --git a/doc/services/object-store/USERGUIDE.md.rst b/doc/services/object-store/USERGUIDE.md.rst new file mode 100644 index 000000000..d9732ea36 --- /dev/null +++ b/doc/services/object-store/USERGUIDE.md.rst @@ -0,0 +1,900 @@ +The Complete User Guide to the Object Store Service +=================================================== + +**Object Store** is an object-based storage system that stores content +and metadata as objects in a cloud. + +Prerequisites +------------- + +Client +~~~~~~ + +To use the object store service, you must first instantiate a +``OpenStack`` or ``Rackspace`` client object. + +- If you are working with a vanilla OpenStack cloud, instantiate an + ``OpenCloud\OpenStack`` client as shown below. + + .. code:: php + + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'apiKey' => '' + )); + +- If you are working with the Rackspace cloud, instantiate a + ``OpenCloud\Rackspace`` client as shown below. + + .. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +Object Store Service +~~~~~~~~~~~~~~~~~~~~ + +All operations on the object store are done via an object store service +object. + +.. code:: php + + $region = 'DFW'; + $objectStoreService = $client->objectStoreService(null, $region); + +In the example above, you are connecting to the ``DFW`` region of the +cloud. Any containers and objects created with this +``$objectStoreService`` instance will be stored in that cloud region. + +Containers +---------- + +A **container** defines a namespace for **objects**. An object with the +same name in two different containers represents two different objects. + +For example, you may create a container called ``logos`` to hold all the +image files for your blog. + +A container may contain zero or more objects in it. + + **Note:** when working with names that contain non-standard + alphanumerical characters (such as spaces or non-English + characters), you must ensure they are encoded with + ```urlencode`` `__ before passing them in + +Create Container +~~~~~~~~~~~~~~~~ + +.. code:: php + + $container = $objectStoreService->createContainer('logos'); + +[ `Get the executable PHP script for this +example `__ ] + +Get Container Details +~~~~~~~~~~~~~~~~~~~~~ + +You can retrieve a single container's details by using its name. An +instance of ``OpenCloud\ObjectStore\Resource\Container`` is returned. + +.. code:: php + + $container = $objectStoreService->getContainer('logos'); + + /** @var $container OpenCloud\ObjectStore\Resource\Container **/ + +[ `Get the executable PHP script for this +example `__ ] + +List Containers +~~~~~~~~~~~~~~~ + +You can retrieve a list of all your containers. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $containers = $objectStoreService->listContainers(); + foreach ($containers as $container) { + /** @var $container OpenCloud\ObjectStore\Resource\Container **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Set or Update Container Metadata +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can set metadata on a container. + +.. code:: php + + $container->saveMetadata(array( + 'author' => 'John Doe' + )); + +[ `Get the executable PHP script for this +example `__ ] + +Get Container Metadata +~~~~~~~~~~~~~~~~~~~~~~ + +You can retrieve the metadata for a container. + +.. code:: php + + $containerMetadata = $container->getMetadata(); + +[ `Get the executable PHP script for this +example `__ ] + +Delete Container +~~~~~~~~~~~~~~~~ + +When you no longer have a need for the container, you can remove it. + +If the container is empty (that is, it has no objects in it), you can +remove it as shown below: + +.. code:: php + + $container->delete(); + +[ `Get the executable PHP script for this +example `__ ] + +If the container is not empty (that is, it has objects in it), you have +two choices in how to remove it: + +- `Individually remove each object <#delete-object>`__ in the + container, then remove the container itself as shown above, or + +- Remove the container and all the objects within it as shown below: + + .. code:: php + + $container->delete(true); + + [ `Get the executable PHP script for this + example `__ ] + +Get Object Count +~~~~~~~~~~~~~~~~ + +You can quickly find out how many objects are in a container. + +.. code:: php + + $containerObjectCount = $container->getObjectCount(); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, ``$containerObjectCount`` will contain the number +of objects in the container represented by ``$container``. + +Get Bytes Used +~~~~~~~~~~~~~~ + +You can quickly find out the space used by a container, in bytes. + +.. code:: php + + $containerSizeInBytes = $container->getBytesUsed(); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, ``$containerSizeInBytes`` will contain the space +used, in bytes, by the container represented by ``$container``. + +Container Quotas +~~~~~~~~~~~~~~~~ + +Set Quota for Number of Objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can set a quota for the maximum number of objects that may be stored +in a container. + +.. code:: php + + $maximumNumberOfObjectsAllowedInContainer = 25; + $container->setCountQuota($maximumNumberOfObjectsAllowedInContainer); + +[ `Get the executable PHP script for this +example `__ ] + +Set Quota for Total Size of Objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can set a quota for the maximum total space (in bytes) used by +objects in a container. + +.. code:: php + + use OpenCloud\Common\Constants\Size; + + $maximumTotalSizeOfObjectsInContainer = 5 * Size::GB; + $container->setBytesQuota($maximumTotalSizeOfObjectsInContainer); + +[ `Get the executable PHP script for this +example `__ ] + +Get Quota for Number of Objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can retrieve the quota for the maximum number of objects that may be +stored in a container. + +.. code:: php + + $maximumNumberOfObjectsAllowedInContainer = $container->getCountQuota(); + +[ `Get the executable PHP script for this +example `__ ] + +Get Quota for Total Size of Objects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +You can retrieve the quota for the maximum total space (in bytes) used +by objects in a container. + +.. code:: php + + $maximumTotalSizeOfObjectsAllowedInContainer = $container->getBytesQuota(); + +[ `Get the executable PHP script for this +example `__ ] + +Objects +------- + +An **object** (sometimes referred to as a file) is the unit of storage +in an Object Store. An object is a combination of content (data) and +metadata. + +For example, you may upload an object named ``php-elephant.jpg``, a JPEG +image file, to the ``logos`` container. Further, you may assign metadata +to this object to indicate that the author of this object was someone +named Jane Doe. + + **Note:** when working with names that contain non-standard + alphanumerical characters (such as spaces or non-English + characters), you must ensure they are encoded with + ```urlencode`` `__ before passing them in + +Upload Object +~~~~~~~~~~~~~ + +Once you have created a container, you can upload objects to it. + +.. code:: php + + $localFileName = '/path/to/local/php-elephant.jpg'; + $remoteFileName = 'php-elephant.jpg'; + + $fileData = fopen($localFileName, 'r'); + $container->uploadObject($remoteFileName, $fileData); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, an image file from the local filesystem +(``path/to/local/php-elephant.jpg``) is uploaded to a container in the +Object Store. + +Note that while we call ``fopen`` to open the file resource, we do not +call ``fclose`` at the end. The file resource is automatically closed +inside the ``uploadObject`` call. + +It is also possible to upload an object and associate metadata with it. + +.. code:: php + + use OpenCloud\ObjectStore\Resource\DataObject; + + $localFileName = '/path/to/local/php-elephant.jpg'; + $remoteFileName = 'php-elephant.jpg'; + $metadata = array('author' => 'Jane Doe'); + + $customHeaders = array(); + $metadataHeaders = DataObject::stockHeaders($metadata); + $allHeaders = $customHeaders + $metadataHeaders; + + $fileData = fopen($localFileName, 'r'); + $container->uploadObject($remoteFileName, $fileData, $allHeaders); + +[ `Get the executable PHP script for this +example `__ ] + +Note that while we call ``fopen`` to open the file resource, we do not +call ``fclose`` at the end. The file resource is automatically closed +inside the ``uploadObject`` call. + +Pseudo-hierarchical Folders +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Although you cannot nest directories in an Object Store, you can +simulate a hierarchical structure within a single container by adding +forward slash characters (``/``) in the object name. + +.. code:: php + + $localFileName = '/path/to/local/php-elephant.jpg'; + $remoteFileName = 'languages/php/elephant.jpg'; + + $fileData = fopen($localFileName, 'r'); + $container->uploadObject($remoteFileName, $fileData); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, an image file from the local filesystem +(``/path/to/local/php-elephant.jpg``) is uploaded to a container in the +Object Store. Within that container, the filename is +``languages/php/elephant.jpg``, where ``languages/php/`` is a +pseudo-hierarchical folder hierarchy. + +Note that while we call ``fopen`` to open the file resource, we do not +call ``fclose`` at the end. The file resource is automatically closed +inside the ``uploadObject`` call. + +Upload Multiple Objects +^^^^^^^^^^^^^^^^^^^^^^^ + +You can upload more than one object at a time to a container. + +.. code:: php + + $objects = array( + array( + 'name' => 'php-elephant.jpg', + 'path' => '/path/to/local/php-elephant.jpg' + ), + array( + 'name' => 'python-snake.jpg', + 'path' => '/path/to/local/python-snake.jpg' + ), + a + ); + + $container->uploadObjects($objects); + +[ `Get the executable PHP script for this +example `__ ] + +In the above example, the contents of two files present on the local +filesystem are uploaded as objects to the container referenced by +``$container``. + +Instead of specifying the ``path`` key in an element of the ``$objects`` +array, you can specify a ``body`` key whose value is a string or a +stream representation. + +Finally, you can pass headers as the second parameter to the +``uploadObjects`` method. These headers will be applied to every object +that is uploaded. + +:: + + $metadata = array('author' => 'Jane Doe'); + + $customHeaders = array(); + $metadataHeaders = DataObject::stockHeaders($metadata); + $allHeaders = $customHeaders + $metadataHeaders; + + $container->uploadObjects($objects, $allHeaders); + +[ `Get the executable PHP script for this +example `__ +] + +In the example above, every object referenced within the ``$objects`` +array will be uploaded with the same metadata. + +Large Objects +~~~~~~~~~~~~~ + +If you want to upload objects larger than 5GB in size, you must use a +different upload process. + +.. code:: php + + $options = array( + 'name' => 'san_diego_vacation_video.mp4', + 'path' => '/path/to/local/videos/san_diego_vacation.mp4' + ); + $objectTransfer = $container->setupObjectTransfer($options); + $objectTransfer->upload(); + +[ `Get the executable PHP script for this +example `__ ] + +The process shown above will automatically partition your large object +into small chunks and upload them concurrently to the container +represented by ``$container``. + +You can tune the parameters of this process by specifying additional +options in the ``$options`` array. Here is a complete listing of keys +that can be specified in the ``$options`` array: + ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ +| Key name | Description | Data Type | Required? | Default Value | Example | ++===================+================================================================================================================================================================================================================================================================================================================+=================================================+=================================================+==================================================+====================================================+ +| ``name`` | Name of large object in container | String | Yes | - | ``san_diego_vacation_video.mp4`` | ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ +| ``path`` | Path to file containing object data on local filesystem | String | One of ``path`` or ``body`` must be specified | - | ``/path/to/local/videos/san_diego_vacation.mp4`` | ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ +| ``body`` | String or stream representation of object data | String \| Stream | One of ``path`` or ``body`` must be specified | - | ``... lots of data ...`` | ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ +| ``metadata`` | Metadata for the object | Associative array of metadata key-value pairs | No | ``array()`` | ``array( "Author" => "Jane Doe" )`` | ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ +| ``partSize`` | The size, in bytes, of each chunk that the large object is partitioned into prior to uploading | Integer | No | ``1073741824`` (1GB) | ``52428800`` (50MB) | ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ +| ``concurrency`` | The number of concurrent transfers to execute as part of the upload | Integer | No | ``1`` (no concurrency; upload chunks serially) | ``10`` | ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ +| ``progress`` | A `callable function or method `__ which is called to report progress of the the upload. See ```CURLOPT_PROGRESSFUNCTION`` documentation `__ for details on parameters passed to this callable function or method. | String (callable function or method name) | No | None | ``reportProgress`` | ++-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ + +Auto-extract Archive Files +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can upload a tar archive file and have the Object Store service +automatically extract it into a container. + +.. code:: php + + use OpenCloud\ObjectStore\Constants\UrlType; + + $localArchiveFileName = '/path/to/local/image_files.tar.gz'; + $remotePath = 'images/'; + + $fileData = fopen($localArchiveFileName, 'r'); + $objectStoreService->bulkExtract($remotePath, $fileData, UrlType::TAR_GZ); + +[ `Get the executable PHP script for this +example `__ ] + +In the above example, a local archive file named ``image_files.tar.gz`` +is uploaded to an Object Store container named ``images`` (defined by +the ``$remotePath`` variable). + +Note that while we call ``fopen`` to open a file resource, we do not +call ``fclose`` at the end. The file resource is automatically closed +inside the ``bulkExtract`` call. + +The third parameter to ``bulkExtract`` is the type of the archive file +being uploaded. The acceptable values for this are: + +- ``UrlType::TAR`` for tar archive files, *or*, +- ``UrlType:TAR_GZ`` for tar archive files that are compressed with + gzip, *or* +- ``UrlType::TAR_BZ`` for tar archive file that are compressed with + bzip + +Note that the value of ``$remotePath`` could have been a +(pseudo-hierarchical folder)[#pseudo-hierarchical-folders] such as +``images/blog`` as well. + +List Objects in a Container +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can list all the objects stored in a container. An instance of +``OpenCloud\Common\Collection\PaginatedIterator`` is returned. + +.. code:: php + + $objects = $container->objectList(); + foreach ($objects as $object) { + /** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +You can list only those objects in the container whose names start with +a certain prefix. + +.. code:: php + + $options = array( + 'prefix' => 'php' + ); + + $objects = $container->objectList($options); + +[ `Get the executable PHP script for this +example `__ ] + +In general, the ``objectList()`` method described above takes an +optional parameter (``$options`` in the example above). This parameter +is an associative array of various options. Here is a complete listing +of keys that can be specified in the ``$options`` array: + ++------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ +| Key name | Description | Data Type | Required? | Default Value | Example | ++==================+=============================================================================+=============+=============+=================+=========================+ +| ``prefix`` | Given a string x, limits the results to object names beginning with x. | String | No | | ``php`` | ++------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ +| ``limit`` | Given an integer n, limits the number of results to at most n values. | Integer | No | | 10 | ++------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ +| ``marker`` | Given a string x, returns object names greater than the specified marker. | String | No | | ``php-elephant.jpg`` | ++------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ +| ``end_marker`` | Given a string x, returns object names less than the specified marker. | String | No | | ``python-snakes.jpg`` | ++------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ + +Retrieve Object +~~~~~~~~~~~~~~~ + +You can retrieve an object and its metadata, given the object's +container and name. + +.. code:: php + + $objectName = 'php-elephant.jpg'; + $object = $container->getObject($objectName); + + /** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ + + $objectContent = $object->getContent(); + + /** @var $objectContent Guzzle\Http\EntityBody **/ + + // Write object content to file on local filesystem. + $objectContent->rewind(); + $stream = $objectContent->getStream(); + $localFilename = tempnam("/tmp", 'php-opencloud-'); + file_put_contents($localFilename, $stream); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, ``$object`` is the object named +``php-elephant.jpg`` in the container represented by ``$container``. +Further, ``$objectContent`` represents the contents of the object. It is +of type +```Guzzle\Http\EntityBody`` `__. + +Retrieve Object Metadata +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can retrieve just an object's metadata without retrieving its +contents. + +.. code:: php + + $objectName = 'php-elephant.jpg'; + $object = $container->getPartialObject($objectName); + $objectMetadata = $object->getMetadata(); + + /** @var $objectMetadata \OpenCloud\Common\Metadata **/ + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, while ``$object`` is an instance of +``OpenCloud\ObjectStore\Resource\DataObject``, that instance is only +partially populated. Specifically, only properties of the instance +relating to object metadata are populated. + +Temporary URLs +~~~~~~~~~~~~~~ + +The Temporary URL feature allows you to create limited-time Internet +addresses that allow you to grant limited access to your Object Store +account. Using this feature, you can allow others to retrieve or place +objects in your Object Store account for a specified amount of time. +Access to the temporary URL is independent of whether or not your +account is `CDN-enabled <#cdn-containers>`__. Even if you do not +CDN-enable a container, you can still grant temporary public access +through a temporary URL. + +First, you must set the temporary URL secret on your account. This is a +one-time operation; you only need to perform it the very first time you +wish to use the temporary URLs feature. + +.. code:: php + + $account->setTempUrlSecret(); + +[ `Get the executable PHP script for this +example `__ ] + +Note that this operation is carried out on ``$account``, which is an +instance of ``OpenCloud\ObjectStore\Resource\Account``, a class +representing `your object store account <#accounts>`__. + +The above operation will generate a random secret and set it on your +account. Instead of a random secret, if you wish to provide a secret, +you can supply it as a parameter to the ``setTempUrlSecret`` method. + +.. code:: php + + $account->setTempUrlSecret(''); + +[ `Get the executable PHP script for this +example `__ +] + +Once a temporary URL secret has been set on your account, you can +generate a temporary URL for any object in your Object Store. + +.. code:: php + + $expirationTimeInSeconds = 3600; // one hour from now + $httpMethodAllowed = 'GET'; + $tempUrl = $object->getTemporaryUrl($expirationTimeInSeconds, $httpMethodAllowed); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, a temporary URL for the object is generated. This +temporary URL will provide public access to the object for an hour (3600 +seconds), as specified by the ``$expirationTimeInSeconds`` variable. +Further, only GET HTTP methods will be allowed on this URL, as specified +by the ``$httpMethodAllowed`` variable. The other value allowed for the +``$httpMethodAllowed`` variable would be ``PUT``. + +You can also retrieve the temporary URL secret that has been set on your +account. + +.. code:: php + + $tempUrlSecret = $account->getTempUrlSecret(); + +[ `Get the executable PHP script for this +example `__ ] + +Update Object +~~~~~~~~~~~~~ + +You can update an object's contents (as opposed to `updating its +metadata <#update-object-metadata>`__) by simply re-\ `uploading the +object <#upload-object>`__ to its container using the same object name +as before. + +Update Object Metadata +~~~~~~~~~~~~~~~~~~~~~~ + +You can update an object's metadata after it has been uploaded to a +container. + +.. code:: php + + $object->saveMetadata(array( + 'author' => 'John Doe' + )); + +[ `Get the executable PHP script for this +example `__ ] + +Copy Object +~~~~~~~~~~~ + +You can copy an object from one container to another, provided the +destination container already exists. + +.. code:: php + + $object->copy('logos_copy/php.jpg'); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, both the name of the destination container +(``logos_copy``)and the name of the destination object (``php.jpg``) +have to be specified, separated by a ``/``. + +Delete Object +~~~~~~~~~~~~~ + +When you no longer need an object, you can delete it. + +.. code:: php + + $object->delete(); + +[ `Get the executable PHP script for this +example `__ ] + +Bulk Delete +~~~~~~~~~~~ + +While you can delete individual objects as shown above, you can also +delete objects and empty containers in bulk. + +.. code:: php + + $objectStoreService->bulkDelete(array( + 'logos/php-elephant.png', + 'logos/python-snakes.png', + 'some_empty_container' + )); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, two objects (``some_container/object_a.png``, +``some_other_container/object_z.png``) and one empty container +(``some_empty_container``) are all being deleted in bulk via a single +command. + +CDN Containers +-------------- + +Note: The functionality described in this section is available only on +the Rackspace cloud. It will not work as described when working with a +vanilla OpenStack cloud. + +Any container can be converted to a CDN-enabled container. When this is +done, the objects within the container can be accessed from anywhere on +the Internet via a URL. + +Enable CDN Container +~~~~~~~~~~~~~~~~~~~~ + +To take advantage of CDN capabilities for a container and its objects, +you must CDN-enable that container. + +.. code:: php + + $container->enableCdn(); + +[ `Get the executable PHP script for this +example `__ ] + +Public URLs +~~~~~~~~~~~ + +Once you have CDN-enabled a container, you can retrieve a +publicly-accessible URL for any of its objects. There are four types of +publicly-accessible URLs for each object. Each type of URL is meant for +a different purpose. The sections below describe each of these URL types +and how to retrieve them. + +HTTP URL +^^^^^^^^ + +You can use this type of URL to access the object over HTTP. + +:: + + $httpUrl = $object->getPublicUrl(); + +[ `Get the executable PHP script for this +example `__ ] + +Secure HTTP URL +^^^^^^^^^^^^^^^ + +You can use this type of URL to access the object over HTTP + TLS/SSL. + +:: + + use OpenCloud\ObjectStore\Constants\UrlType; + + $httpsUrl = $object->getPublicUrl(UrlType::SSL); + +[ `Get the executable PHP script for this +example `__ ] + +Streaming URL +^^^^^^^^^^^^^ + +You can use this type of URL to stream a video or audio object using +Adobe's HTTP Dynamic Streaming. + +:: + + use OpenCloud\ObjectStore\Constants\UrlType; + + $streamingUrl = $object->getPublicUrl(UrlType::STREAMING); + +[ `Get the executable PHP script for this +example `__ ] + +IOS Streaming URL +^^^^^^^^^^^^^^^^^ + +You can use this type of URL to stream an audio or video object to an +iOS device. + +:: + + use OpenCloud\ObjectStore\Constants\UrlType; + + $iosStreamingUrl = $object->getPublicUrl(UrlType::IOS_STREAMING); + +[ `Get the executable PHP script for this +example `__ ] + +Update CDN Container TTL +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can update the TTL of a CDN-enabled container. + +.. code:: php + + $cdnContainer = $container->getCdn(); + $cdnContainer->setTtl(); + +[ `Get the executable PHP script for this +example `__ ] + +Disable CDN Container +~~~~~~~~~~~~~~~~~~~~~ + +If you no longer need CDN capabilities for a container, you can disable +them. + +.. code:: php + + $container->disableCdn(); + +[ `Get the executable PHP script for this +example `__ ] + +Accounts +-------- + +An **account** defines a namespace for **containers**. An account can +have zero or more containers in it. + +Retrieve Account +~~~~~~~~~~~~~~~~ + +You must retrieve the account before performing any operations on it. + +.. code:: php + + $account = $objectStoreService->getAccount(); + +Get Container Count +~~~~~~~~~~~~~~~~~~~ + +You can quickly find out how many containers are in your account. + +.. code:: php + + $accountContainerCount = $account->getContainerCount(); + +[ `Get the executable PHP script for this +example `__ ] + +Get Object Count +~~~~~~~~~~~~~~~~ + +You can quickly find out how many objects are in your account. + +.. code:: php + + $accountObjectCount = $account->getObjectCount(); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, ``$accountObjectCount`` will contain the number of +objects in the account represented by ``$account``. + +Get Bytes Used +~~~~~~~~~~~~~~ + +You can quickly find out the space used by your account, in bytes. + +.. code:: php + + $accountSizeInBytes = $account->getBytesUsed(); + +[ `Get the executable PHP script for this +example `__ ] + +In the example above, ``$accountSizeInBytes`` will contain the space +used, in bytes, by the account represented by ``$account``. diff --git a/doc/services/object-store/index.rst b/doc/services/object-store/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/orchestration/README.md.rst b/doc/services/orchestration/README.md.rst new file mode 100644 index 000000000..1a983d187 --- /dev/null +++ b/doc/services/orchestration/README.md.rst @@ -0,0 +1,98 @@ +Orchestration +============= + +**Orchestration** is a service that can be used to create and manage +cloud resources. Examples of such resources are databases, load +balancers, servers and software installed on them. + +Concepts +-------- + +To use the Orchestration service effectively, you should understand +several key concepts: + +- **Template**: An Orchestration template is a JSON or YAML document + that describes how a set of resources should be assembled to produce + a working deployment. The template specifies what resources should be + used, what attributes of these resources are parameterized and what + information is output to the user when a template is instantiated. + +- **Resource**: A resource is a template artifact that represents some + component of your desired architecture (a Cloud Server, a group of + scaled Cloud Servers, a load balancer, some configuration management + system, and so forth). + +- **Stack**: A stack is a running instance of a template. When a stack + is created, the resources specified in the template are created. + +Getting started +--------------- + +1. Instantiate an OpenStack or Rackspace client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use the Orchestration service, you must first instantiate a +``OpenStack`` or ``Rackspace`` client object. + +- If you are working with an OpenStack cloud, instantiate an + ``OpenCloud\OpenStack`` client as follows: + + .. code:: php + + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'password' => '' + )); + +- If you are working with the Rackspace cloud, instantiate a + ``OpenCloud\Rackspace`` client as follows: + + .. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +2. Obtain an Orchestration service object from the client. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +All Orchestration operations are done via an *orchestration service +object*. To instantiate this object, call the ``orchestrationService`` +method on the ``$client`` object as shown in the following example: + +.. code:: php + + $region = ''; + $orchestrationService = $client->orchestrationService(null, $region); + +Any stacks and resources created with this ``$orchestrationService`` +instance will be stored in the cloud region specified by ``$region``. + +3. Create a stack from a template. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: php + + $stack = $orchestrationService->createStack(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +[ `Get the executable PHP script for this +example `__ ] + +Next steps +---------- + +Once you have created a stack, there is more you can do with it. See +`complete user guide for orchestration `__. diff --git a/doc/services/orchestration/USERGUIDE.md.rst b/doc/services/orchestration/USERGUIDE.md.rst new file mode 100644 index 000000000..98bd51db7 --- /dev/null +++ b/doc/services/orchestration/USERGUIDE.md.rst @@ -0,0 +1,672 @@ +Complete User Guide for the Orchestration Service +================================================= + +Orchestration is a service that you can use to create and manage cloud +resources such as databases, load balancers, and servers, and the +software installed on servers. + +Table of Contents +----------------- + +- `Concepts <#concepts>`__ +- `Prerequisites <#prerequisites>`__ +- `Client <#client>`__ +- `Orchestration service <#orchestration-service>`__ +- `Templates <#templates>`__ +- `Validate template <#validate-template>`__ + + - `Validate a template from a + file <#validate-a-template-from-a-file>`__ + - `Validate Template from URL <#validate-template-from-url>`__ + +- `Stacks <#stacks>`__ +- `Preview stack <#preview-stack>`__ + + - `Preview a stack from a template + file <#preview-a-stack-from-a-template-file>`__ + - `Preview a stack from a template + URL <#preview-a-stack-from-a-template-url>`__ + +- `Create stack <#create-stack>`__ + + - `Create a stack from a template + file <#create-a-stack-from-a-template-file>`__ + - `Create a stack from a template + URL <#create-a-stack-from-a-template-url>`__ + +- `List stacks <#list-stacks>`__ +- `Get stack <#get-stack>`__ +- `Get stack template <#get-stack-template>`__ +- `Update stack <#update-stack>`__ + + - `Update a stack from a template + file <#update-a-stack-from-a-template-file>`__ + - `Update Stack from Template + URL <#update-stack-from-template-url>`__ + +- `Delete stack <#delete-stack>`__ +- `Abandon Stack <#abandon-stack>`__ +- `Adopt stack <#adopt-stack>`__ +- `Stack resources <#stack-resources>`__ +- `List stack resources <#list-stack-resources>`__ +- `Get stack resource <#get-stack-resource>`__ +- `Get stack resource metadata <#get-stack-resource-metadata>`__ +- `Stack resource events <#stack-resource-events>`__ +- `List stack events <#list-stack-events>`__ +- `List stack resource events <#list-stack-resource-events>`__ +- `Get stack resource event <#get-stack-resource-event>`__ +- `Resource types <#resource-types>`__ +- `List resource types <#list-resource-types>`__ +- `Get resource type <#get-resource-type>`__ +- `Get resource type template <#get-resource-type-template>`__ +- `Build info <#build-info>`__ +- `Get build info <#get-build-info>`__ + +Concepts +-------- + +To use the Orchestration service effectively, you should understand the +following key concepts: + +- **Template**: A JSON or YAML document that describes how a set of + resources should be assembled to produce a working deployment. The + template specifies the resources to use, the attributes of these + resources that are parameterized and the information that is sent to + the user when a template is instantiated. + +- **Resource**: Some component of your architecture (a cloud server, a + group of scaled cloud servers, a load balancer, some configuration + management system, and so on) that is defined in a template. + +- **Stack**: A running instance of a template. When a stack is created, + the resources specified in the template are created. + +Prerequisites +------------- + +Client +~~~~~~ + +To use the Orchestration service, you must first instantiate a +``OpenStack`` or ``Rackspace`` client object. + +- If you are working with an OpenStack cloud, instantiate an + ``OpenCloud\OpenStack`` client as follows: + + .. code:: php + + use OpenCloud\OpenStack; + + $client = new OpenStack('', array( + 'username' => '', + 'password' => '' + )); + +- If you are working with the Rackspace cloud, instantiate a + ``OpenCloud\Rackspace`` client as follows: + + .. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => '', + 'apiKey' => '' + )); + +Orchestration service +~~~~~~~~~~~~~~~~~~~~~ + +All Orchestration operations are done via an *orchestration service +object*. To instantiate this object, call the ``orchestrationService`` +method on the ``$client`` object. This method takes two arguments: + ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+--------------------------+ +| Position | Description | Data type | Required? | Default value | Example value | ++============+=============================================================+=============+=============+====================================================+==========================+ +| 1 | Name of the service, as it appears in the service catalog | String | No | ``null``; automatically determined when possible | ``cloudOrchestration`` | ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+--------------------------+ +| 2 | Cloud region | String | Yes | - | ``DFW`` | ++------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+--------------------------+ + +.. code:: php + + $region = ''; + $orchestrationService = $client->orchestrationService(null, $region); + +Any stacks and resources created with this ``$orchestrationService`` +instance will be stored in the cloud region specified by ``$region``. + +Templates +--------- + +An Orchestration template is a JSON or YAML document that describes how +a set of resources should be assembled to produce a working deployment +(known as a `stack <#stacks>`__). The template specifies the resources +to use, the attributes of these resources that are parameterized and the +information that is sent to the user when a template is instantiated. + +Validate template +~~~~~~~~~~~~~~~~~ + +Before you use a template to create a stack, you might want to validate +it. + +Validate a template from a file +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored on your local computer as a JSON or YAML +file, you can validate it as shown in the following example: + +.. code:: php + + use OpenCloud\Common\Exceptions\InvalidTemplateError; + + try { + $orchestrationService->validateTemplate(array( + 'template' => file_get_contents(__DIR__ . '/lamp.yaml') + )); + } catch (InvalidTemplateError $e) { + // Use $e->getMessage() for explanation of why template is invalid + } + +[ `Get the executable PHP script for this +example `__ +] + +Validate Template from URL +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can validate it as shown in the +following example: + +.. code:: php + + use OpenCloud\Common\Exceptions\InvalidTemplateError; + + try { + $orchestrationService->validateTemplate(array( + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml' + )); + } catch (InvalidTemplateError $e) { + // Use $e->getMessage() for explanation of why template is invalid + } + +[ `Get the executable PHP script for this +example `__ +] + +Stacks +------ + +A stack is a running instance of a template. When a stack is created, +the `resources <#stack-resources>`__ specified in the template are +created. + +Preview stack +~~~~~~~~~~~~~ + +Before you create a stack from a template, you might want to see what +that stack will look like. This is called *previewing the stack*. + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+=====================================================================================================================================================================================================================+=========================================================================================================================+=======================================+=================+=================================================================================================+ +| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters | Yes | - | ``simple-lamp-setup`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of the template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters. For example, see the parameters in `this template section `__ | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ + +Preview a stack from a template file +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to preview a stack as shown in the following +example: + +.. code:: php + + $stack = $orchestrationService->previewStack(array( + 'name' => 'simple-lamp-setup', + 'template' => file_get_contents(__DIR__ . '/lamp.yml'), + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ) + )); + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + +[ `Get the executable PHP script for this +example `__ +] + +Preview a stack from a template URL +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to preview a stack as shown +in the following example: + +.. code:: php + + $stack = $orchestrationService->previewStack(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ) + )); + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + +[ `Get the executable PHP script for this +example `__ +] + +Create stack +~~~~~~~~~~~~ + +You can create a stack from a template. + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+====================================================================+==========================================================================================================================+=======================================+=================+=================================================================================================+ +| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters. | Yes | - | ``simple-lamp-setup`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('server_hostname' => 'web01')`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``timeoutMins`` | Duration, in minutes, after which stack creation should time out | Integer | Yes | - | 5 | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ + +Create a stack from a template file +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to create a stack as shown in the following +example: + +.. code:: php + + $stack = $orchestrationService->createStack(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + +[ `Get the executable PHP script for this +example `__ +] + +Create a stack from a template URL +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to create a stack as shown +in the following example: + +.. code:: php + + $stack = $orchestrationService->stack(); + $stack->create(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +[ `Get the executable PHP script for this +example `__ ] + +List stacks +~~~~~~~~~~~ + +You can list all the stacks that you have created as shown in the +following example: + +.. code:: php + + $stacks = $orchestrationService->listStacks(); + foreach ($stacks as $stack) { + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Get stack +~~~~~~~~~ + +You can retrieve a specific stack using its name, as shown in the +following example: + +.. code:: php + + $stack = $orchestrationService->getStack('simple-lamp-setup'); + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + +[ `Get the executable PHP script for this +example `__ ] + +Get stack template +~~~~~~~~~~~~~~~~~~ + +You can retrieve the template used to create a stack. Note that a JSON +string is returned, regardless of whether a JSON or YAML template was +used to create the stack. + +.. code:: php + + $stackTemplate = $stack->getTemplate(); + /** @var $stackTemplate string **/ + +[ `Get the executable PHP script for this +example `__ ] + +Update stack +~~~~~~~~~~~~ + +You can update a running stack. + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+==================================================================+=============================+=======================================+=================+=========================================================================================================+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``timeoutMins`` | Duration, in minutes, after which stack update should time out | Integer | Yes | - | 5 | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ + +Update a stack from a template file +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to update a stack as shown in the following +example: + +.. code:: php + + $stack->update(array( + 'template' => file_get_contents(__DIR__ . '/lamp-updated.yml'), + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + +[ `Get the executable PHP script for this +example `__ +] + +Update Stack from Template URL +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to update a stack as shown +in the following example: + +.. code:: php + + $stack->update(array( + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + +[ `Get the executable PHP script for this +example `__ ] + +Delete stack +~~~~~~~~~~~~ + +If you no longer need a stack and all its resources, you can delete the +stack *and* the resources as shown in the following example: + +.. code:: php + + $stack->delete(); + +[ `Get the executable PHP script for this +example `__ ] + +Abandon Stack +~~~~~~~~~~~~~ + +If you want to delete a stack but preserve all its resources, you can +abandon the stack as shown in the following example: + +.. code:: php + + $abandonStackData = $stack->abandon(); + /** @var $abandonStackData string **/ + + file_put_contents(__DIR__ . '/sample_adopt_stack_data.json', $abandonStackData); + +[ `Get the executable PHP script for this +example `__ ] + +Note that this operation returns data about the abandoned stack as a +string. You can use this data to recreate the stack by using the `adopt +stack <#adopt-stack>`__ operation. + +Adopt stack +~~~~~~~~~~~ + +If you have data from an abandoned stack, you can re-create the stack as +shown in the following example: + +.. code:: php + + $stack = $orchestrationService->adoptStack(array( + 'name' => 'simple-lamp-setup', + 'template' => file_get_contents(__DIR__ . '/lamp.yml'), + 'adoptStackData' => $abandonStackData, + 'timeoutMins' => 5 + )); + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + +[ `Get the executable PHP script for this +example `__ ] + +Stack resources +--------------- + +A stack is made up of zero or more resources such as databases, load +balancers, and servers, and the software installed on servers. + +List stack resources +~~~~~~~~~~~~~~~~~~~~ + +You can list all the resources for a stack as shown in the following +example: + +.. code:: php + + $resources = $stack->listResources(); + foreach ($resources as $resource) { + /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Get stack resource +~~~~~~~~~~~~~~~~~~ + +You can retrieve a specific resource in a stack bt using that resource's +name, as shown in the following example: + +.. code:: php + + $resource = $stack->getResource('load-balancer'); + /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ + +[ `Get the executable PHP script for this +example `__ ] + +Get stack resource metadata +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can retrieve the metadata for a specific resource in a stack as +shown in the following example: + +.. code:: php + + $resourceMetadata = $resource->getMetadata(); + /** @var $resourceMetadata \stdClass **/ + +[ `Get the executable PHP script for this +example `__ ] + +Stack resource events +--------------------- + +Operations on resources within a stack (such as the creation of a +resource) produce events. + +List stack events +~~~~~~~~~~~~~~~~~ + +You can list all of the events for all of the resources in a stack as +shown in the following example: + +.. code:: php + + $stackEvents = $stack->listEvents(); + foreach ($stackEvents as $stackEvent) { + /** @var $stackEvent OpenCloud\Orchestration\Resource\Event **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +List stack resource events +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can list all of the events for a specific resource in a stack as +shown in the following example: + +.. code:: php + + $resourceEvents = $resource->listEvents(); + foreach ($resourceEvents as $resourceEvent) { + /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Get stack resource event +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can retrieve a specific event for a specific resource in a stack, by +using the resource event's ID, as shown in the following example: + +.. code:: php + + $resourceEvent = $resource->getEvent('c1342a0a-59e6-4413-9af5-07c9cae7d729'); + /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ + +[ `Get the executable PHP script for this +example `__ ] + +Resource types +-------------- + +When you define a template, you must use resource types supported by +your cloud. + +List resource types +~~~~~~~~~~~~~~~~~~~ + +You can list all supported resource types as shown in the following +example: + +.. code:: php + + $resourceTypes = $orchestrationService->listResourceTypes(); + foreach ($resourceTypes as $resourceType) { + /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ + } + +[ `Get the executable PHP script for this +example `__ ] + +Get resource type +~~~~~~~~~~~~~~~~~ + +You can retrieve a specific resource type's schema as shown in the +following example: + +.. code:: php + + $resourceType = $orchestrationService->getResourceType('OS::Nova::Server'); + /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ + +[ `Get the executable PHP script for this +example `__ ] + +Get resource type template +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can retrieve a specific resource type's representation as it would +appear in a template, as shown in the following example: + +.. code:: php + + $resourceTypeTemplate = $resourceType->getTemplate(); + /** @var $resourceTypeTemplate string **/ + +[ `Get the executable PHP script for this +example `__ ] + +Build info +---------- + +Get build info +~~~~~~~~~~~~~~ + +You can retrieve information about the current Orchestration service +build as shown in the following example: + +.. code:: php + + $buildInfo = $orchestrationService->getBuildInfo(); + /** @var $resourceType OpenCloud\Orchestration\Resource\BuildInfo **/ + +[ `Get the executable PHP script for this +example `__ ] diff --git a/doc/services/orchestration/index.rst b/doc/services/orchestration/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/queues/Claim.md.rst b/doc/services/queues/Claim.md.rst new file mode 100644 index 000000000..42161536d --- /dev/null +++ b/doc/services/queues/Claim.md.rst @@ -0,0 +1,164 @@ +1. Introduction +--------------- + +A **Claim** is the process of a worker checking out a message to perform +a task. Claiming a message prevents other workers from attempting to +process the same messages. + +2. Setup +-------- + +A Claim is initialized on its parent object, a Queue: + +.. code:: php + + // To initialize an empty object: + $claim = $queue->getClaim(); + + // or retrieve a specific claim: + $claim = $queue->getClaim('51db7067821e727dc24df754'); + +3. Claim messages +----------------- + +3.1 Description +~~~~~~~~~~~~~~~ + +This operation claims a set of messages (up to the value of the limit +parameter) from oldest to newest and skips any messages that are already +claimed. If no unclaimed messages are available, the API returns a +``204 No Content`` message. + +When a client (worker) finishes processing a message, it should delete +the message before the claim expires to ensure that the message is +processed only once. As part of the delete operation, workers should +specify the claim ID (which is best done by simply using the provided +href). If workers perform these actions, then if a claim simply expires, +the server can return an error and notify the worker of the race +condition. This action gives the worker a chance to roll back its own +processing of the given message because another worker can claim the +message and process it. + +The age given for a claim is relative to the server's clock. The claim's +age is useful for determining how quickly messages are getting processed +and whether a given message's claim is about to expire. + +When a claim expires, it is released. If the original worker failed to +process the message, another client worker can then claim the message. + +3.2 Attributes +~~~~~~~~~~~~~~ + +The ``ttl`` attribute specifies how long the server waits before +releasing the claim. The ttl value must be between 60 and 43200 seconds +(12 hours). You must include a value for this attribute in your request. + +The ``grace`` attribute specifies the message grace period in seconds. +The value of grace value must be between 60 and 43200 seconds (12 +hours). You must include a value for this attribute in your request. To +deal with workers that have stopped responding (for up to 1209600 +seconds or 14 days, including claim lifetime), the server extends the +lifetime of claimed messages to be at least as long as the lifetime of +the claim itself, plus the specified grace period. If a claimed message +would normally live longer than the grace period, its expiration is not +adjusted. + +The ``limit`` attribute specifies the number of messages to return, up +to 20 messages. If limit is not specified, limit defaults to 10. The +limit parameter is optional. + +3.3 Code +~~~~~~~~ + +.. code:: php + + use OpenCloud\Common\Constants\Datetime; + + $queue->claimMessages(array( + 'limit' => 15, + 'grace' => 5 * Datetime::MINUTE, + 'ttl' => 5 * Datetime::MINUTE + )); + +4. Query claim +-------------- + +4.1 Description +~~~~~~~~~~~~~~~ + +This operation queries the specified claim for the specified queue. +Claims with malformed IDs or claims that are not found by ID are +ignored. + +4.2 Attributes +~~~~~~~~~~~~~~ + +Claim ID. + +4.3 Code +~~~~~~~~ + +.. code:: php + + $claim = $queue->getClaim('51db7067821e727dc24df754'); + +5. Update claim +--------------- + +5.1 Description +~~~~~~~~~~~~~~~ + +This operation updates the specified claim for the specified queue. +Claims with malformed IDs or claims that are not found by ID are +ignored. + +Clients should periodically renew claims during long-running batches of +work to avoid losing a claim while processing a message. The client can +renew a claim by executing this method on a specific **Claim** and +including a new TTL. The API will then reset the age of the claim and +apply the new TTL. + +5.2 Attributes +~~~~~~~~~~~~~~ + +See section 4.2. + +5.3 Code +~~~~~~~~ + +.. code:: php + + use OpenCloud\Common\Constants\Datetime; + + $claim->update(array( + 'ttl' => 10 * Datetime::MINUTE + )); + +6. Release claim +---------------- + +6.1 Description +~~~~~~~~~~~~~~~ + +This operation immediately releases a claim, making any remaining +undeleted messages that are associated with the claim available to other +workers. Claims with malformed IDs or claims that are not found by ID +are ignored. + +This operation is useful when a worker is performing a graceful +shutdown, fails to process one or more messages, or is taking longer +than expected to process messages, and wants to make the remainder of +the messages available to other workers. + +6.2 Attributes +~~~~~~~~~~~~~~ + +See section 4.2. + +6.3 Code +~~~~~~~~ + +.. code:: php + + $message->delete(); + diff --git a/doc/services/queues/Message.md.rst b/doc/services/queues/Message.md.rst new file mode 100644 index 000000000..ca67e22bb --- /dev/null +++ b/doc/services/queues/Message.md.rst @@ -0,0 +1,257 @@ +1. Introduction +--------------- + +A **Message** is a task, a notification, or any meaningful data that a +producer or publisher sends to the queue. A message exists until it is +deleted by a recipient or automatically by the system based on a TTL +(time-to-live) value. + +2. Setup +-------- + +A message is initialized from its parent object, a Queue: + +.. code:: php + + // Setup an empty object + $message = $queue->getMessage(); + + // or retrieve an existing one + $message = $queue->getMessage(''); + +3. Post message +--------------- + +3.1 Description +~~~~~~~~~~~~~~~ + +This operation posts the specified message or messages. You can submit +up to 10 messages in a single request. + +When posting new messages, you specify only the ``body`` and ``ttl`` for +the message. The API will insert metadata, such as ID and age. + +3.2 Parameters +~~~~~~~~~~~~~~ + +How you pass through the array structure depends on whether you are +executing multiple (3.3.2) or single (3.3.3) posts, but the keys are the +same. + +The ``body`` attribute specifies an arbitrary document that constitutes +the body of the message being sent. The size of this body is limited to +256 KB, excluding whitespace. + +The ``ttl`` attribute specifies how long the server waits before marking +the message as expired and removing it from the queue. The value of ttl +must be between 60 and 1209600 seconds (14 days). Note that the server +might not actually delete the message until its age has reached up to +(ttl + 60) seconds, to allow for flexibility in storage implementations. + +3.3 Code samples +~~~~~~~~~~~~~~~~ + +3.3.1 Posting a single message +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + use OpenCloud\Common\Constants\Datetime; + + $queue->createMessage(array( + 'body' => (object) array( + 'event' => 'BackupStarted', + 'deadline' => '26.12.2013 + ), + 'ttl' => 2 * Datetime::DAY + )); + +3.3.2 Post a batch of messages +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Please note that the list of messages will be truncated at 10. For more, +please execute another method call. + +.. code:: php + + use OpenCloud\Common\Constants\Datetime; + + $messages = array( + array( + 'body' => (object) array( + 'play' => 'football' + ), + 'ttl' => 2 * Datetime::DAY + ), + array( + 'body' => (object) array( + 'play' => 'tennis' + ), + 'ttl' => 50 * Datetime::HOUR + ) + ); + + $queue->createMessages($messages); + +4. Get messages +--------------- + +4.1 Description +~~~~~~~~~~~~~~~ + +This operation gets the message or messages in the specified queue. + +Message IDs and markers are opaque strings. Clients should make no +assumptions about their format or length. Furthermore, clients should +assume that there is no relationship between markers and message IDs +(that is, one cannot be derived from the other). This allows for a wide +variety of storage driver implementations. + +Results are ordered by age, oldest message first. + +4.2 Parameters +~~~~~~~~~~~~~~ + +A hash of options. + ++--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Name | Style | Type | Description | ++====================+=========+============+============================================================================================================================================================================================================================================================================================================================================================================================================================================================================+ +| marker | Query | String | Specifies an opaque string that the client can use to request the next batch of messages. The marker parameter communicates to the server which messages the client has already received. If you do not specify a value, the API returns all messages at the head of the queue (up to the limit). Optional. | ++--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| limit | Query | Integer | When more messages are available than can be returned in a single request, the client can pick up the next batch of messages by simply using the URI template parameters returned from the previous call in the "next" field. Specifies up to 10 messages (the default value) to return. If you do not specify a value for the limit parameter, the default value of 10 is used. Optional. | ++--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| echo | Query | Boolean | Determines whether the API returns a client's own messages. The echo parameter is a Boolean value (true or false) that determines whether the API returns a client's own messages, as determined by the uuid portion of the User-Agent header. If you do not specify a value, echo uses the default value of false. If you are experimenting with the API, you might want to set echo=true in order to see the messages that you posted. The echo parameter is optional. | ++--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| include\_claimed | Query | ​Boolean | Determines whether the API returns claimed messages and unclaimed messages. The include\_claimed parameter is a Boolean value (true or false) that determines whether the API returns claimed messages and unclaimed messages. If you do not specify a value, include\_claimed uses the default value of false (only unclaimed messages are returned). Optional. | ++--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +4.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $messages = $queue->listMessages(array( + 'marker' => '51db6f78c508f17ddc924357', + 'limit' => 20, + 'echo' => true + )); + + while ($message = $messages->next()) { + echo $message->getId() . PHP_EOL; + } + +5. Get a set of messages by ID +------------------------------ + +5.1 Description +~~~~~~~~~~~~~~~ + +This operation provides a more efficient way to query multiple messages +compared to using a series of individual GET. Note that the list of IDs +cannot exceed 20. If a malformed ID or a nonexistent message ID is +provided, it is ignored, and the remaining messages are returned. + +5.2 Parameters +~~~~~~~~~~~~~~ + +A hash of options. + +\|Name\|Style\|Type\|Description\| \|----\|-----\|----\|-----------\| +\|ids\|Query\|String\|Specifies the IDs of the messages to get. Format +multiple message ID values by separating them with commas +(comma-separated). Optional.\| \|claim\_id\|Query\|​String\|Specifies +the claim ID with which the message is associated. Optional.\| +\|----\|-----\|----\|-----------\| + +5.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $ids = array('51db6f78c508f17ddc924357', 'f5b8c8a7c62b0150b68a50d6'); + + $messages = $queue->listMessages(array('ids' => $ids)); + + while ($message = $messages->next()) { + echo $message->getId() . PHP_EOL; + } + +6. Delete a set of messages by ID +--------------------------------- + +6.1 Description +~~~~~~~~~~~~~~~ + +This operation immediately deletes the specified messages. If any of the +message IDs are malformed or non-existent, they are ignored. The +remaining valid messages IDs are deleted. + +6.2 Parameters +~~~~~~~~~~~~~~ + +An array of IDs. + +6.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $ids = array('51db6f78c508f17ddc924357', 'f5b8c8a7c62b0150b68a50d6'); + + $response = $queue->deleteMessages($ids); + +7. Get a specific message +------------------------- + +7.1 Description +~~~~~~~~~~~~~~~ + +This operation gets the specified message from the specified queue. + +7.2 Parameters +~~~~~~~~~~~~~~ + +Message ID. + +7.3 Object properties +~~~~~~~~~~~~~~~~~~~~~ + +``href`` is an opaque relative URI that the client can use to uniquely +identify a message resource and interact with it. + +``ttl`` is the TTL that was set on the message when it was posted. The +message expires after (ttl - age) seconds. + +``age`` is the number of seconds relative to the server's clock. + +``body`` is the arbitrary document that was submitted with the original +request to post the message. + +7.4 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $message = $queue->getMessage('51db6f78c508f17ddc924357'); + +8. Delete message +----------------- + +8.1 Description +~~~~~~~~~~~~~~~ + +This operation immediately deletes the specified message. + +8.2 Parameters +~~~~~~~~~~~~~~ + +None. + +8.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $message->delete(); + diff --git a/doc/services/queues/Queue.md.rst b/doc/services/queues/Queue.md.rst new file mode 100644 index 000000000..1fe9f7036 --- /dev/null +++ b/doc/services/queues/Queue.md.rst @@ -0,0 +1,197 @@ +1. Introduction +--------------- + +A Queue is an entity that holds messages. Ideally, a queue is created +per work type. For example, if you want to compress files, you would +create a queue dedicated to this job. Any application that reads from +this queue would only compress files. + +2. Setup +-------- + +.. code:: php + + $service = $client->queuesService('cloudQueues', 'ORD'); + +3. Client IDs +------------- + +With most of Marconi's operation, you must specify a **Client ID** which +will be used as a unique identifier for the process accessing this +Queue. This is basically a UUID that must be unique to each client +accessing the API - it can be an arbitrary string. + +.. code:: php + + $service->setClientId(); + + echo $service->getClientId(); + +If you call ``setClientId`` without any parameters, a UUID is +automatically generated for you. + +4. List queues +-------------- + +4.1 Description +~~~~~~~~~~~~~~~ + +This operation lists queues for the project. The queues are sorted +alphabetically by name. + +4.2 Parameters +~~~~~~~~~~~~~~ + +\|Name\|Style\|Type\|Description\| \|----\|-----\|----\|-----------\| +\|marker\|Query\|​String\|Specifies the name of the last queue received +in a previous request, or none to get the first page of results. +Optional.\| \|limit\|Query\|Integer\|Specifies the number of queues to +return. The default value for the number of queues returned is 10. If +you do not specify this parameter, the default number of queues is +returned. Optional.\| \|detailed\|Query\|​Boolean\|Determines whether +queue metadata is included in the response. The default value for this +parameter is false, which excludes the metadata. Optional.\| +\|----\|-----\|----\|-----------\| + +4.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $queues = $service->listQueues(); + + while ($queue = $queues->next()) { + echo $queue->getName() . PHP_EOL; + } + +5. Create queue +--------------- + +5.1 Description +~~~~~~~~~~~~~~~ + +This operation creates a new queue. + +5.2 Parameters +~~~~~~~~~~~~~~ + +A string representation of the name for your new Queue. The name must +not exceed 64 bytes in length, and it is limited to US-ASCII letters, +digits, underscores, and hyphens. + +5.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $queue = $service->createQueue('new_queue'); + +6. Retrieve queue +----------------- + +6.1 Description +~~~~~~~~~~~~~~~ + +Returns a ``Queue`` object for use. + +6.2 Parameters +~~~~~~~~~~~~~~ + +Queue name. + +6.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $queue = $service->getQueue('new_queue'); + +7. Check queue existence +------------------------ + +7.1 Description +~~~~~~~~~~~~~~~ + +This operation verifies whether the specified queue exists by returning +``TRUE`` or ``FALSE``. + +7.2 Parameters +~~~~~~~~~~~~~~ + +7.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + if ($service->hasQueue('new_queue')) { + // do something + } + +8. Update queue metadata (permanently to the API) +------------------------------------------------- + +4.1 Description +~~~~~~~~~~~~~~~ + +This operation replaces any existing metadata document in its entirety. +Ensure that you do not accidentally overwrite existing metadata that you +want to retain. If you want to *append* metadata, ensure you merge a new +array to the existing values. + +4.2 Parameters +~~~~~~~~~~~~~~ + +Hash of key pairs. + +4.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $queue->saveMetadata(array( + 'foo' => 'bar' + )); + +9. Retrieve the queue metadata (fresh from the API) +--------------------------------------------------- + +4.1 Description +~~~~~~~~~~~~~~~ + +This operation returns metadata, such as message TTL, for the queue. + +4.2 Parameters +~~~~~~~~~~~~~~ + +None. + +4.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $metadata = $queue->retrieveMetadata(); + + print_r($metadata->toArray()); + +10. Get queue stats +------------------- + +4.1 Description +~~~~~~~~~~~~~~~ + +This operation returns queue statistics, including how many messages are +in the queue, categorized by status. + +4.2 Parameters +~~~~~~~~~~~~~~ + +None. + +4.3 Code sample +~~~~~~~~~~~~~~~ + +.. code:: php + + $queue->getStats(); + diff --git a/doc/services/queues/index.rst b/doc/services/queues/index.rst new file mode 100644 index 000000000..e69de29bb diff --git a/doc/services/volume/index.rst b/doc/services/volume/index.rst new file mode 100644 index 000000000..e69de29bb From f65cda63ea035bf992215276b1cf4e43710c5a16 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 3 Mar 2015 20:04:47 +0100 Subject: [PATCH 114/181] Add remaining top-level things --- doc/caching-creds.rst | 44 +++++++++++ doc/debugging.rst | 99 +++++++++++++++++++++++ doc/index.rst | 23 ++++++ doc/iterators.rst | 178 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 344 insertions(+) create mode 100644 doc/caching-creds.rst create mode 100644 doc/debugging.rst create mode 100644 doc/index.rst create mode 100644 doc/iterators.rst diff --git a/doc/caching-creds.rst b/doc/caching-creds.rst new file mode 100644 index 000000000..3c3e8df23 --- /dev/null +++ b/doc/caching-creds.rst @@ -0,0 +1,44 @@ +Caching credentials +=================== + +You can speed up your API operations by caching your credentials in a +(semi-)permanent location, such as your DB or local filesystem. This +enable subsequent requests to access a shared resource, instead of +repetitively having to re-authenticate on every thread of execution. + +Tokens are valid for 24 hours, so you can effectively re-use the same +cached value for that period. If you try to use a cached version that +has expired, an authentication request will be made. + +Filesystem example +------------------ + +In this example, credentials will be saved to a file in the local +filesystem. Be sure to exclude it from your VCS. + +.. code:: php + + use OpenCloud\Rackspace; + + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => 'foo', + 'apiKey' => 'bar' + )); + + $cacheFile = __DIR__ . '/.opencloud_token'; + + // If the cache file exists, try importing it into the client + if (file_exists($cacheFile)) { + $data = unserialize(file_get_contents($cacheFile)); + $client->importCredentials($data); + } + + $token = $client->getTokenObject(); + + // If no token exists, or the current token is expired, re-authenticate and save the new token to disk + if (!$token || ($token && $token->hasExpired())) { + $client->authenticate(); + file_put_contents($cacheFile, serialize($client->exportCredentials())); + } + +In tests, the above code shaved about 1-2s off the execution time. diff --git a/doc/debugging.rst b/doc/debugging.rst new file mode 100644 index 000000000..445915284 --- /dev/null +++ b/doc/debugging.rst @@ -0,0 +1,99 @@ +Debugging +========= + +There are two important debugging strategies to use when encountering +problems with HTTP transactions. + +Strategy 1: Meaningful exception handling +----------------------------------------- + +If the API returns a ``4xx`` or ``5xx`` status code, it indicates that +there was an error with the sent request, meaning that the transaction +cannot be adequately completed. + +The Guzzle HTTP component, which forms the basis of our SDK's transport +layer, utilizes `numerous exception +classes `__ +to handle this error logic. + +The two most common exception classes are: + +- ``Guzzle\Http\Exception\ClientErrorResponseException``, which is + thrown when a ``4xx`` response occurs + +- ``Guzzle\Http\Exception\ServerErrorResponseException``, which is + thrown when a ``5xx`` response occurs + +Both of these classes extend the base ``BadResponseException`` class. + +This provides you with the granularity you need to debug and handle +exceptions. + +An example with Swift +~~~~~~~~~~~~~~~~~~~~~ + +If you're trying to retrieve a Swift resource, such as a Data Object, +and you're not completely certain that it exists, it makes sense to wrap +your call in a try/catch block: + +.. code:: php + + use Guzzle\Http\Exception\ClientErrorResponseException; + + try { + return $service->getObject('foo.jpg'); + } catch (ClientErrorResponseException $e) { + // Okay, the resource probably does not exist + return false; + } catch (\Exception $e) { + // Some other exception was thrown, probably critical + $this->logException($e); + $this->alertDevs(); + } + +Both ``ClientErrorResponseException`` and +``ServerErrorResponseException`` have two methods that allow you to +access the HTTP transaction: + +.. code:: php + + // Find out the faulty request + $request = $e->getRequest(); + + // Display everything by casting as string + echo (string) $request; + + // Find out the HTTP response + $response = $e->getResponse(); + + // Output that too + echo (string) $response; + +Strategy 2: Wire logging +------------------------ + +Guzzle provides a `Log +plugin `__ +that allows you to log everything over the wire, which is useful if you +don't know what's going on. + +Here's how you enable it: + +Install the plugin +^^^^^^^^^^^^^^^^^^ + +.. code:: bash + + php composer.phar require guzzle/plugin-log:~3.8 + +Add to your client +^^^^^^^^^^^^^^^^^^ + +.. code:: php + + use Guzzle\Plugin\Log\LogPlugin; + + $client->addSubscriber(LogPlugin::getDebugPlugin()); + +The above will add a generic logging subscriber to your client, which +will be notified every time a relevant HTTP event is fired off. diff --git a/doc/index.rst b/doc/index.rst new file mode 100644 index 000000000..45c453a40 --- /dev/null +++ b/doc/index.rst @@ -0,0 +1,23 @@ +.. php-opencloud documentation master file, created by + sphinx-quickstart on Tue Mar 3 12:28:19 2015. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to php-opencloud's documentation! +========================================= + +Contents: + +.. toctree:: + :glob: + :maxdepth: 2 + + services/**/index + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/doc/iterators.rst b/doc/iterators.rst new file mode 100644 index 000000000..e5d3c198d --- /dev/null +++ b/doc/iterators.rst @@ -0,0 +1,178 @@ +Iterators +========= + +Intro +----- + +Iterators allow you to traverse over collections of your resources in an +efficient and easy way. Currently there are two Iterators provided by +the SDK: + +- **ResourceIterator**. The standard iterator class that implements + SPL's standard + `Iterator `__, + `ArrayAccess `__ + and `Countable `__ + interfaces. In short, this allows you to traverse this object (using + ``foreach``), count its internal elements like an array (using + ``count`` or ``sizeof``), and access its internal elements like an + array (using ``$iterator[1]``). + +- **PaginatedIterator**. This is a child of ResourceIterator, and as + such inherits all of its functionality. The difference however is + that when it reaches the end of the current collection, it attempts + to construct a URL to access the API based on predictive paginated + collection templates. + +Common behaviour +---------------- + +.. code:: php + + $iterator = $computeService->flavorList(); + +There are two ways to traverse an iterator. The first is the longer, +more traditional way: + +.. code:: php + + while ($iterator->valid()) { + $flavor = $iterator->current(); + + // do stuff.. + echo $flavor->id; + + $iterator->next(); + } + +There is also a shorter and more intuitive version: + +.. code:: php + + foreach ($iterator as $flavor) { + // do stuff... + echo $flavor->id; + } + +Because the iterator implements PHP's native ``Iterator`` interface, it +can inherit all the native functionality of traversible data structures +with ``foreach``. + +Very important note +------------------- + +Until now, users have been expected to do this: + +.. code:: php + + while ($flavor = $iterator->next()) { + // ... + } + +which is **incorrect**. The single responsibility of ``next`` is to move +the internal pointer forward. It is the job of ``current`` to retrieve +the current element. + +For your convenience, these two Iterator classes are fully backward +compatible: they exhibit all the functionality you'd expect from a +correctly implemented iterator, but they also allow previous behaviour. + +Using paginated collections +--------------------------- + +For large collections, such as retrieving DataObjects from +CloudFiles/Swift, you need to use pagination. Each resource will have a +different limit per page; so once that page is traversed, there needs to +be another API call to retrieve to *next* page's resources. + +There are two key concepts: + +- **limit** is the amount of resources returned per page +- **marker** is the way you define a starting point. It is some form of + identifier that allows the collection to begin from a specific + resource + +Resource classes +~~~~~~~~~~~~~~~~ + +When the iterator returns a current element in the internal list, it +populates the relevant resource class with all the data returned to the +API. In most cases, a ``stdClass`` object will become an instance of +``OpenCloud\Common\PersistentObject``. + +In order for this instantiation to happen, the ``resourceClass`` option +must correspond to some method in the parent class that creates the +resource. For example, if we specify 'ScalingPolicy' as the +``resourceClass``, the parent object (in this case +``OpenCloud\Autoscale\Group``, needs to have some method will allows the +iterator to instantiate the child resource class. These are all valid: + +1. ``Group::scalingGroup($data);`` + +2. ``Group::getScalingGroup($data);`` + +3. ``Group::resource('ScalingGroup', $data);`` + +where ``$data`` is the standard object. This list runs in order of +precedence. + +Setting up a PaginatedIterator +------------------------------ + +.. code:: php + + use OpenCloud\Common\Collection\PaginatedIterator; + + $service = $client->computeService(); + + $flavors = PaginatedIterator::factory($service, array( + 'resourceClass' => 'Flavor', + 'baseUrl' => $service->getUrl('flavors') + 'limit.total' => 350, + 'limit.page' => 100, + 'key.collection' => 'flavors' + )); + + foreach ($flavors as $flavor) { + echo $flavor->getId(); + } + +As you can see, there are a lot of configuration parameters to pass in - +and getting it right can be quite fiddly, involving a lot of API +research. For this reason, using the convenience methods like +``flavorList`` is recommended because it hides the complexity. + +PaginatedIterator options +~~~~~~~~~~~~~~~~~~~~~~~~~ + +There are certain configuration options that the paginated iterator +needs to work. These are: + ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| Name | Description | Type | Required | Default | ++=========================+===================================================================================================================================================================================================================================================+==============================+============+===============+ +| resourceClass | The resource class that is instantiated when the current element is retrieved. This is relative to the parent/service which called the iterator. | string | Yes | - | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| baseUrl | The base URL that is used for making new calls to the API for new pages | ``Guzzle\Http\Url`` | Yes | - | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| limit.total | The total amount of resources you want to traverse in your collection. The iterator will stop as this limit is reached, regardless if there are more items in the list | int | No | 10000 | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| limit.page | The amount of resources each page contains | int | No | 100 | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| key.links | Often, API responses will contain "links" that allow easy access to the next page of a resource collection. This option specifies what that JSON element is called (its key). For example, for Rackspace Compute images it is ``images_links``. | string | No | links | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| key.collection | The top-level key for the array of resources. For example, servers are returned with this data structure: ``{"servers": [...]}``. The **key.collection** value in this case would be ``servers``. | string | No | ``null`` | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| key.collectionElement | Rarely used. But it indicates the key name for each nested resource element. KeyPairs, for example, are listed like this: ``{"keypairs": [ {"keypair": {...}} ] }``. So in this case the collectionElement key would be ``keypair``. | string | No | ``null`` | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| key.marker | The value used as the marker. It needs to represent a valid property in the JSON resource objects. Often it is ``id`` or ``name``. | string | No | name | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| request.method | The HTTP method used when making API calls for new pages | string | No | GET | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| request.headers | The HTTP headers to send when making API calls for new pages | array | No | ``array()`` | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| request.body | The HTTP entity body to send when making API calls for new pages | ``Guzzle\Http\EntityBody`` | No | ``null`` | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ +| request.curlOptions | Additional cURL options to use when making API calls for new pages | array | No | ``array()`` | ++-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ + From 31b39641c2ef3009ddbeeebc6dcf9f6825fa4a06 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 4 Mar 2015 13:49:42 +0100 Subject: [PATCH 115/181] Shuffle structure --- doc/services/autoscale/group-config.rst | 6 +----- doc/services/autoscale/groups.rst | 9 --------- doc/services/autoscale/index.rst | 18 +++++++++++++++++ doc/services/autoscale/policies.rst | 4 +--- doc/services/autoscale/service.sample.rst | 7 ------- doc/services/autoscale/webhooks.rst | 4 +--- doc/services/common/service-args.rst | 16 +++++++++++++++ doc/services/compute/flavors.rst | 6 ------ doc/services/compute/images.rst | 5 ----- doc/services/compute/index.rst | 18 +++++++++++++++++ doc/services/compute/keypairs.rst | 6 ------ doc/services/compute/servers.rst | 5 ----- doc/services/compute/service.sample.rst | 24 ----------------------- 13 files changed, 55 insertions(+), 73 deletions(-) delete mode 100644 doc/services/autoscale/service.sample.rst create mode 100644 doc/services/common/service-args.rst delete mode 100644 doc/services/compute/service.sample.rst diff --git a/doc/services/autoscale/group-config.rst b/doc/services/autoscale/group-config.rst index a0d7c98f7..5dcfb6ce4 100644 --- a/doc/services/autoscale/group-config.rst +++ b/doc/services/autoscale/group-config.rst @@ -1,14 +1,10 @@ Group configurations ==================== -.. contents:: - Setup ----- -.. include:: service.sample.rst - -Finally, in order to interact with the functionality of a group's configuration, +In order to interact with the functionality of a group's configuration, you must first retrieve the details of the group itself. To do this, you must substitute `{groupId}` for your group's ID: diff --git a/doc/services/autoscale/groups.rst b/doc/services/autoscale/groups.rst index 8e781a2aa..a6caf3f9d 100644 --- a/doc/services/autoscale/groups.rst +++ b/doc/services/autoscale/groups.rst @@ -1,15 +1,6 @@ Groups ====== -.. contents:: - - -Setup ------ - -.. include:: service.sample.rst - - List all groups --------------- diff --git a/doc/services/autoscale/index.rst b/doc/services/autoscale/index.rst index 3077a0a2c..d6ec512ac 100644 --- a/doc/services/autoscale/index.rst +++ b/doc/services/autoscale/index.rst @@ -1,6 +1,23 @@ Auto Scale v2 ============= +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now, set up the Auto Scale service: + +.. code-block:: php + + $service = $client->autoscaleService(); + +.. include:: ../common/service-args.rst + + +Operations +---------- + .. toctree:: groups @@ -8,6 +25,7 @@ Auto Scale v2 policies webhooks + Glossary -------- diff --git a/doc/services/autoscale/policies.rst b/doc/services/autoscale/policies.rst index f5d2605f4..e103d328e 100644 --- a/doc/services/autoscale/policies.rst +++ b/doc/services/autoscale/policies.rst @@ -4,9 +4,7 @@ Scaling Policies Setup ----- -.. include:: service.sample.rst - -Finally, in order to interact with the functionality of a group's scaling +In order to interact with the functionality of a group's scaling policies, you must first retrieve the details of the group itself. To do this, you must substitute `{groupId}` for your group's ID: diff --git a/doc/services/autoscale/service.sample.rst b/doc/services/autoscale/service.sample.rst deleted file mode 100644 index 7e5d166ab..000000000 --- a/doc/services/autoscale/service.sample.rst +++ /dev/null @@ -1,7 +0,0 @@ -.. include:: ../common/rs-client.sample.rst - -Now, set up the Auto Scale service: - -.. code-block:: php - - $service = $client->autoscaleService(); diff --git a/doc/services/autoscale/webhooks.rst b/doc/services/autoscale/webhooks.rst index 68b16b0dc..9133aa9ed 100644 --- a/doc/services/autoscale/webhooks.rst +++ b/doc/services/autoscale/webhooks.rst @@ -4,9 +4,7 @@ Webhooks Setup ----- -.. include:: service.sample.rst - -Finally, in order to interact with webhooks, you must first retrieve the +In order to interact with webhooks, you must first retrieve the details of the group and scaling policy you want to execute: .. code-block:: php diff --git a/doc/services/common/service-args.rst b/doc/services/common/service-args.rst new file mode 100644 index 000000000..696f32f2a --- /dev/null +++ b/doc/services/common/service-args.rst @@ -0,0 +1,16 @@ +``{catalogName}`` is the **name** of the service, as it appears in the service +catalog. For Rackspace users, a default will be provided if you pass ``null`` +in for this argument. For OpenStack users, you cannot do this: you must instead +set your own value since it can depend on your environment setup. + +``{region}`` is the Compute region the service will operate in. For Rackspace +users, you can select one of the following from the `supported regions page +`_. + +``{urlType}`` is the type of URL to use, depending on what endpoints your +catalog provides. For Rackspace, you may use either ``internalURL`` or +``publicURL``. The former will execute HTTP transactions over the internal +network configured for your service, possibly reducing latency and the overall +bandwidth cost - the caveat is that all of your resources must be in same region. +``publicURL``, however, which is the default, will operate over the public +Internet and is to be used for multi-region installations. diff --git a/doc/services/compute/flavors.rst b/doc/services/compute/flavors.rst index f79caa171..eeb447d3c 100644 --- a/doc/services/compute/flavors.rst +++ b/doc/services/compute/flavors.rst @@ -1,12 +1,6 @@ Flavors ======= -Setup ------ - -.. include:: service.sample.rst - - Get a flavor ------------ diff --git a/doc/services/compute/images.rst b/doc/services/compute/images.rst index b2aae4a65..fb68af7f7 100644 --- a/doc/services/compute/images.rst +++ b/doc/services/compute/images.rst @@ -9,11 +9,6 @@ Images Cloud Backup or Cloud Block Storage to ensure availability in case you need to rebuild or restore a server. -Setup ------ - -.. include:: service.sample.rst - List images ----------- diff --git a/doc/services/compute/index.rst b/doc/services/compute/index.rst index 94c41979f..207151d50 100644 --- a/doc/services/compute/index.rst +++ b/doc/services/compute/index.rst @@ -6,6 +6,23 @@ Compute v2 This is a joint service that supports both Rackspace Cloud Servers v2 API, and OpenStack Nova v2 API. +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now, set up the Compute service: + +.. code-block:: php + + $service = $client->computeService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + .. toctree:: images @@ -13,6 +30,7 @@ Compute v2 servers keypairs + Glossary -------- diff --git a/doc/services/compute/keypairs.rst b/doc/services/compute/keypairs.rst index 4040c0e65..f7e67b113 100644 --- a/doc/services/compute/keypairs.rst +++ b/doc/services/compute/keypairs.rst @@ -1,12 +1,6 @@ Keypairs ======== -Setup ------ - -.. include:: service.sample.rst - - Generate a new keypair ---------------------- diff --git a/doc/services/compute/servers.rst b/doc/services/compute/servers.rst index 4d2f2363c..229e8e4ff 100644 --- a/doc/services/compute/servers.rst +++ b/doc/services/compute/servers.rst @@ -1,11 +1,6 @@ Servers ======= -Setup ------ - -.. include:: service.sample.rst - Get server ---------- diff --git a/doc/services/compute/service.sample.rst b/doc/services/compute/service.sample.rst deleted file mode 100644 index c684caf9a..000000000 --- a/doc/services/compute/service.sample.rst +++ /dev/null @@ -1,24 +0,0 @@ -.. include:: ../common/rs-client.sample.rst - -Now, set up the Auto Scale service: - -.. code-block:: php - - $service = $client->computeService('{catalogName}', '{region}', '{urlType}'); - - -``{catalogName}`` is the **name** of the service, as it appears in the service -catalog. For Rackspace users, this will default to `cloudServersOpenStack`; for -OpenStack users, you must set your own value since it can depend on your -environment setup. - -``{region}`` is the Compute region the service will operate in. For Rackspace -users, you can select one of the following from the `supported regions page`. - -``{urlType}`` is the type of URL to use, depending on what endpoints your -catalog provides. For Rackspace, you may use either `internalURL` or `publicURL`. -The former will execute HTTP transactions over the internal Rackspace network, -reducing latency and the overall bandwidth cost - the caveat is that all of your -resources must be in same region. `publicURL`, however, which is the default, -will operate over the public Internet and is to be used for multi-region -installations. From 9ece52bcd87ba09cdf432bd89eb42ec5f683cf95 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 4 Mar 2015 13:50:03 +0100 Subject: [PATCH 116/181] Turn on extension --- doc/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/conf.py b/doc/conf.py index 7f9e29414..f49381d42 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -23,7 +23,7 @@ lexers['php-annotations'] = PhpLexer(startinline=True, linenos=1) primary_domain = 'php' -extensions = [] +extensions = ['sphinxcontrib.phpdomain'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' From 5afe71fcf52fff14939c24d451f49ad9acaaaeee Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 4 Mar 2015 13:50:07 +0100 Subject: [PATCH 117/181] Add regions --- doc/regions.rst | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 doc/regions.rst diff --git a/doc/regions.rst b/doc/regions.rst new file mode 100644 index 000000000..82edf28ec --- /dev/null +++ b/doc/regions.rst @@ -0,0 +1,15 @@ +Rackspace regions +================= + +Below are the supported regions on the Rackspace network: + ++======+===========+ +| code | location | ++======+===========+ +| IAD | Virginia | +| ORD | Chicago | +| DFW | Dallas | +| LON | London | +| SYD | Sydney | +| HKG | Hong Kong | ++------+-----------+ From 0f0a1aef4f41b6d3f66693fe06ed7b259ab385c5 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 4 Mar 2015 13:50:13 +0100 Subject: [PATCH 118/181] Add DNS docs --- doc/services/dns/Domains.md.rst | 290 ------------------ doc/services/dns/Records.md.rst | 111 ------- doc/services/dns/Service.md.rst | 13 - doc/services/dns/domains.rst | 288 +++++++++++++++++ doc/services/dns/index.rst | 51 +++ .../dns/{Limits.md.rst => limits.rst} | 37 +-- doc/services/dns/records.rst | 113 +++++++ .../{Reverse-DNS.md.rst => reverse-dns.rst} | 24 +- 8 files changed, 474 insertions(+), 453 deletions(-) delete mode 100644 doc/services/dns/Domains.md.rst delete mode 100644 doc/services/dns/Records.md.rst delete mode 100644 doc/services/dns/Service.md.rst create mode 100644 doc/services/dns/domains.rst rename doc/services/dns/{Limits.md.rst => limits.rst} (59%) create mode 100644 doc/services/dns/records.rst rename doc/services/dns/{Reverse-DNS.md.rst => reverse-dns.rst} (82%) diff --git a/doc/services/dns/Domains.md.rst b/doc/services/dns/Domains.md.rst deleted file mode 100644 index 824c05099..000000000 --- a/doc/services/dns/Domains.md.rst +++ /dev/null @@ -1,290 +0,0 @@ -Domains -======= - -A domain is an entity/container of all DNS-related information -containing one or more records. - -Setup ------ - -Limit methods will be called on the DNS service, an instance of -``OpenCloud\DNS\Service``. Please see the `DNS service `__ -documentation for setup instructions. - -Get domain ----------- - -To retrieve a specific domain, you will need the domain's **id**, not -its domain name. - -.. code:: php - - $domain = $service->domain(12345); - -If you are having trouble remembering or accessing the domain ID, you -can do a domain list search for your domain and then access its ID. - -List domains ------------- - -These calls provide a list of all DNS domains manageable by a given -account. The resulting list is flat, and does not break the domains down -hierarchically by subdomain. All representative domains are included in -the list, even if a domain is conceptually a subdomain of another domain -in the list. - -.. code:: php - - $domains = $service->domainList(); - - # Return detailed information for each domain - $domains = $service->domainList(true); - -Please consult the `iterator -documentation `__ for more information -about iterators. - -Filter parameters -~~~~~~~~~~~~~~~~~ - -You can filter the aforementioned search by using the ``name`` parameter -in a key/value array supplied as a method argument. For example, -providing ``array('name' => 'hoola.com')`` will return hoola.com and -similar names such as main.hoola.com and sub.hoola.com. - -.. code:: php - - $hoolaDomains = $service->domainList(array( - 'name' => 'hoola.com' - )); - -Filter criteria may consist of: - -- Any letter (A-Za-z) -- Numbers (0-9) -- Hyphen ("-") -- 1 to 63 characters - -Filter criteria should not include any of the following characters: - - ' + , \| ! " £ $ % & / ( ) = ? ^ \* ç ° § ; : \_ > ] [ @ à, é, ò - -Finding a domain ID -~~~~~~~~~~~~~~~~~~~ - -If you know a domain's name, but not its unique identifier, you can do -this: - -.. code:: php - - $domains = $service->domainList(array( - 'name' => 'foo.com' - )); - - foreach ($domains as $domain) { - $id = $domain->id; - } - -List domain changes -------------------- - -This call shows all changes to the specified domain since the specified -date/time. The since parameter is optional and defaults to midnight of -the current day. - -.. code:: php - - $changes = $domain->changes(); - - # Changes since last week - $since = date('c', strtotime('last week')); - $changes = $domain->changes($since); - - foreach ($changes->changes as $change) { - printf("Domain: %s\nAction: %s\nTarget: %s", $change->domain, $change->action, $change->targetType); - - foreach ($change->changeDetails as $detail) { - printf("Details: %s was changed from %s to %s", $detail->field, $detail->oldValue, $detail->newValue); - } - } - -Export domain -------------- - -This call provides the BIND (Berkeley Internet Name Domain) 9 formatted -contents of the requested domain. This call is for a single domain only, -and as such, does not traverse up or down the domain hierarchy for -details (that is, no subdomain information is provided). - -.. code:: php - - $asyncResponse = $domain->export(); - $body = $asyncResponse->waitFor('COMPLETED'); - echo $body['contents']; - -Create domain -------------- - -A domain is composed of DNS records (e.g. ``A``, ``CNAME`` or ``MX`` -records) and an optional list of sub-domains. You will need to specify -these before creating the domain itself: - -.. code:: php - - // get empty object - $domain = $service->domain(); - - // add A record - $aRecord = $domain->record(array( - 'type' => 'A', - 'name' => 'example.com', - 'data' => '192.0.2.17', - 'ttl' => 3600 - )); - $domain->addRecord($aRecord); - - // add optional C record - $cRecord = $domain->record(array( - 'type' => 'CNAME', - 'name' => 'www.example.com', - 'data' => 'example.com', - 'ttl' => 3600 - )); - $domain->addRecord($cRecord); - - // add optional MX record - $mxRecord = $domain->record(array( - 'type' => 'MX', - 'data' => 'mail.example.com', - 'name' => 'example.com', - 'ttl' => 3600, - 'priority' => 5 - )); - $domain->addRecord($mxRecord); - - // add optional NS records - $nsRecord1 = $domain->record(array( - 'type' => 'NS', - 'data' => 'dns1.stabletransit.com', - 'name' => 'example.com', - 'ttl' => 5400 - )); - $domain->addRecord($nsRecord1); - - $nsRecord2 = $domain->record(array( - 'type' => 'NS', - 'data' => 'dns2.stabletransit.com', - 'name' => 'example.com', - 'ttl' => 5400 - )); - $domain->addRecord($nsRecord2); - - // add optional subdomains - $sub1 = $domain->subdomain(array( - 'emailAddress' => 'foo@example.com', - 'name' => 'dev.example.com', - 'comment' => 'Dev portal' - )); - $domain->addSubdomain($sub1); - - // send to API - $domain->create(array( - 'emailAddress' => 'webmaster@example.com', - 'ttl' => 3600, - 'name' => 'example.com', - 'comment' => 'Optional comment' - )); - -Clone domain ------------- - -This call will duplicate a single existing domain configuration with a -new domain name for the specified Cloud account. By default, all records -and, optionally, subdomain(s) are duplicated as well. - -The method signature you will need to use is: - -.. code:: php - - cloneDomain ( string $newDomainName [, bool $subdomains [, bool $comments [, bool $email [, bool $records ]]]] ) - -+----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| Name | Data type | Default | Description | -+======================+==============+============+====================================================================================================================================================================================+ -| ``$newDomainName`` | ``string`` | - | The new name for your cloned domain | -+----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``$subdomains`` | ``bool`` | ``true`` | Set to ``TRUE`` to clone all the subdomains for this domain | -+----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``$comments`` | ``bool`` | ``true`` | Set to ``TRUE`` to replace occurrences of the reference domain name with the new domain name in comments on the cloned (new) domain. | -+----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``$email`` | ``bool`` | ``true`` | Set to ``TRUE`` to replace occurrences of the reference domain name with the new domain name in data fields (of records) on the cloned (new) domain. Does not affect NS records. | -+----------------------+--------------+------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ - -For example: - -.. code:: php - - $asyncResponse = $domain->cloneDomain('new-name.com', true); - -Import domain -------------- - -This call provisions a new DNS domain under the account specified by the -BIND 9 formatted file configuration contents defined in the request -object. - -You will need to ensure that the BIND 9 formatted file configuration -contents are valid by adhering to the following rules: - -- Each record starts on a new line and on the first column. If a record - will not fit on one line, use the BIND\_9 line continuation - convention where you put a left parenthesis and continue the one - record on the next line and put a right parenthesis when the record - ends. For example, - - example2.net. 3600 IN SOA dns1.stabletransit.com. ( - sample@rackspace.com. 1308874739 3600 3600 3600 3600) - -- The attribute values of a record must be separated by a single blank - or tab. No other white space characters. - -- If there are any NS records, the data field should not be - dns1.stabletransit.com or dns2.stabletransit.com. They will result in - "duplicate record" errors. - -For example: - -.. code:: php - - $bind9Data = <<import($bind9Data); - -Modify domain -------------- - -This call modifies DNS domain(s) attributes only. Only the TTL, email -address and comment attributes of a domain can be modified. Records -cannot be added, modified, or removed through this API operation - you -will need to use the `add -records `__, `modify -records `__ or `remove -records `__ operations -respectively. - -.. code:: php - - $domain->update(array( - 'ttl' => ($domain->ttl + 100), - 'emailAddress' => 'new_dev@foo.com' - )); - -Remove domain -------------- - -.. code:: php - - $domain->delete(); - diff --git a/doc/services/dns/Records.md.rst b/doc/services/dns/Records.md.rst deleted file mode 100644 index 4e492e8ef..000000000 --- a/doc/services/dns/Records.md.rst +++ /dev/null @@ -1,111 +0,0 @@ -Records -======= - -A DNS record belongs to a particular domain and is used to specify -information about the domain. - -There are several types of DNS records. Examples include mail exchange -(MX) records, which specify the mail server for a particular domain, and -name server (NS) records, which specify the authoritative name servers -for a domain. - -It is represented by the ``OpenCloud\DNS\Resource\Record`` class. -Records belong to a `Domain `__. - -Get record ----------- - -In order to retrieve details for a specific DNS record, you will need -its **id**: - -.. code:: php - - $record = $domain->record('NS-1234567'); - -If you do not have this ID at your disposal, you can traverse the record -collection and do a string comparison (detailed below). - -List records ------------- - -This call lists all records configured for the specified domain. - -.. code:: php - - $records = $domain->recordList(); - - foreach ($records as $record) { - printf("Record name: %s, ID: %s, TTL: %s\n", $record->name, $record->id, $record->ttl); - } - -Please consult the `iterator -documentation `__ for more information -about iterators. - -Query parameters -~~~~~~~~~~~~~~~~ - -You can pass in an array of query parameters for greater control over -your search: - -+------------+--------------+------------------------+---------------+ -| Name | Data type | Default | Description | -+============+==============+========================+===============+ -| ``type`` | ``string`` | The record type | -+------------+--------------+------------------------+---------------+ -| ``name`` | ``string`` | The record name | -+------------+--------------+------------------------+---------------+ -| ``data`` | ``string`` | Data for this record | -+------------+--------------+------------------------+---------------+ - -Find a record ID from its name -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -For example: - -.. code:: php - - $records = $domain->recordList(array( - 'name' => 'imap.example.com', - 'type' => 'MX' - )); - - foreach ($records as $record) { - $recordId = $record->id; - } - -Add record ----------- - -This call adds a new record to the specified domain: - -.. code:: php - - $record = $domain->record(array( - 'type' => 'A', - 'name' => 'example.com', - 'data' => '192.0.2.17', - 'ttl' => 3600 - )); - - $record->create(); - -Please be aware that records that are added with a different hostname -than the parent domain might fail silently. - -Modify record -------------- - -.. code:: php - - $record = $domain->record(123456); - $record->ttl -= 100; - $record->update(); - -Delete record -------------- - -.. code:: php - - $record->delete(); - diff --git a/doc/services/dns/Service.md.rst b/doc/services/dns/Service.md.rst deleted file mode 100644 index 29ea79193..000000000 --- a/doc/services/dns/Service.md.rst +++ /dev/null @@ -1,13 +0,0 @@ -DNS Service -=========== - -To instantiate a Compute service object, you first need to setup a -Rackspace/OpenStack client. To do this, or for more information, please -consult the `Clients documentation <../Clients.md>`__. - -You will then need to run: - -.. code:: php - - $service = $client->dnsService(); - diff --git a/doc/services/dns/domains.rst b/doc/services/dns/domains.rst new file mode 100644 index 000000000..0a7b83b96 --- /dev/null +++ b/doc/services/dns/domains.rst @@ -0,0 +1,288 @@ +Domains +======= + +Get domain +---------- + +To retrieve a specific domain, you will need the domain's **id**, not +its domain name: + +.. code-block:: php + + $domain = $service->domain('{domainId}'); + + +If you are having trouble remembering or accessing the domain ID, you +can do a domain list search for your domain and then access its ID. + + +List domains +------------ + +These calls provide a list of all DNS domains manageable by a given +account. The resulting list is flat, and does not break the domains down +hierarchically by subdomain. All representative domains are included in +the list, even if a domain is conceptually a subdomain of another domain +in the list. + +.. code-block:: php + + $domains = $service->domainList(); + + # Return detailed information for each domain + $domains = $service->domainList(true); + + +Filter parameters +~~~~~~~~~~~~~~~~~ + +You can filter the search by using the ``name`` parameter in a key/value array +supplied as a method argument. For example, to retrieve domains named ``foo.com``, +along with any subdomains like ``bar.foo.com``: + +.. code-block:: php + + $hoolaDomains = $service->domainList(array( + 'name' => 'foo.com' + )); + +Filter criteria may consist of: + +* Any letter (A-Za-z) +* Numbers (0-9) +* Hyphen ("-") +* 1 to 63 characters + +Filter criteria should not include any of the following characters: + + ' + , \| ! " £ $ % & / ( ) = ? ^ \* ç ° § ; : \_ > ] [ @ à, é, ò + + +Finding a domain ID +~~~~~~~~~~~~~~~~~~~ + +Once you have a list of domains, to retrieve a domain's ID: + +.. code-block:: php + + foreach ($domains as $domain) { + $id = $domain->id; + } + + +List domain changes +------------------- + +This call shows all changes to the specified domain since the specified +date/time. To list all available changes for a domain for the current day: + +.. code-block:: php + + $changes = $domain->changes(); + + +For more granular control, you can manually define the ``since`` parameter like +so: + +.. code-block:: php + + $since = date('c', strtotime('last week')); + $changes = $domain->changes($since); + +Once you have a set of changes, you can iterate over them like so: + +.. code-block:: php + + foreach ($changes->changes as $change) { + printf("Domain: %s\nAction: %s\nTarget: %s", $change->domain, $change->action, $change->targetType); + + foreach ($change->changeDetails as $detail) { + printf("Details: %s was changed from %s to %s", $detail->field, $detail->oldValue, $detail->newValue); + } + } + + +Create domain +------------- + +The first thing you will need to do is instantiate a new object and set the +primary ``A`` record for the DNS domain, like so: + +.. code-block:: php + + // get empty object + $domain = $service->domain(); + + // add A record + $aRecord = $domain->record(array( + 'type' => 'A', + 'name' => 'example.com', + 'data' => '192.0.2.17', + 'ttl' => 3600 + )); + + $domain->addRecord($aRecord); + +You also have the option of adding more types of DNS records such as ``CNAME``, +``MX`` and ``NS`` records. This step is completely optional and depends on +your requirements: + +.. code-block:: php + + // add CNAME record + $cRecord = $domain->record(array( + 'type' => 'CNAME', + 'name' => 'www.example.com', + 'data' => 'example.com', + 'ttl' => 3600 + )); + $domain->addRecord($cRecord); + + // add MX record + $mxRecord = $domain->record(array( + 'type' => 'MX', + 'data' => 'mail.example.com', + 'name' => 'example.com', + 'ttl' => 3600, + 'priority' => 5 + )); + $domain->addRecord($mxRecord); + + // add NS record + $nsRecord = $domain->record(array( + 'type' => 'NS', + 'data' => 'dns1.stabletransit.com', + 'name' => 'example.com', + 'ttl' => 5400 + )); + $domain->addRecord($nsRecord); + +You can also add sub-domains to your new DNS domain. Again, this is completely +optional: + +.. code-block:: php + + $subdomain = $domain->subdomain(array( + 'emailAddress' => 'foo@example.com', + 'name' => 'dev.example.com', + 'comment' => 'Dev portal' + )); + $domain->addSubdomain($subdomain); + +Once you've finished configuring how your DNS domain will work, you're ready +to specify the essential details and send it to the API for creation: + +.. code-block:: php + + $domain->create(array( + 'emailAddress' => 'webmaster@example.com', + 'ttl' => 3600, + 'name' => 'example.com', + 'comment' => 'Optional comment' + )); + + +Clone domain +------------ + +This call will duplicate an existing domain under a new name. By default, all +records and, optionally, subdomains are duplicated as well. + +The method signature you will need to use is: + +.. function:: cloneDomain( $newDomainName[, $subdomains[, $comments[, $email[, $records]]]] ) + + Clone a domain + + :param string $newDomainName: The name of the new domain entry + :param bool $subdomains: Set to ``true`` to clone all the subdomains for this domain + :param bool $comments: Set to ``true`` to replace occurrences of the reference domain name with the new domain name in comments on the cloned (new) domain. + :param bool $email: Set to ``true`` to replace occurrences of the reference domain name with the new domain name in data fields (of records) on the cloned (new) domain. Does not affect NS records. + :param bool $records: Set to ``true`` to replace occurrences of the reference domain name with the new domain name in data fields (of records) on the cloned (new) domain. Does not affect NS records. + + +For example: + +.. code-block:: php + + $asyncResponse = $domain->cloneDomain('new-name.com', true, false, true, false); + + +Export domain +------------- + +This call provides access to the `BIND `_ +(Berkeley Internet Name Domain) 9 for the requested domain. This call is for a +single domain only, and as such, does not traverse up or down the domain +hierarchy for details: + +.. code-block:: php + + $asyncResponse = $domain->export(); + + $body = $asyncResponse->waitFor('COMPLETED'); + echo $body['contents']; + + +Import domain +------------- + +This operation will create a new DNS domain according to a `BIND `_ +(Berkeley Internet Name Domain) 9 formatted value. + +In order for the BIND value to be considered valid, it needs to adhere to the +following rules: + +* Each record starts on a new line and on the first column. If a record will + not fit on one line, use the BIND\_9 line continuation convention where you put + a left parenthesis and continue the one record on the next line and put a right + parenthesis when the record ends. For example: + + example2.net. 3600 IN SOA dns1.stabletransit.com. (sample@rackspace.com. 1308874739 3600 3600 3600 3600) + +* The attribute values of a record must be separated by a single blank or tab. + No other white space characters. + +* If there are any NS records, the data field should not be + ``dns1.stabletransit.com`` or ``dns2.stabletransit.com``. They will result in + "duplicate record" errors. + +For example: + +.. code-block:: php + + $bind9Data = <<import($bind9Data); + + +Modify domain +------------- + +Only the TTL, email address and comment attributes of a domain can be modified. +Records cannot be added, modified, or removed through this API operation - you +will need to use the `add records `__, `modify records +`__ or `remove records `__ +operations respectively. + +.. code-block:: php + + $domain->update(array( + 'ttl' => ($domain->ttl + 100), + 'emailAddress' => 'new_dev@foo.com' + )); + + +Delete domain +------------- + +.. code-block:: php + + $domain->delete(); diff --git a/doc/services/dns/index.rst b/doc/services/dns/index.rst index e69de29bb..4caca9fe5 100644 --- a/doc/services/dns/index.rst +++ b/doc/services/dns/index.rst @@ -0,0 +1,51 @@ +DNS v1 +====== + +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now, set up the DNS service: + +.. code-block:: php + + $service = $client->dnsService(); + + +Operations +---------- + +.. toctree:: + + records + domains + limits + reverse-dns + + +Glossary +-------- + + domain + A domain is an entity/container of all DNS-related information containing + one or more records. + + record + A DNS record belongs to a particular domain and is used to specify + information about the domain. There are several types of DNS records. Each + record type contains particular information used to describe that record's + purpose. Examples include mail exchange (MX) records, which specify the + mail server for a particular domain, and name server (NS) records, which + specify the authoritative name servers for a domain. + + subdomain + Subdomains are domains within a parent domain, and subdomains cannot be + registered. Subdomains allow you to delegate domains. Subdomains can + themselves have subdomains, so third-level, fourth-level, fifth-level, and + deeper levels of nesting are possible. + + pointer records + DNS usually determines an IP address associated with a domain name. + Reverse DNS is the opposite process: resolving a domain name from an IP + address. This is usually achieved with a domain name pointer. diff --git a/doc/services/dns/Limits.md.rst b/doc/services/dns/limits.rst similarity index 59% rename from doc/services/dns/Limits.md.rst rename to doc/services/dns/limits.rst index 72f8219a0..289c3888d 100644 --- a/doc/services/dns/Limits.md.rst +++ b/doc/services/dns/limits.rst @@ -1,22 +1,15 @@ Limits ====== -Setup ------ - -Limit methods will be called on the DNS service, an instance of -``OpenCloud\DNS\Service``. Please see the `DNS service `__ -documentation for setup instructions. - List all limits --------------- -This call provides a list of all applicable limits for the specified -account. +This call provides a list of all applicable limits for the specified account. .. code:: php - $limits = $service->limits(); + $limits = $service->limits(); + Absolute limits ~~~~~~~~~~~~~~~ @@ -29,12 +22,13 @@ domain: $absoluteLimits = $limits->absolute; - # Domain limit + // Domain limit echo $absoluteLimits->domains; - # Record limit per domain + // Record limit per domain echo $absoluteLimits->{'records per domain'}; + List limit types ---------------- @@ -42,20 +36,17 @@ To find out the different limit types you can query, run: .. code:: php - $limitTypes = $service->limitTypes(); + $limitTypes = $service->limitTypes(); will return: :: - array(3) { - [0] => - string(10) "RATE_LIMIT" - [1] => - string(12) "DOMAIN_LIMIT" - [2] => - string(19) "DOMAIN_RECORD_LIMIT" - } + array(3) { + [0] => string(10) "RATE_LIMIT" + [1] => string(12) "DOMAIN_LIMIT" + [2] => string(19) "DOMAIN_RECORD_LIMIT" + } Query a specific limit ---------------------- @@ -63,8 +54,4 @@ Query a specific limit .. code:: php $limit = $service->limits('DOMAIN_LIMIT'); - echo $limit->absolute->limits->value; - - >>> 500 - diff --git a/doc/services/dns/records.rst b/doc/services/dns/records.rst new file mode 100644 index 000000000..26e17ee5e --- /dev/null +++ b/doc/services/dns/records.rst @@ -0,0 +1,113 @@ +Records +======= + +Setup +----- + +In order to interact with the functionality of records, you must first +retrieve the details of the domain itself. To do this, you must substitute +`{domainId}` for your domain's ID: + +.. code-block:: php + + $domain = $service->domain('{domainId}'); + + +Get record +---------- + +In order to retrieve details for a specific DNS record, you will need +its **id**: + +.. code:: php + + $record = $domain->record('{recordId}'); + +If you do not have this ID at your disposal, you can traverse the record +collection and do a string comparison (detailed below). + + +List records +------------ + +This call lists all records configured for the specified domain. + +.. code:: php + + $records = $domain->recordList(); + + foreach ($records as $record) { + printf("Record name: %s, ID: %s, TTL: %s\n", $record->name, $record->id, $record->ttl); + } + + +Query parameters +~~~~~~~~~~~~~~~~ + +You can pass in an array of query parameters for greater control over +your search: + ++------------+--------------+------------------------+ +| Name | Data type | Description | ++============+==============+========================+ +| ``type`` | ``string`` | The record type | ++------------+--------------+------------------------+ +| ``name`` | ``string`` | The record name | ++------------+--------------+------------------------+ +| ``data`` | ``string`` | Data for this record | ++------------+--------------+------------------------+ + + +Find a record ID from its name +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For example: + +.. code:: php + + $records = $domain->recordList(array( + 'name' => 'imap.example.com', + 'type' => 'MX' + )); + + foreach ($records as $record) { + $recordId = $record->id; + } + + +Add record +---------- + +This call adds a new record to the specified domain: + +.. code:: php + + $record = $domain->record(array( + 'type' => 'A', + 'name' => 'example.com', + 'data' => '192.0.2.17', + 'ttl' => 3600 + )); + + $record->create(); + + +Please be aware that records that are added with a different hostname +than the parent domain might fail silently. + +Modify record +------------- + +.. code:: php + + $record = $domain->record('{recordId}'); + $record->ttl -= 100; + $record->update(); + + +Delete record +------------- + +.. code:: php + + $record->delete(); diff --git a/doc/services/dns/Reverse-DNS.md.rst b/doc/services/dns/reverse-dns.rst similarity index 82% rename from doc/services/dns/Reverse-DNS.md.rst rename to doc/services/dns/reverse-dns.rst index b8a5c0e76..4d0eb671c 100644 --- a/doc/services/dns/Reverse-DNS.md.rst +++ b/doc/services/dns/reverse-dns.rst @@ -1,9 +1,6 @@ Reverse DNS =========== -DNS usually determines an IP address associated with a domain name. -Reverse DNS is the opposite process: resolving a domain name from an IP -address. This is usually achieved with a domain name pointer. Get PTR record -------------- @@ -20,14 +17,15 @@ formed resource object in order to retrieve either one's PTR record: 'parent' => $parent )); -So, in the above example, a ``$parent`` could be an instance of +So, in the above example, the ``$parent`` object could be an instance of ``OpenCloud\Compute\Resource\Server`` or ``OpenCloud\LoadBalancer\Resource\LoadBalancer`` - because they both implement ``OpenCloud\DNS\Resource\HadPtrRecordsInterface``. Please -consult the `server documentation <../Compute/Server.md>`__ and `load -balancer documentation <../LoadBalancer/USERGUIDE.md>`__ for more +consult the `server documentation <../compute>`__ and `load +balancer documentation <../load-balancer>`__ for more detailed usage instructions. + List PTR records ---------------- @@ -41,9 +39,6 @@ List PTR records } -Please consult the `iterator -documentation `__ for more information -about iterators. Add PTR record -------------- @@ -78,19 +73,20 @@ Here is a table that explains the above attributes: | comment | If included, its length must be less than or equal to 160 characters. | No | +-----------+------------------------------------------------------------------------------------+------------+ + Modify PTR record ----------------- .. code:: php - $ptr->update(array( - 'ttl' => $ptr->ttl * 2 - )); + $ptr->update(array( + 'ttl' => $ptr->ttl * 2 + )); + Delete PTR record ----------------- .. code:: php - $ptr->delete(); - + $ptr->delete(); From f46fb834cdaa94351778bd80c5a959f9c13d7ae4 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 4 Mar 2015 13:50:23 +0100 Subject: [PATCH 119/181] Add DB docs --- doc/services/database/README.md.rst | 125 ------------------ doc/services/database/configurations.rst | 127 +++++++++++++++++++ doc/services/database/databases.rst | 60 +++++++++ doc/services/database/datastores.rst | 59 +++++++++ doc/services/database/index.rst | 69 ++++++++++ doc/services/database/instances.rst | 155 +++++++++++++++++++++++ doc/services/database/users.rst | 67 ++++++++++ 7 files changed, 537 insertions(+), 125 deletions(-) delete mode 100644 doc/services/database/README.md.rst create mode 100644 doc/services/database/configurations.rst create mode 100644 doc/services/database/databases.rst create mode 100644 doc/services/database/datastores.rst create mode 100644 doc/services/database/instances.rst create mode 100644 doc/services/database/users.rst diff --git a/doc/services/database/README.md.rst b/doc/services/database/README.md.rst deleted file mode 100644 index 3f6bdd3c2..000000000 --- a/doc/services/database/README.md.rst +++ /dev/null @@ -1,125 +0,0 @@ -Databases -========= - -A **cloud database** is a MySQL relational database service that allows -customers to programatically provision database instances of varying -virtual resource sizes without the need to maintain and/or update MySQL. - -Getting started ---------------- - -1. Instantiate a Rackspace client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - use OpenCloud\Rackspace; - use OpenCloud\Common\Constants\State; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -2. Create a database server instance. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $databaseService = $client->databaseService('cloudDatabases', 'DFW'); - - $twoGbFlavor = $databaseService->flavor(3); - - $dbInstance = $databaseService->instance(); - $dbInstance->name = 'Demo database instance'; - $dbInstance->volume = new stdClass(); - $dbInstance->volume->size = 20; // GB - $dbInstance->flavor = $twoGbFlavor; - $dbInstance->create(); - - $dbInstance->waitFor(State::ACTIVE, null, function ($dbInstance) { - - printf("Database instance build status: %s\n", $dbInstance->status); - - }); - -The example above creates a database server instance with 20GB of disk -space and 2GB of memory, then waits for it to become ACTIVE. - -3. Create a database on the database server instance. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $db = $dbInstance->database(); - $db->name = 'demo_db'; - - $db->create(); - -The example above creates a database named ``demo_db`` on the database -server instance created in the previous step. - -4. Create database user and give it access to database. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $user = $dbInstance->user(); - $user->name = 'demo_user'; - $user->password = 'h@X0r!'; - $user->databases = array('demo_db'); - - $user->create(); - -The example above creates a database user named ``demo_user``, sets its -password and gives it access to the ``demo_db`` database created in the -previous step. - -5. Optional step: Create a load balancer to allow access to the database from the Internet. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The database created in the previous step can only be accessed from the -Rackspace private network (aka ``SERVICENET``). If you have a cloud -server instance in the same region as the database server instance, you -will be able to connect to the database from that cloud server instance. - -If, however, you would like to access the database from the Internet, -you will need to create a load balancer with an IP address that is -routable from the Internet and attach the database server instance as a -back-end node of this load balancer. - -.. code:: php - - $loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); - - $loadBalancer = $loadBalancerService->loadBalancer(); - - $loadBalancer->name = 'Load balancer - DB'; - $loadBalancer->addNode($dbInstance->hostname, 3306); - $loadBalancer->port = 3306; - $loadBalancer->protocol = 'MYSQL'; - $loadBalancer->addVirtualIp('PUBLIC'); - - $loadBalancer->create(); - - $loadBalancer->waitFor(State::ACTIVE, null, function ($lb) { - printf("Load balancer build status: %s\n", $lb->status); - }); - - foreach ($loadBalancer->virtualIps as $vip) { - if ($vip->type == 'PUBLIC') { - printf("Load balancer public %s address: %s\n", $vip->ipVersion, $vip->address); - } - } - -In the example above, a load balancer is created with the database -server instance as its only back-end node. Further, this load balancer -is configured to listen for MySQL connections on port 3306. Finally a -virtual IP address (VIP) is configured in the ``PUBLIC`` network address -space so that this load balancer may receive connections from the -Internet. - -Once the load balancer is created and becomes ``ACTIVE``, it's -Internet-accessible IP addresses are printed out. If you connect to any -of these IP addresses on port 3306 using the MySQL protocol, you will be -connected to the database created in step 3. diff --git a/doc/services/database/configurations.rst b/doc/services/database/configurations.rst new file mode 100644 index 000000000..edfb9dc89 --- /dev/null +++ b/doc/services/database/configurations.rst @@ -0,0 +1,127 @@ +Configurations +============== + +Creating a configuration +------------------------ + +.. code-block:: php + + /** @var $configuration OpenCloud\Database\Resource\Configuration **/ + $configuration = $service->configuration(); + + $configuration->create(array( + 'name' => 'example-configuration-name', + 'description' => 'An example configuration', + 'values' => array( + 'collation_server' => 'latin1_swedish_ci', + 'connect_timeout' => 120 + ), + 'datastore' => array( + 'type' => '10000000-0000-0000-0000-000000000001', + 'version' => '1379cc8b-4bc5-4c4a-9e9d-7a9ad27c0866' + ) + )); + +`Get the executable PHP script for this example `__ + + +Listing configurations +---------------------- + +You can list out all the configurations you have created as shown below: + +.. code-block:: php + + $configurations = $service->configurationList(); + foreach ($configurations as $configuration) { + /** @var $configuration OpenCloud\Database\Resource\Configuration **/ + } + +`Get the executable PHP script for this example `__ + + +Retrieving a configuration +-------------------------- + +You can retrieve a specific configuration, using its ID, as shown below: + +.. code-block:: php + + $configuration = $service->configuration('{configId}'); + /** @var OpenCloud\Database\Resource\Configuration **/ + +`Get the executable PHP script for this example `__ + + +Updating a configuration +------------------------ + +You have two choices when updating a configuration: + +* you can `patch a configuration <#patching-a-configuration>`__ to change only +some configuration parameters +* you can `entirely replace a configuration <#replacing-a-configuration>`__ to +replace all configuration parameters with new ones + + +Patching a configuration +~~~~~~~~~~~~~~~~~~~~~~~~ + +You can patch a configuration as shown below: + +.. code-block:: php + + $configuration->patch(array( + 'values' => array( + 'connect_timeout' => 30 + ) + )); + +`Get the executable PHP script for this example `__ + + +Replacing a configuration +~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can replace a configuration as shown below: + +.. code-block:: php + + $configuration->update(array( + 'values' => array( + 'collation_server' => 'utf8_general_ci', + 'connect_timeout' => 60 + ) + )); + +`Get the executable PHP script for this example `__ + + +Deleting a configuration +------------------------ + +.. code-block:: php + + $configuration->delete(); + +`Get the executable PHP script for this example `__ + +.. note:: + + You cannot delete a configuration if it is in use by a running instance. + + +Listing instances using a configuration +--------------------------------------- + +You can list all instances using a specific configuration, using its ID, +as shown below: + +.. code-block:: php + + $instances = $configuration->instanceList(); + foreach ($instances as $instance) { + /** @var $instance OpenCloud\Database\Resource\Instance **/ + } + +`Get the executable PHP script for this example `__ diff --git a/doc/services/database/databases.rst b/doc/services/database/databases.rst new file mode 100644 index 000000000..83d07c5e2 --- /dev/null +++ b/doc/services/database/databases.rst @@ -0,0 +1,60 @@ +Databases +========= + +Setup +----- + +In order to interact with the functionality of databases, you must first +retrieve the details of the instance itself. To do this, you must substitute +`{instanceId}` for your instance's ID: + +.. code-block:: php + + $instance = $service->instance('{instanceId}'); + + +Creating a new database +----------------------- + +To create a new database, you must supply it with a name; you can +optionally specify its character set and collating sequence: + +.. code-block:: php + + // Create an empty object + $database = $instance->database(); + + // Send to API + $database->create(array( + 'name' => 'production', + 'character_set' => 'utf8', + 'collate' => 'utf8_general_ci' + )); + +You can find values for ``character_set`` and ``collate`` at `the MySQL +website `__. + + +Deleting a database +------------------- + +.. code-block:: php + + $database->delete(); + +.. note:: + + This is a destructive operation: all your data will be wiped away and will + not be retrievable. + + +Listing databases +----------------- + +.. code-block:: php + + $databases = $service->databaseList(); + + foreach ($databases as $database) { + /** @param $database OpenCloud\Database\Resource\Database */ + } diff --git a/doc/services/database/datastores.rst b/doc/services/database/datastores.rst new file mode 100644 index 000000000..6ca45daed --- /dev/null +++ b/doc/services/database/datastores.rst @@ -0,0 +1,59 @@ +Datastores +========== + +Listing datastores +------------------ + +You can list out all the datastores available as shown below: + +.. code-block:: php + + $datastores = $service->datastoreList(); + foreach ($datastores as $datastore) { + /** @var $datastore OpenCloud\Database\Resource\Datastore **/ + } + +`Get the executable PHP script for this example `__ + + +Retrieving a datastore +---------------------- + +You can retrieve a specific datastore's information, using its ID, as +shown below: + +.. code-block:: php + + /** @var OpenCloud\Database\Resource\Datastore **/ + $datastore = $service->datastore('{datastoreId}'); + +`Get the executable PHP script for this example `__ + + +Listing datastore versions +-------------------------- + +You can list out all the versions available for a specific datastore, as +shown below: + +.. code-block:: php + + $versions = $datastore->versionList(); + foreach ($versions as $version) { + /** @var $version OpenCloud\Database\Resource\DatastoreVersion **/ + } + +`Get the executable PHP script for this example `__ + + +Retrieving a datastore version +------------------------------ + +You a retrieve a specific datastore version, using its ID, as shown +below: + +.. code-block:: php + + $datastoreVersion = $datastore->version('{versionId}'); + +`Get the executable PHP script for this example `__ diff --git a/doc/services/database/index.rst b/doc/services/database/index.rst index e69de29bb..850e56c8a 100644 --- a/doc/services/database/index.rst +++ b/doc/services/database/index.rst @@ -0,0 +1,69 @@ +Databases v1 +============ + +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now, set up the Database service: + +.. code-block:: php + + $service = $client->databaseService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + +.. toctree:: + + instances + databases + users + datastores + + +Glossary +-------- + +.. glossary:: + + configuration group + A configuration group is a collection of key/value pairs which configure a + database instance. Some directives are capable of being applied dynamically, + while other directives require a server restart to take effect. The + configuration group can be applied to an instance at creation or applied to + an existing instance to modify the behavior of the running datastore on the + instance. + + flavor + A flavor is an available hardware configuration for a database instance. + Each flavor has a unique combination of memory capacity and priority for + CPU time. + + instance + A database instance is an isolated MySQL instance in a single tenant + environment on a shared physical host machine. Also referred to as + instance. + + database + A database is a local MySQL database running on an instance. + + user + A user is a local MySQL user that can access a database running on an + instance. + + datastore + The database engine running on your instance. Currently, there is support + for MySQL 5.6, MySQL 5.1, Percona 5.6 and MariaDB 10. + + volume + A volume is user-specified storage that contains the database engine data + directory. Volumes are automatically provisioned on shared Internet Small + Computer System Interface (iSCSI) storage area networks (SAN) that provide + for increased performance, scalability, availability and manageability. + Applications with high I/O demands are performance optimized and data is + protected through both local and network RAID-10. diff --git a/doc/services/database/instances.rst b/doc/services/database/instances.rst new file mode 100644 index 000000000..082e56c05 --- /dev/null +++ b/doc/services/database/instances.rst @@ -0,0 +1,155 @@ +Instances +========= + +Create a new instance +--------------------- + +.. code-block:: php + + // Create an empty object + $instance = $service->instance(); + + // Send to the API + $instance->create(array( + 'name' => '{name}', + 'flavor' => $service->flavor('{flavorId}'), + 'volume' => array('size' => 4) // 4GB of volume disk + )); + +`Get the executable PHP script for this sample `__ + + +Waiting for the instance to build +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The SDK provides a blocking operation that will wait until your instance resource +has transitioned into an ``ACTIVE`` state. During this period, it will +continuously poll the API and break the loop when the state has been achieved: + +.. code-block:: php + + $instance->waitFor('ACTIVE', null, function ($instance) { + // This will be executed continuously + printf("Database instance build status: %s\n", $instance->status); + }); + + +Connecting an instance to a load balancer +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The instance created in the previous step can only be accessed from the +Rackspace private network (aka ``SERVICENET``). If you have a cloud +server instance in the same region as the database server instance, you +will be able to connect to the database from that cloud server instance. + +If, however, you would like to access the database from the Internet, +you will need to create a load balancer with an IP address that is +routable from the Internet and attach the database server instance as a +back-end node of this load balancer. + +.. code-block:: php + + $lbService = $client->loadBalancerService(null, '{region}'); + + // Create empty object + $loadBalancer = $lbService->loadBalancer(); + + // Associate this LB with the instance as a "node" + $loadBalancer->addNode($instance->hostname, 3306); + $loadBalancer->addVirtualIp('PUBLIC'); + + // Configure other parameters and send to the API + $loadBalancer->create(array( + 'name' => 'DB Load Balancer', + 'port' => 3306, + 'protocol' => 'MYSQL', + )); + + // Wait for the resource to create + $loadBalancer->waitFor('ACTIVE', null, function ($loadBalancer) { + printf("Load balancer build status: %s\n", $loadBalancer->status); + }); + + foreach ($loadBalancer->virtualIps as $vip) { + if ($vip->type == 'PUBLIC') { + printf("Load balancer public %s address: %s\n", $vip->ipVersion, $vip->address); + } + } + +In the example above, a load balancer is created with the database +server instance as its only back-end node. Further, this load balancer +is configured to listen for MySQL connections on port 3306. Finally a +virtual IP address (VIP) is configured in the ``PUBLIC`` network address +space so that this load balancer may receive connections from the +Internet. + +Once the load balancer is created and becomes ``ACTIVE``, it's +Internet-accessible IP addresses are printed out. If you connect to any +of these IP addresses on port 3306 using the MySQL protocol, you will be +connected to the database created in step 3. + + +Retrieving an instance +---------------------- + +.. code-block:: php + + $instance = $service->instance('{instanceId}'); + +`Get the executable PHP script for this example `__ + + +Updating an instance +-------------------- + +An instance can be updated to use a specific `configuration `__ as shown below. + +.. code-block:: php + + $instance->update(array( + 'configuration' => '{configurationId}' + )); + +.. note:: + + If any parameters in the associated configuration require a restart, then you + will need to `restart the instance <#restarting-an-instance>`__ after the update. + + +Deleting an instance +-------------------- + +.. code-block:: php + + $instance->delete(); + + +Restarting an instance +---------------------- + +.. code-block:: php + + $instance->restart(); + + +Resizing an instance's RAM +-------------------------- + +To change the amount of RAM allocated to the instance: + +.. code-block:: php + + $flavor = $service->flavor('{flavorId}'); + $instance->resize($flavor); + + +Resizing an instance's volume +----------------------------- + +You can also independently change the volume size to increase the disk +space: + +.. code-block:: php + + // Increase to 8GB disk + $instance->resizeVolume(8); diff --git a/doc/services/database/users.rst b/doc/services/database/users.rst new file mode 100644 index 000000000..0343c4904 --- /dev/null +++ b/doc/services/database/users.rst @@ -0,0 +1,67 @@ +Users +===== + +Setup +----- + +Finally, in order to interact with the functionality of databases, you must +first retrieve the details of the instance itself. To do this, you must +substitute `{instanceId}` for your instance's ID: + +.. code-block:: php + + $instance = $service->instance('{instanceId}'); + + +Creating users +-------------- + +Database users exist at the ``Instance`` level, but can be associated +with a specific ``Database``. They are represented by the +``OpenCloud\Database\Resource\User`` class. + +.. code-block:: php + + // New instance of OpenCloud\Database\Resource\User + $user = $instance->user(); + + // Send to API + $user->create(array( + 'name' => 'Alice', + 'password' => 'fooBar' + 'databases' => array('production') + )); + + +Deleting a user +--------------- + +.. code-block:: php + + $user->delete(); + + +The root user +------------- + +By default, Cloud Databases does not enable the root user. In most +cases, the root user is not needed, and having one can leave you open to +security violations. However, if you do want to enable access to the root user: + +.. code-block:: php + + $rootUser = $instance->enableRootUser(); + + +This returns a regular ``User`` object with the ``name`` attribute set +to ``root`` and the ``password`` attribute set to an auto-generated +password. + + +Check if root user is enabled +----------------------------- + +.. code-block:: php + + // true for yes, false for no + $instance->isRootEnabled(); From f29826dc43bf6aac97eb67a3e87f3ce7560f9b5c Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 4 Mar 2015 15:16:07 +0100 Subject: [PATCH 120/181] Identity docs --- doc/services/identity/Service.md.rst | 35 ----- doc/services/identity/Tenants.md.rst | 29 ---- doc/services/identity/Tokens.md.rst | 105 ------------- doc/services/identity/index.rst | 46 ++++++ .../identity/{Roles.md.rst => roles.rst} | 0 doc/services/identity/tenants.rst | 26 ++++ doc/services/identity/tokens.rst | 101 +++++++++++++ .../identity/{Users.md.rst => users.rst} | 139 ++++++++---------- 8 files changed, 238 insertions(+), 243 deletions(-) delete mode 100644 doc/services/identity/Service.md.rst delete mode 100644 doc/services/identity/Tenants.md.rst delete mode 100644 doc/services/identity/Tokens.md.rst rename doc/services/identity/{Roles.md.rst => roles.rst} (100%) create mode 100644 doc/services/identity/tenants.rst create mode 100644 doc/services/identity/tokens.rst rename doc/services/identity/{Users.md.rst => users.rst} (79%) diff --git a/doc/services/identity/Service.md.rst b/doc/services/identity/Service.md.rst deleted file mode 100644 index f7e8e12ba..000000000 --- a/doc/services/identity/Service.md.rst +++ /dev/null @@ -1,35 +0,0 @@ -Identity service -================ - -Intro ------ - -The Identity service is regionless, so you do not need to specify a -region when instantiating the service object. Although this was -primarily based on Rackspace's implementation of Cloud Identity, it -should also work for OpenStack Keystone. - -A note on object creation -------------------------- - -Normally, when services are created the client handles authenticates -automatically. But because Keystone/Identity is fundamental to the -authentication process itself, it proves difficult to do this procedure -as its normally done. For this reason, you have two options when -creating the service object: - -1: Use the client's factory method - -.. code:: php - - $identity = $client->identityService(); - -2: Authenticate manually - -.. code:: php - - use OpenCloud\Identity\Service as IdentityService; - - $identity = IdentityService::factory($client); - $identity->getClient()->authenticate(); - diff --git a/doc/services/identity/Tenants.md.rst b/doc/services/identity/Tenants.md.rst deleted file mode 100644 index 9b58efd1a..000000000 --- a/doc/services/identity/Tenants.md.rst +++ /dev/null @@ -1,29 +0,0 @@ -Tenants -======= - -Intro ------ - -A tenant is a container used to group or isolate resources and/or -identity objects. Depending on the service operator, a tenant may map to -a customer, account, organization, or project. - -Setup ------ - -Tenant objects are instantiated from the Identity service. For more -details, see the `Service `__ docs. - -List tenants ------------- - -.. code:: php - - $tenants = $service->getTenants(); - - foreach ($tenants as $tenant) { - // ... - } - -For more information about how to use iterators, see the -`documentation <../Iterators.md>`__. diff --git a/doc/services/identity/Tokens.md.rst b/doc/services/identity/Tokens.md.rst deleted file mode 100644 index c42ce1573..000000000 --- a/doc/services/identity/Tokens.md.rst +++ /dev/null @@ -1,105 +0,0 @@ -Tokens -====== - -Intro ------ - -A token is an opaque string that represents an authorization to access -cloud resources. Tokens may be revoked at any time and are valid for a -finite duration. - -Setup ------ - -Token objects are instantiated from the Identity service. For more -details, see the `Service `__ docs. - -Useful object properties/methods --------------------------------- - -+------------+-------------------------------------------+----------------------------------------+--------------------+ -| Property | Description | Getter | Setter | -+============+===========================================+========================================+====================+ -| id | The unique ID of the token | ``getId()`` | ``setId()`` | -+------------+-------------------------------------------+----------------------------------------+--------------------+ -| expires | Timestamp of when the token will expire | ``getExpires()`` or ``hasExpired()`` | ``setExpires()`` | -+------------+-------------------------------------------+----------------------------------------+--------------------+ - -Create token (authenticate) ---------------------------- - -In order to generate a token, you must pass in the JSON template that is -sent to the API. This is because Rackspace's operation expects a -slightly different entity body than OpenStack Keystone. - -Request body for Rackspace's generate token operation: - -.. code:: json - - { - "auth": { - "RAX-KSKEY:apiKeyCredentials": { - "username": "foo", - "apiKey": "aaaaa-bbbbb-ccccc-12345678" - }, - "tenantId": "1100111" - } - } - -Request body for Keystone's generate token operation: - -.. code:: json - - { - "auth": { - "passwordCredentials":{ - "username":"demoauthor", - "password":"theUsersPassword" - }, - "tenantId": "12345678" - } - } - -The only real differences you'll notice is the name of the object key -(``RAX-KSKEY:apiKeyCredentials``/``passwordCredentials``) and the secret -(``apiKey``/``password``). The ``tenantId`` property in both templates -are optional. You can also add ``tenantName`` too. - -.. code:: php - - use OpenCloud\Common\Http\Message\Formatter; - - $template = sprintf( - '{"auth": {"RAX-KSKEY:apiKeyCredentials":{"username": "%s", "apiKey": "%s"}}}', - 'my_username', - 'my_api_key' - ); - - $response = $service->generateToken($template); - - $body = Formatter::decode($response); - - // service catalog - $catalog = $body->access->serviceCatalog; - - // token - $token = $body->access->token; - - // user - $user = $body->access->user; - -As you will notice, these variables will be stdClass objects - for fully -fledged functionality, let the client authenticate by itself because it -ends up stocking the necessary models for you. - -To see the response body structure, consult the `official -docs `__. - -Revoke token (destroy session) ------------------------------- - -.. code:: php - - $tokenId = '1234567'; - $service->revokeToken($tokenId); - diff --git a/doc/services/identity/index.rst b/doc/services/identity/index.rst index e69de29bb..35c27131b 100644 --- a/doc/services/identity/index.rst +++ b/doc/services/identity/index.rst @@ -0,0 +1,46 @@ +Identity v2 +=========== + +Setup +----- + +.. include:: ../common/rs-client.sample + +.. code-block:: php + + $service = $client->identityService(); + + +Operations +---------- + +.. toctree:: + + tokens + users + tenants + +Glossary +-------- + +.. glossary:: + + token + A token is an opaque string that represents an authorization to access + cloud resources. Tokens may be revoked at any time and are valid for a + finite duration. + + tenant + A tenant is a container used to group or isolate resources and/or + identity objects. Depending on the service operator, a tenant may map to + a customer, account, organization, or project. + + user + A user is a digital representation of a person, system, or service who + consumes cloud services. Users have credentials and may be assigned + tokens; based on these credentials and tokens, the authentication + service validates that incoming requests are being made by the user who + claims to be making the request, and that the user has the right to + access the requested resources. Users may be directly assigned to a + particular tenant and behave as if they are contained within that + tenant. diff --git a/doc/services/identity/Roles.md.rst b/doc/services/identity/roles.rst similarity index 100% rename from doc/services/identity/Roles.md.rst rename to doc/services/identity/roles.rst diff --git a/doc/services/identity/tenants.rst b/doc/services/identity/tenants.rst new file mode 100644 index 000000000..a27417cca --- /dev/null +++ b/doc/services/identity/tenants.rst @@ -0,0 +1,26 @@ +Tenants +======= + +List tenants +------------ + +.. code-block:: php + + $tenants = $service->getTenants(); + + foreach ($tenants as $tenant) { + // ... + } + +Tenant object properties and methods +------------------------------------ + +Once you have a ``OpenCloud\Identity\Resource\Tenant`` object, you can retrieve +information like so: + +.. code-block:: php + + $tenant->getId(); + $tenant->getName(); + $tenant->getDescription(); + $tenant->isEnabled(); diff --git a/doc/services/identity/tokens.rst b/doc/services/identity/tokens.rst new file mode 100644 index 000000000..f49484105 --- /dev/null +++ b/doc/services/identity/tokens.rst @@ -0,0 +1,101 @@ +Tokens +====== + +Create token (authenticate) +--------------------------- + +In order to generate a token, you must pass in the JSON template that is +sent to the API. This is because Rackspace's operation expects a +slightly different entity body than OpenStack Keystone. + +To do this, and then generate a token: + +.. code-block:: php + + $json = $client->getCredentials(); + + /** @var $response Guzzle\Http\Message\Response */ + $response = $service->generateToken($json); + $jsonBody = $response->json(); + +When a token is generated by the API, there are a few things returned: + +* a `service catalog `_ + outlining all of the services you can interact with, + including their names, service types, and endpoint URLs. Which services + make up your catalog, and how your catalog is structured, will depend on + your service provider. + +* details about your token, such as its ID, created and expiration date + +* details about your user account + +* details about your tenant + +Interacting with the service catalog +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once you have the ``$jsonBody``, you can construct a ``Catalog`` object for +easier interaction: + +.. code-block:: php + + $data = $jsonBody->access->serviceCatalog; + $catalog = OpenCloud\Common\Service\Catalog::factory($data); + + foreach ($catalog->getItems() as $service) { + /** @param $service OpenCloud\Common\Service\CatalogItem */ + printf("Catalog item: Name [%s] Type [%s]\n", $service->getName(), $service->getType()); + + foreach ($service->getEndpoints() as $endpoint) { + printf(" Endpoint provided: Region [%s] PublicURL [%s] PrivateURL [%s]\n", + $endpoint->getRegion(), $endpoint->getPublicUrl(), $endpoint->getPrivateUrl()); + } + } + +Interacting with tokens +~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $data = $jsonBody->access->token; + $token = $service->resource('Token', $data); + + printf("Token ID: %s - Token expiry %s", $token->getId(), $token->getExpires()); + + if ($token->hasExpired()) { + // ... + } + +Interacting with users +~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $data = $jsonBody->access->user; + $user = $service->resource('User', $data); + +To see which methods you can call on ``$user`` (which implements +``OpenCloud\Identity\Resource\User``), see our `user documentation `_ +which accompanies this guide. + + +Interacting with tenants +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $data = $jsonBody->access->tenant; + $tenant = $service->resource('Tenant', $data); + +To see which methods you can call on ``$tenant`` (which implements +``OpenCloud\Identity\Resource\Tenant``), see our `user documentation `_ +which accompanies this guide. + + +Revoke token (destroy session) +------------------------------ + +.. code-block:: php + + $service->revokeToken('{tokenId}'); diff --git a/doc/services/identity/Users.md.rst b/doc/services/identity/users.rst similarity index 79% rename from doc/services/identity/Users.md.rst rename to doc/services/identity/users.rst index e8c2e6d63..b55236a74 100644 --- a/doc/services/identity/Users.md.rst +++ b/doc/services/identity/users.rst @@ -1,26 +1,9 @@ Users ===== -Intro ------ -A user is a digital representation of a person, system, or service who -consumes cloud services. Users have credentials and may be assigned -tokens; based on these credentials and tokens, the authentication -service validates that incoming requests are being made by the user who -claims to be making the request, and that the user has the right to -access the requested resources. Users may be directly assigned to a -particular tenant and behave as if they are contained within that -tenant. - -Setup ------ - -User objects are instantiated from the Identity service. For more -details, see the `Service `__ docs. - -Useful object properties/methods --------------------------------- +Object properties/methods +------------------------- +-----------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------+---------------------------------------------------------------------------------------------------------------+ | Property | Description | Getter | Setter | @@ -43,74 +26,78 @@ Useful object properties/methods List users ---------- -.. code:: php +.. code-block:: php + + $users = $service->getUsers(); + + foreach ($users as $user) { + // ... + } - $users = $service->getUsers(); - foreach ($users as $user) { - // ... - } +Retrieve a user by username +--------------------------- -For more information about how to use iterators, see the -`documentation <../Iterators.md>`__. +.. code-block:: php -Get user --------- + $user = $service->getUser('jamie'); -There are various ways to get a specific user: by name, ID and email -address. -.. code:: php +Retrieve a user by user ID +-------------------------- - use OpenCloud\Identity\Constants\User as UserConst; +.. code-block:: php + + use OpenCloud\Identity\Constants\User as UserConst; + + $user = $service->getUser('{userId}', UserConst::MODE_ID); + + +Retrieve a user by email address +-------------------------------- - // Get user by name - $user1 = $service->getUser('jamie'); +.. code-block:: php - // Get user by ID - $user2 = $service->getUser(123456, UserConst::MODE_ID); + use OpenCloud\Identity\Constants\User as UserConst; + + $user = $service->getUser('{emailAddress}', UserConst::MODE_EMAIL); - // Get user by email - $user3 = $service->getUser('jamie.hannaford@rackspace.com', UserConst::MODE_EMAIL); Create user ----------- -There are a few things to remember when creating a user: +There are a few things to bear in mind when creating a user: -- This operation is available only to users who hold the +* This operation is available only to users who hold the ``identity:user-admin`` role. This admin can create a user who holds the ``identity:default`` user role. -- The created user **will** have access to APIs but **will not** have +* The created user **will** have access to APIs but **will not** have access to the Cloud Control Panel. -- Within an account, a maximum of 100 account users can be added. +* A maximum of 100 account users can be added per account. -- If you attempt to add a user who already exists, an HTTP error 409 +* If you attempt to add a user who already exists, an HTTP error 409 results. + The ``username`` and ``email`` properties are required for creating a user. Providing a ``password`` is optional; if omitted, one will be automatically generated and provided in the response. -.. code:: php - use Guzzle\Http\Exception\ClientErrorResponseException; +.. code-block:: php + + use Guzzle\Http\Exception\ClientErrorResponseException; - try { - // execute operation - $user = $service->createUser(array( - 'username' => 'newUser', - 'email' => 'foo@bar.com' - )); - } catch (ClientErrorResponseException $e) { - // catch 4xx HTTP errors - echo $e->getResponse()->toString(); - } + $user = $service->createUser(array( + 'username' => 'newUser', + 'email' => 'foo@bar.com' + )); + + // show generated password + echo $user->getPassword(); - // show generated password - echo $user->getPassword(); Update user ----------- @@ -118,27 +105,30 @@ Update user When updating a user, specify which attribute/property you want to update: -.. code:: php +.. code-block:: php + + $user->update(array( + 'email' => 'new_email@bar.com' + )); - $user->update(array( - 'email' => 'new_email@bar.com' - )); Updating a user password -~~~~~~~~~~~~~~~~~~~~~~~~ +------------------------ Updating a user password requires calling a distinct method: -.. code:: php +.. code-block:: php + + $user->updatePassword('password123'); - $user->updatePassword('password123'); Delete user ----------- -.. code:: php +.. code-block:: php + + $user->delete(); - $user->delete(); List credentials ---------------- @@ -146,16 +136,18 @@ List credentials This operation allows you to see your non-password credential types for all authentication methods available. -.. code:: php +.. code-block:: php + + $creds = $user->getOtherCredentials(); - $creds = $user->getOtherCredentials(); Get user API key ---------------- -.. code:: php +.. code-block:: php + + echo $user->getApiKey(); - echo $user->getApiKey(); Reset user API key ------------------ @@ -163,8 +155,7 @@ Reset user API key When resetting an API key, a new one will be automatically generated for you: -.. code:: php - - $user->resetApiKey(); - echo $user->getApiKey(); +.. code-block:: php + $user->resetApiKey(); + echo $user->getApiKey(); From 305bd1ea72415d202f4b7e63ca67f1a5b091db0a Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 4 Mar 2015 22:43:10 -0800 Subject: [PATCH 121/181] Adding unit tests + implementation for Neutron Security Groups and Security Group Rules. --- lib/OpenCloud/Networking/Service.php | 100 ++++++++++++++++++ .../Tests/Networking/NetworkingTestCase.php | 10 ++ .../Tests/Networking/ServiceTest.php | 46 ++++++++ 3 files changed, 156 insertions(+) diff --git a/lib/OpenCloud/Networking/Service.php b/lib/OpenCloud/Networking/Service.php index 3c1f879e2..12bb7477f 100644 --- a/lib/OpenCloud/Networking/Service.php +++ b/lib/OpenCloud/Networking/Service.php @@ -22,6 +22,8 @@ use OpenCloud\Networking\Resource\Network; use OpenCloud\Networking\Resource\Subnet; use OpenCloud\Networking\Resource\Port; +use OpenCloud\Networking\Resource\SecurityGroup; +use OpenCloud\Networking\Resource\SecurityGroupRule; /** * The Networking class represents the OpenNetwork Neutron service. @@ -290,6 +292,104 @@ public function listPorts(array $params = array()) return $this->resourceList('Port', $url); } + /** + * Returns a SecurityGroup object associated with this Networking service + * + * @param string $id ID of security group to retrieve + * @return \OpenCloud\Networking\Resource\SecurityGroup object + */ + public function securityGroup($id = null) + { + return $this->resource('SecurityGroup', $id); + } + + /** + * Creates a new SecurityGroup and returns it. + * + * @param array $params SecurityGroup creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-security-group + * @return \OpenCloud\Networking\Resource\SecurityGroup Object representing created security group + */ + public function createSecurityGroup(array $params = array()) + { + $securityGroup = $this->securityGroup(); + $securityGroup->create($params); + return $securityGroup; + } + + /** + * Returns a SecurityGroup object associated with this Networking service + * + * @param string $id ID of security group to retrieve + * @return \OpenCloud\Networking\Resource\SecurityGroup object + */ + public function getSecurityGroup($id) + { + return $this->securityGroup($id); + } + + /** + * Returns a list of security groups you created + * + * @param array $params + * @return \OpenCloud\Common\Collection\PaginatedIterator + */ + public function listSecurityGroups(array $params = array()) + { + $url = clone $this->getUrl(); + $url->addPath(SecurityGroup::resourceName())->setQuery($params); + + return $this->resourceList('SecurityGroup', $url); + } + + /** + * Returns a SecurityGroupRule object associated with this Networking service + * + * @param string $id ID of security group rule to retrieve + * @return \OpenCloud\Networking\Resource\SecurityGroupRule object + */ + public function securityGroupRule($id = null) + { + return $this->resource('SecurityGroupRule', $id); + } + + /** + * Creates a new SecurityGroupRule and returns it. + * + * @param array $params SecurityGroupRule creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-security-group-rule + * @return \OpenCloud\Networking\Resource\SecurityGroupRule Object representing created security group rule + */ + public function createSecurityGroupRule(array $params = array()) + { + $securityGroupRule = $this->securityGroupRule(); + $securityGroupRule->create($params); + return $securityGroupRule; + } + + /** + * Returns a SecurityGroupRule object associated with this Networking service + * + * @param string $id ID of security group rule to retrieve + * @return \OpenCloud\Networking\Resource\SecurityGroupRule object + */ + public function getSecurityGroupRule($id) + { + return $this->securityGroupRule($id); + } + + /** + * Returns a list of security group rules you created + * + * @param array $params + * @return \OpenCloud\Common\Collection\PaginatedIterator + */ + public function listSecurityGroupRules(array $params = array()) + { + $url = clone $this->getUrl(); + $url->addPath(SecurityGroupRule::resourceName())->setQuery($params); + + return $this->resourceList('SecurityGroupRule', $url); + } + /** * Return namespaces. * diff --git a/tests/OpenCloud/Tests/Networking/NetworkingTestCase.php b/tests/OpenCloud/Tests/Networking/NetworkingTestCase.php index be6b304c4..399094b6e 100644 --- a/tests/OpenCloud/Tests/Networking/NetworkingTestCase.php +++ b/tests/OpenCloud/Tests/Networking/NetworkingTestCase.php @@ -48,4 +48,14 @@ protected function assertIsPort($object) { $this->assertInstanceOf('OpenCloud\Networking\Resource\Port', $object); } + + protected function assertIsSecurityGroup($object) + { + $this->assertInstanceOf('OpenCloud\Networking\Resource\SecurityGroup', $object); + } + + protected function assertIsSecurityGroupRule($object) + { + $this->assertInstanceOf('OpenCloud\Networking\Resource\SecurityGroupRule', $object); + } } diff --git a/tests/OpenCloud/Tests/Networking/ServiceTest.php b/tests/OpenCloud/Tests/Networking/ServiceTest.php index 92b793e19..f2ab2cbfe 100644 --- a/tests/OpenCloud/Tests/Networking/ServiceTest.php +++ b/tests/OpenCloud/Tests/Networking/ServiceTest.php @@ -146,4 +146,50 @@ public function testGetPort() $this->assertIsPort($port); $this->assertEquals('port1', $port->getName()); } + + public function testCreateSecurityGroup() + { + $this->assertIsSecurityGroup($this->service->createSecurityGroup()); + } + + public function testListSecurityGroups() + { + $this->addMockSubscriber($this->makeResponse('{"security_groups":[{"description":"default","id":"85cc3048-abc3-43cc-89b3-377341426ac5","name":"default","security_group_rules":[{"direction":"egress","ethertype":"IPv6","id":"3c0e45ff-adaf-4124-b083-bf390e5482ff","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":null,"remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"egress","ethertype":"IPv4","id":"93aa42e5-80db-4581-9391-3a608bd0e448","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":null,"remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"ingress","ethertype":"IPv6","id":"c0b09f00-1d49-4e64-a0a7-8a186d928138","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"ingress","ethertype":"IPv4","id":"f7d45c89-008e-4bab-88ad-d6811724c51c","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"}],"tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"}]}')); + + $securityGroups = $this->service->listSecurityGroups(); + $this->isCollection($securityGroups); + $this->assertIsSecurityGroup($securityGroups->getElement(0)); + } + + public function testGetSecurityGroup() + { + $this->addMockSubscriber($this->makeResponse('{"security_group":{"description":"default","id":"85cc3048-abc3-43cc-89b3-377341426ac5","name":"default","security_group_rules":[{"direction":"egress","ethertype":"IPv6","id":"3c0e45ff-adaf-4124-b083-bf390e5482ff","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":null,"remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"egress","ethertype":"IPv4","id":"93aa42e5-80db-4581-9391-3a608bd0e448","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":null,"remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"ingress","ethertype":"IPv6","id":"c0b09f00-1d49-4e64-a0a7-8a186d928138","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"ingress","ethertype":"IPv4","id":"f7d45c89-008e-4bab-88ad-d6811724c51c","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"}],"tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"}}')); + + $securityGroup = $this->service->getSecurityGroup('85cc3048-abc3-43cc-89b3-377341426ac5'); + $this->assertIsSecurityGroup($securityGroup); + $this->assertEquals('default', $securityGroup->getName()); + } + + public function testCreateSecurityGroupRule() + { + $this->assertIsSecurityGroupRule($this->service->createSecurityGroupRule()); + } + + public function testListSecurityGroupRules() + { + $this->addMockSubscriber($this->makeResponse('{"security_group_rules":[{"direction":"egress","ethertype":"IPv6","id":"3c0e45ff-adaf-4124-b083-bf390e5482ff","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":null,"remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"egress","ethertype":"IPv4","id":"93aa42e5-80db-4581-9391-3a608bd0e448","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":null,"remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"ingress","ethertype":"IPv6","id":"c0b09f00-1d49-4e64-a0a7-8a186d928138","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"},{"direction":"ingress","ethertype":"IPv4","id":"f7d45c89-008e-4bab-88ad-d6811724c51c","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"}]}')); + + $securityGroupRules = $this->service->listSecurityGroupRules(); + $this->isCollection($securityGroupRules); + $this->assertIsSecurityGroupRule($securityGroupRules->getElement(0)); + } + + public function testGetSecurityGroupRule() + { + $this->addMockSubscriber($this->makeResponse('{"security_group_rule":{"direction":"egress","ethertype":"IPv6","id":"3c0e45ff-adaf-4124-b083-bf390e5482ff","port_range_max":null,"port_range_min":null,"protocol":null,"remote_group_id":null,"remote_ip_prefix":null,"security_group_id":"85cc3048-abc3-43cc-89b3-377341426ac5","tenant_id":"e4f50856753b4dc6afee5fa6b9b6c550"}}')); + + $securityGroupRule = $this->service->getSecurityGroupRule('3c0e45ff-adaf-4124-b083-bf390e5482ff'); + $this->assertIsSecurityGroupRule($securityGroupRule); + $this->assertEquals('egress', $securityGroupRule->getDirection()); + } } From 7b6a2f0df90b09b43769b281c34dea7c886c9e5f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 4 Mar 2015 23:09:09 -0800 Subject: [PATCH 122/181] Adding userguide documentation for security groups and security group rules. --- docs/userguide/Networking/USERGUIDE.md | 147 +++++++++++++++++++++++++ 1 file changed, 147 insertions(+) diff --git a/docs/userguide/Networking/USERGUIDE.md b/docs/userguide/Networking/USERGUIDE.md index 74e713b8a..bfa1a217c 100644 --- a/docs/userguide/Networking/USERGUIDE.md +++ b/docs/userguide/Networking/USERGUIDE.md @@ -33,6 +33,16 @@ these entities. * [Get a port](#get-a-port) * [Update a port](#update-a-port) * [Delete a port](#delete-a-port) + * [Security Groups](#security-groups) + * [Create a security group](#create-a-security-group) + * [List security groups](#list-security-groups) + * [Get a security group](#get-a-security-group) + * [Delete a security group](#delete-a-security-group) + * [Security group rule Rules](#security-group-rules) + * [Create a security group rule](#create-a-security-group-rule) + * [List security group rules](#list-security-group-rules) + * [Get a security group rule](#get-a-security-group-rule) + * [Delete a security group rule](#delete-a-security-group-rule) ## Concepts @@ -55,6 +65,10 @@ be assigned to the interfaces plugged into them. When IP addresses are associated with a port, this also implies the port is associated with a subnet because the IP address is taken from the allocation pool for a specific subnet. +* **Security Group**: TODO + +* **Security Group Rule**: TODO + ## Prerequisites ### Client @@ -468,3 +482,136 @@ $port->delete(); ``` [ [Get the executable PHP script for this example](/samples/Networking/delete-port.php) ] + +## Security Groups + +TODO: Add description + +### Create a security group + +This operation takes one parameter, an associative array, with the following keys: + +| Name | Description | Data type | Required? | Default value | Example value | +| ---- | ----------- | --------- | --------- | ------------- | ------------- | +| `name` | A human-readable name for the security group. This name might not be unique. | String | Yes | - | `new-webservers` | +| `description` | Description of the security group. | String | No | `null` | `security group for webservers` | + +You can create a security group as shown in the following example: + +```php +$securityGroup = $networkingService->createSecurityGroup(array( + 'name' => 'new-webservers', + 'description' => 'security group for webservers' +)); +/** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ +``` + +[ [Get the executable PHP script for this example](/samples/Networking/create-security-group.php) ] + +### List security groups + +You can list all the security groups to which you have access as shown in the following +example: + +```php +$securityGroups = $networkingService->listSecurityGroups(); +foreach ($securityGroups as $securityGroup) { + /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ +} +``` + +[ [Get the executable PHP script for this example](/samples/Networking/list-security-groups.php) ] + +### Get a security group + +You can retrieve a specific security group by using that security group's ID, as shown in the +following example: + +```php +$securityGroup = $networkingService->getSecurityGroup('2076db17-a522-4506-91de-c6dd8e837028'); +/** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ +``` + +[ [Get the executable PHP script for this example](/samples/Networking/get-security-group.php) ] + +### Delete a security group + +You can delete a security group as shown in the following example: + +```php +$securityGroup->delete(); +``` + +[ [Get the executable PHP script for this example](/samples/Networking/delete-security-group.php) ] + +## Security Group Rules + +TODO: Add description + +### Create a security group rule + +This operation takes one parameter, an associative array, with the following keys: + +| Name | Description | Data type | Required? | Default value | Example value | +| ---- | ----------- | --------- | --------- | ------------- | ------------- | +| `securityGroupId` | The security group ID to associate with this security group rule. | String | Yes | - | `2076db17-a522-4506-91de-c6dd8e837028` | +| `direction` | The direction in which the security group rule is applied. For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. | String (`ingress` or `egress`) | Yes | - | `ingress` | +| `ethertype` | Must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. | String (`IPv4` or `IPv6`) | No | `IPv4` | `IPv6` | +| `portRangeMin` | The minimum port number in the range that is matched by the security group rule. If the protocol is TCP or UDP, this value must be less than or equal to the value of the `portRangeMax` attribute. If the protocol is ICMP, this value must be an ICMP type. | Integer | No | `null` | `80` | +| `portRangeMax` | The maximum port number in the range that is matched by the security group rule. The port_range_min attribute constrains the attribute. If the protocol is ICMP, this value must be an ICMP type. | Integer | No | `null` | `80` | +| `protocol` | The protocol that is matched by the security group rule. | String (`tcp`, `udp`, `icmp`) | No | `null` | `tcp` | +| `remoteGroupId` | The remote group ID to be associated with this security group rule. You can specify either `remoteGroupId` or `remoteGroupPrefix`. | String | Optional | `null` | `85cc3048-abc3-43cc-89b3-377341426ac5` | +| `remoteIpPrefix` | The remote IP prefix to be associated with this security group rule. You can specify either `remoteGroupId` or `remoteGroupPrefix`. | String | Optional | `null` | `192.168.5.0` | + +You can create a security group rule as shown in the following example: + +```php +$securityGroupRule = $networkingService->createSecurityGroupRule(array( + 'securityGroupId' => '2076db17-a522-4506-91de-c6dd8e837028', + 'direction' => 'egress', + 'ethertype' => 'IPv4', + 'portRangeMin' => 80, + 'portRangeMax' => 80, + 'protocol' => 'tcp', + 'remoteGroupId' => '85cc3048-abc3-43cc-89b3-377341426ac5' +)); +/** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ +``` + +[ [Get the executable PHP script for this example](/samples/Networking/create-security-group-rule.php) ] + +### List security group rules + +You can list all the security group rules to which you have access as shown in the following +example: + +```php +$securityGroupRules = $networkingService->listSecurityGroupRules(); +foreach ($securityGroupRules as $securityGroupRule) { + /** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ +} +``` + +[ [Get the executable PHP script for this example](/samples/Networking/list-security-group-rules.php) ] + +### Get a security group rule + +You can retrieve a specific security group rule by using that security group rule's ID, as shown in the +following example: + +```php +$securityGroupRule = $networkingService->getSecurityGroupRule(''); +/** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ +``` + +[ [Get the executable PHP script for this example](/samples/Networking/get-security-group-rule.php) ] + +### Delete a security group rule + +You can delete a security group rule as shown in the following example: + +```php +$securityGroupRule->delete(); +``` + +[ [Get the executable PHP script for this example](/samples/Networking/delete-security-group-rule.php) ] From c5f8630cbe12309acd5058b745ba1a7b33d3df0d Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 4 Mar 2015 23:24:17 -0800 Subject: [PATCH 123/181] Adding downloadable code samples for Security Groups and Security Group Rules. --- .../Networking/create-security-group-rule.php | 42 +++++++++++++++++++ samples/Networking/create-security-group.php | 37 ++++++++++++++++ .../Networking/delete-security-group-rule.php | 36 ++++++++++++++++ samples/Networking/delete-security-group.php | 36 ++++++++++++++++ .../Networking/get-security-group-rule.php | 34 +++++++++++++++ samples/Networking/get-security-group.php | 34 +++++++++++++++ .../Networking/list-security-group-rules.php | 36 ++++++++++++++++ samples/Networking/list-security-groups.php | 36 ++++++++++++++++ 8 files changed, 291 insertions(+) create mode 100644 samples/Networking/create-security-group-rule.php create mode 100644 samples/Networking/create-security-group.php create mode 100644 samples/Networking/delete-security-group-rule.php create mode 100644 samples/Networking/delete-security-group.php create mode 100644 samples/Networking/get-security-group-rule.php create mode 100644 samples/Networking/get-security-group.php create mode 100644 samples/Networking/list-security-group-rules.php create mode 100644 samples/Networking/list-security-groups.php diff --git a/samples/Networking/create-security-group-rule.php b/samples/Networking/create-security-group-rule.php new file mode 100644 index 000000000..e60059774 --- /dev/null +++ b/samples/Networking/create-security-group-rule.php @@ -0,0 +1,42 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. Create a security group rule. +$securityGroupRule = $networkingService->createSecurityGroupRule(array( + 'securityGroupId' => '2076db17-a522-4506-91de-c6dd8e837028', + 'direction' => 'egress', + 'ethertype' => 'IPv4', + 'portRangeMin' => 80, + 'portRangeMax' => 80, + 'protocol' => 'tcp', + 'remoteGroupId' => '85cc3048-abc3-43cc-89b3-377341426ac5' +)); +/** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ diff --git a/samples/Networking/create-security-group.php b/samples/Networking/create-security-group.php new file mode 100644 index 000000000..bf69ad044 --- /dev/null +++ b/samples/Networking/create-security-group.php @@ -0,0 +1,37 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. Create a security group. +$securityGroup = $networkingService->createSecurityGroup(array( + 'name' => 'new-webservers', + 'description' => 'security group for webservers' +)); +/** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ diff --git a/samples/Networking/delete-security-group-rule.php b/samples/Networking/delete-security-group-rule.php new file mode 100644 index 000000000..d7cf988dd --- /dev/null +++ b/samples/Networking/delete-security-group-rule.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. Get security group rule. +$securityGroupRule = $networkingService->getSecurityGroupRule('{securityGroupRuleId}'); + +// 4. Delete security group rule. +$securityGroupRule->delete(); diff --git a/samples/Networking/delete-security-group.php b/samples/Networking/delete-security-group.php new file mode 100644 index 000000000..758da3ae8 --- /dev/null +++ b/samples/Networking/delete-security-group.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. Get security group. +$securityGroup = $networkingService->getSecurityGroup('{securityGroupId}'); + +// 4. Delete security group. +$securityGroup->delete(); diff --git a/samples/Networking/get-security-group-rule.php b/samples/Networking/get-security-group-rule.php new file mode 100644 index 000000000..f6ea2bc25 --- /dev/null +++ b/samples/Networking/get-security-group-rule.php @@ -0,0 +1,34 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. Get security group rule. +$securityGroupRule = $networkingService->getSecurityGroupRule('{securityGroupRuleId}'); +/** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ diff --git a/samples/Networking/get-security-group.php b/samples/Networking/get-security-group.php new file mode 100644 index 000000000..7573aa1f9 --- /dev/null +++ b/samples/Networking/get-security-group.php @@ -0,0 +1,34 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. Get security group. +$securityGroup = $networkingService->getSecurityGroup('{securityGroupId}'); +/** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ diff --git a/samples/Networking/list-security-group-rules.php b/samples/Networking/list-security-group-rules.php new file mode 100644 index 000000000..1adba50d7 --- /dev/null +++ b/samples/Networking/list-security-group-rules.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. List security group rules +$securityGroupRules = $networkingService->listSecurityGroupRules(); +foreach ($securityGroupRules as $securityGroupRule) { + /** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ +} diff --git a/samples/Networking/list-security-groups.php b/samples/Networking/list-security-groups.php new file mode 100644 index 000000000..82ffd0931 --- /dev/null +++ b/samples/Networking/list-security-groups.php @@ -0,0 +1,36 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain a Networking service object from the client. +$networkingService = $client->networkingService(null, '{region}'); + +// 3. List security groups +$securityGroups = $networkingService->listSecurityGroups(); +foreach ($securityGroups as $securityGroup) { + /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ +} From 271f8dbe11a418157aa5c82ed89e4c99d52454c8 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 4 Mar 2015 23:40:40 -0800 Subject: [PATCH 124/181] Adding smoke tests for Security Groups and Security Group Rules. --- tests/OpenCloud/Smoke/Unit/Networking.php | 80 ++++++++++++++++++++++- 1 file changed, 77 insertions(+), 3 deletions(-) diff --git a/tests/OpenCloud/Smoke/Unit/Networking.php b/tests/OpenCloud/Smoke/Unit/Networking.php index 74f39fac7..b6ab4592e 100644 --- a/tests/OpenCloud/Smoke/Unit/Networking.php +++ b/tests/OpenCloud/Smoke/Unit/Networking.php @@ -26,9 +26,11 @@ */ class Networking extends AbstractUnit implements UnitInterface { - protected $cleanupNetworkIds = array(); - protected $cleanupSubnetIds = array(); - protected $cleanupPortIds = array(); + protected $cleanupNetworkIds = array(); + protected $cleanupSubnetIds = array(); + protected $cleanupPortIds = array(); + protected $cleanupSecurityGroupIds = array(); + protected $cleanupSecurityGroupRuleIds = array(); public function setupService() { @@ -40,6 +42,8 @@ public function main() $this->testNetworkOperations(); $this->testSubnetOperations(); $this->testPortOperations(); + $this->testSecurityGroupOperations(); + $this->testSecurityGroupRuleOperations(); } protected function testNetworkOperations() @@ -251,8 +255,78 @@ protected function testPortOperations() )); } + protected function testSecurityGroupOperations() + { + $this->step('Create security group'); + $security group = $this->getService()->createSecurityGroup(array( + 'name' => 'new-webservers', + 'description' => 'security group for webservers' + )); + $this->stepInfo('Security Group ID: ' . $securityGroup->getId()); + $this->stepInfo('Security Group Name: ' . $securityGroup->getName()); + $this->cleanupSecurityGroupIds[] = $securityGroup->getId(); + + $this->step('List security groups'); + $securityGroups = $this->getService()->listSecurityGroups(); + $this->stepInfo('%-40s | %s', 'Security Group ID', 'Security Group name'); + $this->stepInfo('%-40s | %s', str_repeat('-', 40), str_repeat('-', 40)); + foreach ($securityGroups as $securityGroup) { + $this->stepInfo('%-40s | %s', $securityGroup->getId(), $securityGroup->getName()); + } + + $this->step('Get security group'); + $security group = $this->getService()->getSecurityGroup($securityGroup->getId()); + $this->stepInfo('Security Group ID: ' . $securityGroup->getId()); + $this->stepInfo('Security Group Name: ' . $securityGroup->getName()); + } + + protected function testSecurityGroupRuleOperations() + { + $securityGroup1 = $this->getService()->createSecurityGroup(array( + 'name' => 'test_security_group_for_test_security_group_rule' + )); + $this->cleanupSecurityGroupIds[] = $securityGroup1->getId(); + + $this->step('Create security group rule'); + $security group rule = $this->getService()->createSecurityGroupRule(array( + 'securityGroupId' => $securityGroup1->getId(), + 'direction' => 'egress', + 'ethertype' => 'IPv4', + 'portRangeMin' => 80, + 'portRangeMax' => 80, + 'protocol' => 'tcp', + 'remoteGroupId' => '85cc3048-abc3-43cc-89b3-377341426ac5' + )); + $this->stepInfo('Security Group Rule ID: ' . $securityGroupRule->getId()); + $this->stepInfo('Security Group Rule Direction: ' . $securityGroupRule->getDirection()); + $this->cleanupSecurityGroupRuleIds[] = $securityGroupRule->getId(); + + $this->step('List security group rules'); + $securityGroupRules = $this->getService()->listSecurityGroupRules(); + $this->stepInfo('%-40s | %s', 'Security Group Rule ID', 'Security Group Rule name'); + $this->stepInfo('%-40s | %s', str_repeat('-', 40), str_repeat('-', 40)); + foreach ($securityGroupRules as $securityGroupRule) { + $this->stepInfo('%-40s | %s', $securityGroupRule->getId(), $securityGroupRule->getName()); + } + + $this->step('Get security group rule'); + $security group rule = $this->getService()->getSecurityGroupRule($securityGroupRule->getId()); + $this->stepInfo('Security Group Rule ID: ' . $securityGroupRule->getId()); + $this->stepInfo('Security Group Rule Name: ' . $securityGroupRule->getName()); + } + public function teardown() { + foreach ($this->cleanupSecurityGroupRuleIds as $securityGroupRuleId) { + $securityGroupRule = $this->getService()->getSecurityGroupRule($securityGroupRuleId); + $securityGroupRule->delete(); + } + + foreach ($this->cleanupSecurityGroupIds as $securityGroupId) { + $securityGroup = $this->getService()->getSecurityGroup($securityGroupId); + $securityGroup->delete(); + } + foreach ($this->cleanupPortIds as $portId) { $port = $this->getService()->getPort($portId); $port->delete(); From 0b0b54eca816b729a68d6f7988936acd44dbd449 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 4 Mar 2015 23:41:48 -0800 Subject: [PATCH 125/181] Forgot to check-in resource classes. --- .../Networking/Resource/SecurityGroup.php | 67 +++++++++++++++ .../Networking/Resource/SecurityGroupRule.php | 82 +++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 lib/OpenCloud/Networking/Resource/SecurityGroup.php create mode 100644 lib/OpenCloud/Networking/Resource/SecurityGroupRule.php diff --git a/lib/OpenCloud/Networking/Resource/SecurityGroup.php b/lib/OpenCloud/Networking/Resource/SecurityGroup.php new file mode 100644 index 000000000..105fc22a1 --- /dev/null +++ b/lib/OpenCloud/Networking/Resource/SecurityGroup.php @@ -0,0 +1,67 @@ + 'securityGroupRules', + 'tenant_id' => 'tenantId' + ); + + protected $createKeys = array( + 'name', + 'description' + ); + + /** + * This method is inherited. The inherited method has protected scope + * but we are widening the scope to public so this method may be called + * from other classes such as {@see OpenCloud\Networking\Service}. + */ + public function createJson() + { + return parent::createJson(); + } + + /** + * {@inheritDoc} + */ + public function update($params = array()) + { + return $this->noUpdate(); + } +} diff --git a/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php b/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php new file mode 100644 index 000000000..3659d08ac --- /dev/null +++ b/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php @@ -0,0 +1,82 @@ + 'portRangeMin', + 'port_range_max' => 'portRangeMax', + 'remote_group_id' => 'remoteGroupId', + 'remote_ip_prefix' => 'remoteIpPrefix', + 'security_group_id' => 'securityGroupId', + 'tenant_id' => 'tenantId' + ); + + protected $createKeys = array( + 'direction', + 'ethertype', + 'securityGroupId', + 'portRangeMin', + 'portRangeMax', + 'protocol', + 'remoteGroupId', + 'remoteIpPrefix' + ); + + /** + * This method is inherited. The inherited method has protected scope + * but we are widening the scope to public so this method may be called + * from other classes such as {@see OpenCloud\Networking\Service}. + */ + public function createJson() + { + return parent::createJson(); + } + + /** + * {@inheritDoc} + */ + public function update($params = array()) + { + return $this->noUpdate(); + } +} From 309c01d51998ba26d550c98e8caeeac9bbbd1215 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 15:29:11 +0100 Subject: [PATCH 126/181] Add docs for Images --- doc/services/image/Images.md.rst | 107 ------------------ doc/services/image/Tags.md.rst | 28 ----- doc/services/image/images.rst | 84 ++++++++++++++ doc/services/image/index.rst | 41 +++++++ .../image/{Schemas.md.rst => schemas.rst} | 29 ++--- .../image/{Sharing.md.rst => sharing.rst} | 50 ++++---- doc/services/image/tags.rst | 29 +++++ 7 files changed, 189 insertions(+), 179 deletions(-) delete mode 100644 doc/services/image/Images.md.rst delete mode 100644 doc/services/image/Tags.md.rst create mode 100644 doc/services/image/images.rst rename doc/services/image/{Schemas.md.rst => schemas.rst} (87%) rename doc/services/image/{Sharing.md.rst => sharing.rst} (75%) create mode 100644 doc/services/image/tags.rst diff --git a/doc/services/image/Images.md.rst b/doc/services/image/Images.md.rst deleted file mode 100644 index ef187f083..000000000 --- a/doc/services/image/Images.md.rst +++ /dev/null @@ -1,107 +0,0 @@ -Images -====== - -A virtual machine image is a single file which contains a virtual disk -that has an installed bootable operating system. In the Cloud Images -API, an image is represented by a JSON-encoded data structure (the image -schema) and its raw binary data (the image file). - -An Image is represented by the ``OpenCloud\Image\Resource\Image`` class. - -Setup ------ - -You instantiate an Image object from its ``OpenCloud\Image\Service`` -class, which is available from the OpenStack/Rackspace client: - -.. code:: php - - $service = $client->imageService('cloudImages', 'IAD'); - -View the guides for more information about `clients <../Clients.md>`__ -or `services <../Services.md>`__. - -List images ------------ - -.. code:: php - - $images = $service->listImages(); - - foreach ($images as $image) { - /** @param $image OpenCloud\Image\Resource\Image */ - } - -For more information about working with iterators, please see the -`iterators documentation <../Iterators.md>`__. - -Get image details ------------------ - -.. code:: php - - /** @param $image OpenCloud\Image\Resource\Image */ - $image = $service->getImage(''); - -A note on schema classes -~~~~~~~~~~~~~~~~~~~~~~~~ - -Both ``OpenCloud\Image\Resource\Image`` and -``OpenCloud\Image\Resource\Member`` extend the -``AbstractSchemaResource`` abstract class, which offers some unique -functionality. - -Because these resources are inherently dynamic - i.e. they are modelled -on dynamic JSON schema - you need to access their state in a way -different than conventional getter/setter methods, and even class -properties. For this reason, they implement SPL's native -```ArrayAccess`` `__ -interface which allows you to access their state as a conventional -array: - -.. code:: php - - $image = $service->getImage(''); - - $id = $image['id']; - $tags = $image['tags']; - -Update image ------------- - -You can only update your own custom images - you cannot update or delete -base images. The way in which you may update your image is dictated by -its `schema `__. - -Although you should be able to add new and replace existing properties, -always prepare yourself for a situation where it might be forbidden: - -.. code:: php - - use OpenCloud\Common\Exceptions\ForbiddenOperationException; - - try { - $image->update(array( - 'name' => 'foo', - 'newProperty' => 'bar' - )); - } catch (ForbiddenOperationException $e) { - // A 403 Forbidden was returned - } - -There are three operations that can take place for each Image property: - -- If a ``false`` or ``null`` value is provided, a ``REMOVE`` operation - will occur, removing the property from the JSON document -- If a non-false value is provided and the property does not exist, an - ``ADD`` operation will add it to the document -- If a non-false value is provided and the property does exist, a - ``REPLACE`` operation will modify the property in the document - -Delete image ------------- - -.. code:: php - - $image->delete(); - diff --git a/doc/services/image/Tags.md.rst b/doc/services/image/Tags.md.rst deleted file mode 100644 index af5baf157..000000000 --- a/doc/services/image/Tags.md.rst +++ /dev/null @@ -1,28 +0,0 @@ -Image tags -========== - -An image tag is a string of characters used to identify a specific image -or images. - -Setup ------ - -All member operations are executed against an `Image `__, so -you will need to set this up first. - -Add image tag -------------- - -.. code:: php - - /** @param $response Guzzle\Http\Message\Response */ - $response = $image->addTag('jamie_dev'); - -Delete image tag ----------------- - -.. code:: php - - /** @param $response Guzzle\Http\Message\Response */ - $response = $image->deleteTag('jamie_dev'); - diff --git a/doc/services/image/images.rst b/doc/services/image/images.rst new file mode 100644 index 000000000..ec1a17c34 --- /dev/null +++ b/doc/services/image/images.rst @@ -0,0 +1,84 @@ +Images +====== + +List images +----------- + +.. code-block:: php + + $images = $service->listImages(); + + foreach ($images as $image) { + /** @param $image OpenCloud\Image\Resource\Image */ + } + + +Get image details +----------------- + +.. code-block:: php + + /** @param $image OpenCloud\Image\Resource\Image */ + $image = $service->getImage('{imageId}'); + + +A note on schema classes +~~~~~~~~~~~~~~~~~~~~~~~~ + +Both ``OpenCloud\Image\Resource\Image`` and ``OpenCloud\Image\Resource\Member`` +extend the ``AbstractSchemaResource`` class, which offers some unique functionality. + +Because these resources are inherently dynamic - i.e. they are modelled +on dynamic JSON schema - you need to access their state in a different way +than conventional getter/setter methods, and even class properties. For this +reason, they implement SPL's native +`ArrayAccess `_ +interface which allows you to access their state as a conventional +array: + +.. code-block:: php + + $image = $service->getImage('{imageId}'); + + $id = $image['id']; + $tags = $image['tags']; + + +Update image +------------ + +You can only update your own custom images - you cannot update or delete +base images. The way in which you may update your image is dictated by +its `schema `__. + +Although you should be able to add new and replace existing properties, +always prepare yourself for a situation where it might be forbidden: + +.. code-block:: php + + use OpenCloud\Common\Exceptions\ForbiddenOperationException; + + try { + $image->update(array( + 'name' => 'foo', + 'newProperty' => 'bar' + )); + } catch (ForbiddenOperationException $e) { + // A 403 Forbidden was returned + } + +There are three operations that can take place for each Image property: + +* If a ``false`` or ``null`` value is provided, a ``REMOVE`` operation + will occur, removing the property from the JSON document +* If a non-false value is provided and the property does not exist, an + ``ADD`` operation will add it to the document +* If a non-false value is provided and the property does exist, a + ``REPLACE`` operation will modify the property in the document + +Delete image +------------ + +.. code-block:: php + + $image->delete(); diff --git a/doc/services/image/index.rst b/doc/services/image/index.rst index e69de29bb..d54b09ad0 100644 --- a/doc/services/image/index.rst +++ b/doc/services/image/index.rst @@ -0,0 +1,41 @@ +Images v1 +========= + +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +.. code-block:: php + + $service = $client->imageService(null, '{region}'); + + +Operations +---------- + +.. toctree:: + + images + schemas + sharing + tags + + +Glossary +-------- + + image + A virtual machine image is a single file which contains a virtual disk + that has an installed bootable operating system. In the Cloud Images + API, an image is represented by a JSON-encoded data structure (the image + schema) and its raw binary data (the image file). + + schema + The Cloud Images API supplies JSON documents describing the JSON-encoded + data structures that represent domain objects, so that a client knows + exactly what to expect in an API response. + + tag + An image tag is a string of characters used to identify a specific image + or images. diff --git a/doc/services/image/Schemas.md.rst b/doc/services/image/schemas.rst similarity index 87% rename from doc/services/image/Schemas.md.rst rename to doc/services/image/schemas.rst index 8f792c4c0..c1b85b8de 100644 --- a/doc/services/image/Schemas.md.rst +++ b/doc/services/image/schemas.rst @@ -1,13 +1,6 @@ JSON schemas ============ -The Cloud Images API supplies json documents describing the JSON-encoded -data structures that represent domain objects, so that a client knows -exactly what to expect in an API response. - -A JSON Schema is represented by the -``OpenCloud\Image\Resource\Schema\Schema`` class. - Schema types ------------ @@ -19,7 +12,7 @@ Example response from the API A sample response from the API, for an Images schema might be: -.. code:: json +.. code-block:: json { "name": "images", @@ -70,7 +63,7 @@ links and a properties object. Inside this properties object we see the structure of this top-level ``images`` object. So we know that it will take this form: -.. code:: json +.. code-block:: json { "images": [something...] @@ -80,7 +73,7 @@ Within this object, we can see that it contains an array of anonymous objects, each of which is called ``image`` and has its own set of nested properties: -.. code:: json +.. code-block:: json { "images": [ @@ -101,7 +94,7 @@ i.e. a *subschema*. We know that each object has an ID property (string), a name property (string), a visibility property (can either be ``private`` or ``public``), etc. -.. code:: json +.. code-block:: json { "images": [ @@ -147,21 +140,21 @@ Requests need to use the In order for the operation to occur, the request entity body needs to contain a very particular structure: -:: +.. code-block:: json [ {"op": "replace", "path": "/name", "value": "Fedora 17"}, {"op": "replace", "path": "/tags", "value": ["fedora", "beefy"]} ] -The ``op`` key refers to the type of Operation (see -``OpenCloud\Image\Enum\OperationType`` for a full list). +* The ``op`` key refers to the type of Operation (see + ``OpenCloud\Image\Enum\OperationType`` for a full list). -The ``path`` key is a JSON pointer to the document property you want to -modify or insert. JSON pointers are defined in `RFC -6901 `__. +* The ``path`` key is a JSON pointer to the document property you want to + modify or insert. JSON pointers are defined in `RFC + 6901 `__. -The ``value`` key is the value. +* The ``value`` key is the value. Because this is all handled for you behind the scenes, we will not go into exhaustive depth about how this operation is handled. You can diff --git a/doc/services/image/Sharing.md.rst b/doc/services/image/sharing.rst similarity index 75% rename from doc/services/image/Sharing.md.rst rename to doc/services/image/sharing.rst index b1a1ea382..5edf63ab4 100644 --- a/doc/services/image/Sharing.md.rst +++ b/doc/services/image/sharing.rst @@ -63,66 +63,64 @@ Additional notes Setup ----- -All member operations are executed against an `Image `__, so -you will need to set this up first. +All member operations are executed against an `Image `__, so you will +need to set one up first: + +.. code-block:: php + + $image = $service->getImage('{imageId}'); + List image members ------------------ This operation is available for both producers and consumers. -.. code:: php +.. code-block:: php - $members = $image->listMembers(); + $members = $image->listMembers(); - foreach ($members as $member) { - /** @param $member OpenCloud\Image\Resource\Member */ - } + foreach ($members as $member) { + /** @param $member OpenCloud\Image\Resource\Member */ + } -For more information about working with iterators, please see the -`iterators documentation <../Iterators.md>`__. Create image member ------------------- This operation is only available for producers. -.. code:: php +.. code-block:: php - $tenantId = 12345; + /** @param $response Guzzle\Http\Message\Response */ + $response = $image->createMember('{tenantId}'); - /** @param $response Guzzle\Http\Message\Response */ - $response = $image->createMember($tenantId); Delete image member ------------------- This operation is only available for producers. -.. code:: php +.. code-block:: php - $tenantId = 12345; + /** @param $member OpenCloud\Image\Resource\Member */ + $member = $image->getMember('{tenantId}'); + $member->delete(); - /** @param $member OpenCloud\Image\Resource\Member */ - $member = $image->getMember($tenantId); - - $member->delete(); Update image member status -------------------------- This operation is only available for consumers. -.. code:: php - - use OpenCloud\Images\Enum\MemberStatus; +.. code-block:: php - $tenantId = 12345; + use OpenCloud\Images\Enum\MemberStatus; - /** @param $member OpenCloud\Image\Resource\Member */ - $member = $image->getMember($tenantId); + /** @param $member OpenCloud\Image\Resource\Member */ + $member = $image->getMember('{tenantId}'); - $member->updateStatus(MemberStatus::ACCEPTED); + $member->updateStatus(MemberStatus::ACCEPTED); The acceptable states you may pass in are made available to you through the constants defined in the ``OpenCloud\Images\Enum\MemberStatus`` diff --git a/doc/services/image/tags.rst b/doc/services/image/tags.rst new file mode 100644 index 000000000..0a376e6de --- /dev/null +++ b/doc/services/image/tags.rst @@ -0,0 +1,29 @@ +Image tags +========== + +Setup +----- + +All member operations are executed against an `Image `__, so you will +need to set one up first: + +.. code-block:: php + + $image = $service->getImage('{imageId}'); + + +Add image tag +------------- + +.. code-block:: php + + /** @param $response Guzzle\Http\Message\Response */ + $response = $image->addTag('jamie_dev'); + +Delete image tag +---------------- + +.. code-block:: php + + /** @param $response Guzzle\Http\Message\Response */ + $response = $image->deleteTag('jamie_dev'); From fa7820646d98c9385039b458d6443cf9ad465e5b Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 15:29:21 +0100 Subject: [PATCH 127/181] Add LB docs --- doc/services/load-balancer/README.md.rst | 92 -- doc/services/load-balancer/USERGUIDE.md.rst | 840 ------------------ doc/services/load-balancer/access.rst | 79 ++ doc/services/load-balancer/caching.rst | 35 + doc/services/load-balancer/errors.rst | 44 + doc/services/load-balancer/index.rst | 93 ++ .../load-balancer/lb-setup.sample.rst | 9 + doc/services/load-balancer/load-balancer.rst | 165 ++++ doc/services/load-balancer/logging.rst | 33 + doc/services/load-balancer/metadata.rst | 46 + doc/services/load-balancer/monitors.rst | 43 + doc/services/load-balancer/nodes.rst | 124 +++ doc/services/load-balancer/sessions.rst | 53 ++ doc/services/load-balancer/ssl.rst | 52 ++ doc/services/load-balancer/stats.rst | 59 ++ doc/services/load-balancer/virtual-ips.rst | 74 ++ 16 files changed, 909 insertions(+), 932 deletions(-) delete mode 100644 doc/services/load-balancer/README.md.rst delete mode 100644 doc/services/load-balancer/USERGUIDE.md.rst create mode 100644 doc/services/load-balancer/access.rst create mode 100644 doc/services/load-balancer/caching.rst create mode 100644 doc/services/load-balancer/errors.rst create mode 100644 doc/services/load-balancer/lb-setup.sample.rst create mode 100644 doc/services/load-balancer/load-balancer.rst create mode 100644 doc/services/load-balancer/logging.rst create mode 100644 doc/services/load-balancer/metadata.rst create mode 100644 doc/services/load-balancer/monitors.rst create mode 100644 doc/services/load-balancer/nodes.rst create mode 100644 doc/services/load-balancer/sessions.rst create mode 100644 doc/services/load-balancer/ssl.rst create mode 100644 doc/services/load-balancer/stats.rst create mode 100644 doc/services/load-balancer/virtual-ips.rst diff --git a/doc/services/load-balancer/README.md.rst b/doc/services/load-balancer/README.md.rst deleted file mode 100644 index 862cf20d2..000000000 --- a/doc/services/load-balancer/README.md.rst +++ /dev/null @@ -1,92 +0,0 @@ -Load Balancers -============== - -A **load balancer** is a device that distributes incoming network -traffic amongst multiple back-end systems. These back-end systems are -called the **nodes** of the load balancer. - -Getting started ---------------- - -1. Instantiate a Rackspace client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -2. Retrieve the server instances you want to add as nodes of the load balancer. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $computeService = $client->computeService('cloudServersOpenStack', 'DFW'); - - $serverOne = $computeService->server('e836fc4e-056d-4447-a80e-fefcaa640216'); - $serverTwo = $computeService->server('5399cd36-a23f-41a6-bdf7-20902aec0e74'); - -The example above uses two server instances that have already been -created. It retrieves the server instances using their IDs. See also: -`creating server instances <>`__. - -3. Obtain a Load Balancer service object from the client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This object will be used to first define the load balancer nodes and -later create the load balancer itself. - -.. code:: php - - $loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); - -4. Define a load balancer node for each server. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $loadBalancer = $loadBalancerService->loadBalancer(); - - $serverOneNode = $loadBalancer->node(); - $serverOneNode->address = $serverOne->addresses->private[0]->addr; - $serverOneNode->port = 8080; - $serverOneNode->condition = 'ENABLED'; - - $serverTwoNode = $loadBalancer->node(); - $serverTwoNode->address = $serverTwo->addresses->private[0]->addr; - $serverTwoNode->port = 8080; - $serverTwoNode->condition = 'ENABLED'; - -In the example above, each node runs a service that listens on port -8080. Further, each node will start out as ``ENABLED``, which means it -will be ready to receive network traffic from the load balancer as soon -as it is created. - -5. Create the load balancer with the two nodes. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $loadBalancer->addVirtualIp('PUBLIC'); - $loadBalancer->create(array( - 'name' => 'My smart load balancer', - 'port' => 80, - 'protocol' => 'HTTP', - 'nodes' => array($serverOneNode, $serverTwoNode) - )); - -In the example above, the load balancer will have a virtual IP address -accessible from the public Internet. Also notice that the port the load -balancer listens on (80) does not need to match the ports of its nodes -(8080). - -Next steps ----------- - -Once you have created a load balancer, there is a lot you can do with -it. See the `complete user guide for load balancers `__. diff --git a/doc/services/load-balancer/USERGUIDE.md.rst b/doc/services/load-balancer/USERGUIDE.md.rst deleted file mode 100644 index 788651f2b..000000000 --- a/doc/services/load-balancer/USERGUIDE.md.rst +++ /dev/null @@ -1,840 +0,0 @@ -The Complete User Guide to Load Balancers -========================================= - -Prerequisites -------------- - -Client -~~~~~~ - -To use the load balancers service, you must first instantiate a -``Rackspace`` client object. - -.. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -Load Balancer Service -~~~~~~~~~~~~~~~~~~~~~ - -All operations on load balancers are done via a load balancer service -object. - -.. code:: php - - $loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); - -Cloud Servers -~~~~~~~~~~~~~ - -Many of the examples in this document use two cloud servers as nodes for -the load balancer. The variables ``$serverOne`` and ``$serverTwo`` refer -to these two cloud servers. - -Load Balancers --------------- - -A **load balancer** is a device that distributes incoming network -traffic amongst multiple back-end systems. These back-end systems are -called the **nodes** of the load balancer. - -Create Load Balancer -~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $loadBalancer = $loadBalancerService->loadBalancer(); - - $serverOneNode = $loadBalancer->node(); - $serverOneNode->address = $serverOne->addresses->private[0]->addr; - $serverOneNode->port = 8080; - $serverOneNode->condition = 'ENABLED'; - - $serverTwoNode = $loadBalancer->node(); - $serverTwoNode->address = $serverTwo->addresses->private[0]->addr; - $serverTwoNode->port = 8080; - $serverTwoNode->condition = 'ENABLED'; - - $loadBalancer->addVirtualIp('PUBLIC'); - $loadBalancer->create(array( - 'name' => 'My smart load balancer', - 'port' => 80, - 'protocol' => 'HTTP', - 'nodes' => array($serverOneNode, $serverTwoNode) - )); - -List Load Balancer Details -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can retrieve a single load balancer's details by using its ID. - -.. code:: php - - $loadBalancer = $loadBalancerService->loadBalancer('254889'); - - /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ - -List Load Balancers -~~~~~~~~~~~~~~~~~~~ - -You can retrieve a list of all your load balancers. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $loadBalancers = $loadBalancerService->loadBalancerList(); - foreach ($loadBalancers as $loadBalancer) { - /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ - } - -Update Load Balancer Attributes -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can update one or more of the following load balancer attributes: - -- ``name``: The name of the load balancer -- ``algorithm``: The algorithm used by the load balancer to distribute - traffic amongst its nodes. See also: `Load balancing - algorithms <#algorithms>`__. -- ``protocol``: The network protocol used by traffic coming in to the - load balancer. See also: `Protocols <#protocols>`__. -- ``port``: The network port on which the load balancer listens for - incoming traffic. -- ``halfClosed``: Enable or Disable Half-Closed support for the load - balancer. -- ``timeout``: The timeout value for the load balancer to communicate - with its nodes. -- ``httpsRedirect``: Enable or disable HTTP to HTTPS redirection for - the load balancer. When enabled, any HTTP request will return status - code 301 (Moved Permanently), and the requestor will be redirected to - the requested URL via the HTTPS protocol on port 443. For example, - http://example.com/page.html would be redirected to https:// - example.com/page.html. Only available for HTTPS protocol (``port`` = - 443), or HTTP Protocol with a properly configured SSL Termination - (\`secureTrafficOnly=true, securePort=443). See also: `SSL - Termination <#ssl-termination>`__. - -Updating a single attribute of a load balancer -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code:: php - - $loadBalancer->update(array( - 'name' => 'New name' - )); - -Updating multiple attributes of a load balancer -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code:: php - - $loadBalancer->update(array( - 'name' => 'New name', - 'algorithm' => 'ROUND_ROBIN' - )); - -Remove Load Balancer -~~~~~~~~~~~~~~~~~~~~ - -When you no longer have a need for the load balancer, you can remove it. - -.. code:: php - - $loadBalancer->delete(); - -Nodes ------ - -A **node** is a backend device that provides a service on specified IP -and port. An example of a load balancer node might be a web server -serving HTTP traffic on port 8080. - -A load balancer typically has multiple nodes attached to it so it can -distribute incoming network traffic amongst them. - -List Nodes -~~~~~~~~~~ - -You can list the nodes attached to a load balancer. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $nodes = $loadBalancer->nodeList(); - foreach ($nodes as $node) { - /** @var $node OpenCloud\LoadBalancer\Resource\Node **/ - } - -Add Nodes -~~~~~~~~~ - -You can attach additional nodes to a load balancer. Assume -``$loadBalancer`` already has two nodes attached to it - ``$serverOne`` -and ``$serverTwo`` - and you want to attach a third node to it, say -``$serverThree``, which provides a service on port 8080. - -**Important:** Remember to call ``$loadBalancer->addNodes()`` after all -the calls to ``$loadBalancer->addNode()`` as shown below. - -.. code:: php - - $address = $serverThree->addresses->private[0]->addr; - $loadBalancer->addNode($address, 8080); - $loadBalancer->addNodes(); - -The ``addNode`` method accepts three more optional parameters, in -addition to the two shown above: - -| Position \| Description \| Data type \| Required? \| Default value \| -| ----------- \| --------------- \| --------------\| -------------- \| ------------------ \| -|  1 \| IP address of node \| String \| Yes \| - \| -|  2 \| Port used by node's service \| Integer \| Yes \| - \| -|  3 \| Starting condition of node: -|  4 \| Type of node to add: -|  5 \| Weight, between 1 and 100, given to node when distributing -traffic using either the ``WEIGHTED_ROUND_ROBIN`` or the -``WEIGHTED_LEAST_CONNECTIONS`` load balancing algorithm. \| Integer \| -No \| 1 \| - -Modify Nodes -~~~~~~~~~~~~ - -You can modify one or more of the following node attributes: - -- ``condition``: The condition of the load balancer: - - - ``ENABLED`` – Node is ready to receive traffic from the load - balancer. - - ``DISABLED`` – Node should not receive traffic from the load - balancer. - - ``DRAINING`` – Node should process any traffic it is already - receiving but should not receive any further traffic from the load - balancer. - -- ``type``: The type of the node: - - - ``PRIMARY`` – Nodes defined as PRIMARY are in the normal rotation - to receive traffic from the load balancer. - - ``SECONDARY`` – Nodes defined as SECONDARY are only in the - rotation to receive traffic from the load balancer when all the - primary nodes fail. - -- ``weight``: The weight, between 1 and 100, given to node when - distributing traffic using either the ``WEIGHTED_ROUND_ROBIN`` or the - ``WEIGHTED_LEAST_CONNECTIONS`` load balancing algorithm. - -Modifying a single attribute of a node -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code:: php - - use OpenCloud\LoadBalancer\Enum\NodeCondition; - - $node->update(array( - 'condition' => NodeCondition::DISABLED - )); - -Modifying multiple attributes of a node -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code:: php - - use OpenCloud\LoadBalancer\Enum\NodeCondition; - use OpenCloud\LoadBalancer\Enum\NodeType; - - $node->update(array( - 'condition' => NodeCondition::DISABLED, - 'type' => NodeType::SECONDARY - )); - -Remove Nodes -~~~~~~~~~~~~ - -There are two ways to remove a node. - -Given an ``OpenCloud\LoadBalancer\Resource\Node`` instance -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code:: php - - $node->delete(); - -Given an ``OpenCloud\LoadBalancer\Resource\LoadBalancer`` instance and a node ID -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -.. code:: php - - $loadBalancer->removeNode(490639); - -The ``removeNode`` method, as shown above, accepts the following -arguments: - -+------------+---------------+-------------+-------------+-----------------+ -| Position | Description | Data type | Required? | Default value | -+============+===============+=============+=============+=================+ -| 1 | ID of node | Integer | Yes | - | -+------------+---------------+-------------+-------------+-----------------+ - -View Node Service Events -~~~~~~~~~~~~~~~~~~~~~~~~ - -You can view events associated with the activity between a node and a -load balancer. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $nodeEvents = $loadBalancer->nodeEventList(); - foreach ($nodeEvents as $nodeEvent) { - /** @var $nodeEvent OpenCloud\LoadBalancer\Resource\NodeEvent **/ - } - -Virtual IPs ------------ - -A **virtual IP (VIP)** makes a load balancer accessible by clients. The -load balancing service supports either a public VIP address -(``PUBLIC``), routable on the public Internet, or a ServiceNet VIP -address (``SERVICENET``), routable only within the region in which the -load balancer resides. - -List Virtual IPs -~~~~~~~~~~~~~~~~ - -You can list the VIPs associated with a load balancer. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $vips = $loadBalancer->virtualIpList(); - foreach ($vips as $vip) { - /** @var $vip of OpenCloud\LoadBalancer\Resource\VirtualIp **/ - } - -Add Virtual IPv6 -~~~~~~~~~~~~~~~~ - -You can add additional IPv6 VIPs to a load balancer. - -.. code:: php - - use OpenCloud\LoadBalancer\Enum\IpType; - - $loadBalancer->addVirtualIp(IpType::PUBLIC, 6); - -The ``addVirtualIp`` method, as shown above, accepts the following -arguments: - -| Position \| Description \| Data type \| Required? \| Default value \| -| ----------- \| --------------- \| -------------- \|-------------- \| ------------------ \| -|  1 \| Type of VIP: -|  2 \| IP version: Must be ``6`` \| Integer \| Yes \| - \| - -Remove Virtual IPs -~~~~~~~~~~~~~~~~~~ - -You can remove a VIP from a load balancer. - -.. code:: php - - $vip->remove(); - -Please note that a load balancer must have at least one VIP associated -with it. If you try to remove a load balancer's last VIP, a -``ClientErrorResponseException`` will be thrown. - -Algorithms ----------- - -Load balancers use an **algorithm** to determine how incoming traffic is -distributed amongst the back-end nodes. - -List Load Balancing Algorithms -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can list all supported load balancing algorithms using a load -balancer service object. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $algorithms = $loadBalancerService->algorithmList(); - foreach ($algorithms as $algorithm) { - /** @var $algorithm OpenCloud\LoadBalancer\Resource\Algorithm **/ - } - -Protocols ---------- - -When a load balancer is created a network protocol must be specified. -This network protocol should be based on the network protocol of the -back-end service being load balanced. - -List Load Balancing Protocols -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can list all supported network protocols using a load balancer -service object. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $protocols = $loadBalancerService->protocolList(); - foreach ($protocols as $protocol) { - /** @var $protocol OpenCloud\LoadBalancer\Resource\Protocol **/ - } - -Session Persistence -------------------- - -**Session persistence** is a feature of the load balancing service that -forces multiple requests, of the same protocol, from clients to be -directed to the same node. This is common with many web applications -that do not inherently share application state between back-end servers. - -There are two types (or modes) of session persistence: - -+-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| Name | Description | -+===================+===================================================================================================================================================================================================================================+ -| ``HTTP_COOKIE`` | A session persistence mechanism that inserts an HTTP cookie and is used to determine the destination back-end node. This is supported for HTTP load balancing only. | -+-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| ``SOURCE_IP`` | A session persistence mechanism that will keep track of the source IP address that is mapped and is able to determine the destination back-end node. This is supported for HTTPS pass-through and non-HTTP load balancing only. | -+-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ - -List Session Persistence Configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $sessionPersistence = $loadBalancer->sessionPersistence(); - $sessionPersistenceType = $sessionPersistence->persistenceType; - - /** @var $sessionPersistenceType null | 'HTTP_COOKIE' | 'SOURCE_IP' **/ - -In the example above: - -- If session persistence is enabled, the value of - ``$sessionPersistenceType`` is the type of session persistence: - either ``HTTP_COOKIE`` or ``SOURCE_IP``. -- If session persistence is disabled, the value of - ``$sessionPersistenceType`` is ``null``. - -Enable Session Persistence -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $sessionPersistence = $loadBalancer->sessionPersistence(); - $sessionPersistence->update(array( - 'persistenceType' => 'HTTP_COOKIE' - )); - -Disable Session Persistence -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $sessionPersistence = $loadBalancer->sessionPersistence(); - $sessionPersistence->delete(); - -Connection Logging ------------------- - -The **connection logging** feature allows logs to be delivered to a -Cloud Files account every hour. For HTTP-based protocol traffic, these -are Apache-style access logs. For all other traffic, this is connection -and transfer logging. - -Check Logging Configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - /** @var $connectionLogging bool **/ - - $connectionLogging = $loadBalancer->hasConnectionLogging(); - -In the example above: - -- If connection logging is enabled, the value of ``$connectionLogging`` - is ``true``. -- If connection logging is disabled, the value of - ``$connectionLogging`` is ``false``. - -Enable Connection Logging -~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $loadBalancer->enableConnectionLogging(true); - -Disable Connection Logging -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $loadBalancer->enableConnectionLogging(false); - -Error Page ----------- - -An **error page** is the html file that is shown to the end user when an -error in the service has been thrown. By default every virtual server is -provided with the default error file. It is also possible to set a -custom error page for a load balancer. - -View Error Page Content -~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $errorPage = $loadBalancer->errorPage(); - $errorPageContent = $errorPage->content; - - /** @var $errorPageContent string **/ - -In the example above the value of ``$errorPageContent`` is the HTML for -that page. This could either be the HTML of the default error page or of -your custom error page. - -Set Custom Error Page -~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $errorPage = $loadBalancer->errorPage(); - $errorPage->update(array( - 'content' => '' - )); - -Delete Custom Error Page -~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $errorPage = $loadBalancer->errorPage(); - $errorPage->delete(); - -Allowed Domains ---------------- - -**Allowed domains** are a restricted set of domain names that are -allowed to add load balancer nodes. - -List Allowed Domains -~~~~~~~~~~~~~~~~~~~~ - -You can list all allowed domains using a load balancer service object. -An instance of ``OpenCloud\Common\Collection\PaginatedIterator`` is -returned. - -.. code:: php - - $allowedDomains = $loadBalancerService->allowedDomainList(); - foreach ($allowedDomains as $allowedDomain) { - /** @var $allowedDomain OpenCloud\LoadBalancer\Resource\AllowedDomain **/ - } - -Access Lists ------------- - -**Access Lists** allow fine-grained network access to a load balancer's -VIP. Using access lists, network traffic to a load balancer's VIP can be -allowed or denied from a single IP address, multiple IP addresses or -entire network subnets. - -Note that ``ALLOW`` network items will take precedence over ``DENY`` -network items in an access list. - -To reject traffic from all network items except those with the ``ALLOW`` -type, add a ``DENY`` network item with the address of ``0.0.0.0/0``. - -View Access List -~~~~~~~~~~~~~~~~ - -You can view a load balancer's access list. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $accessList = $loadBalancer->accessList(); - foreach ($accessList as $networkItem) { - /** @var $networkItem OpenCloud\LoadBalancer\Resource\Access **/ - } - -Add Network Items To Access List -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can add network items to a load balancer's access list very easily: - -.. code:: php - - $loadBalancer->createAccessList(array( - (object) array( - 'type' => 'ALLOW', - 'address' => '206.160.165.1/24' - ), - (object) array( - 'type' => 'DENY', - 'address' => '0.0.0.0/0' - ) - )); - -In the above example, we allowed access for 1 IP address, and used the -"0.0.0.0" wildcard to blacklist all other traffic. - -Remove Network Item From Access List -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You an remove a network item from a load balancer's access list. - -.. code:: php - - $networkItem->delete(); - -Content Caching ---------------- - -When **content caching** is enabled on a load balancer, -recently-accessed files are stored on the load balancer for easy -retrieval by web clients. Requests to the load balancer for these files -are serviced by the load balancer itself, which reduces load off its -back-end nodes and improves response times as well. - -Check Content Caching Configuration -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - /** @var $contentCaching bool **/ - - $contentCaching = $loadBalancer->hasContentCaching(); - -In the example above: - -- If content caching is enabled, the value of ``$contentCaching`` is - ``true``. -- If content caching is disabled, the value of ``$contentCaching`` is - ``false``. - -Enable Content Caching -~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $loadBalancer->enableContentCaching(true); - -Disable Content Caching -~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $loadBalancer->enableContentCaching(false); - -SSL Termination ---------------- - -The SSL Termination feature allows a load balancer user to terminate SSL -traffic at the load balancer layer versus at the web server layer. A -user may choose to configure SSL Termination using a key and an SSL -certificate or an (Intermediate) SSL certificate. - -When SSL Termination is configured on a load balancer, a secure shadow -server is created that listens only for secure traffic on a -user-specified port. This shadow server is only visible to and -manageable by the system. Existing or updated attributes on a load -balancer with SSL Termination will also apply to its shadow server. For -example, if Connection Logging is enabled on an SSL load balancer, it -will also be enabled on the shadow server and Cloud Files logs will -contain log files for both. - -View current SSL termination config -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - /** @var $sslConfig OpenCloud\LoadBalancer\Resource\SSLTermination **/ - - $sslConfig = $loadBalancer->SSLTermination(); - -Update SSL termination config -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $sslConfig->update(array( - 'enabled' => true, - 'securePort' => 443, - 'privateKey' => $key, - 'certificate' => $cert - )); - -For a full list, with explanations, of required and optional attributes, -please consult the `official -documentation `__ - -Delete SSL termination config -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $sslConfig->delete(); - -Metadata --------- - -Metadata can be associated with each load balancer and each node for the -client's personal use. It is defined using key-value pairs where the key -and value consist of alphanumeric characters. A key is unique per load -balancer. - -List metadata -~~~~~~~~~~~~~ - -.. code:: php - - $metadataList = $loadBalancer->metadataList(); - - foreach ($metadataList as $metadataItem) { - printf("Key: %s, Value: %s", $metadataItem->key, $metadataItem->value); - } - -Please consult the `iterator -documentation `__ for more information -about iterators. - -Add metadata -~~~~~~~~~~~~ - -.. code:: php - - $metadataItem = $loadBalancer->metadata(); - $metadataItem->create(array( - 'key' => 'foo', - 'value' => 'bar' - )); - -Modify metadata -~~~~~~~~~~~~~~~ - -.. code:: php - - $metadataItem = $loadBalancer->metadata('foo'); - $metadataItem->update(array( - 'value' => 'baz' - )); - -Remove metadata -~~~~~~~~~~~~~~~ - -.. code:: php - - $metadataItem->delete(); - -Monitors --------- - -The load balancing service includes a health monitoring operation which -periodically checks your back-end nodes to ensure they are responding -correctly. If a node is not responding, it is removed from rotation -until the health monitor determines that the node is functional. In -addition to being performed periodically, the health check also is -performed against every node that is added to ensure that the node is -operating properly before allowing it to service traffic. Only one -health monitor is allowed to be enabled on a load balancer at a time. - -.. code:: php - - /** @var $healthMonitor OpenCloud\LoadBalancer\Resource\HealthMonitor **/ - - $healthMonitor = $loadBalancer->healthMonitor(); - - printf( - "Monitoring type: %s, delay: %s, timeout: %s, attempts before deactivation: %s", - $healthMonitor->type, $healthMonitor->delay, $healthMonitor->timeout - ); - -For a full list, with explanations, of required and optional attributes, -please consult the `official -documentation `__ - -Update or delete -~~~~~~~~~~~~~~~~ - -.. code:: php - - // Update - $healthMonitor->update(array( - 'delay' => 120, - 'timeout' => 60, - 'type' => 'CONNECT' - 'attemptsBeforeDeactivation' => 3 - )); - - // Delete - $healthMonitor->delete(); - -Statistics ----------- - -You can retrieve detailed stats about your load balancer, including the -following information: - -- ``connectTimeOut`` – Connections closed by this load balancer because - the 'connect\_timeout' interval was exceeded. -- ``connectError`` – Number of transaction or protocol errors in this - load balancer. -- ``connectFailure`` – Number of connection failures in this load - balancer. -- ``dataTimedOut`` – Connections closed by this load balancer because - the 'timeout' interval was exceeded. -- ``keepAliveTimedOut`` – Connections closed by this load balancer - because the 'keepalive\_timeout' interval was exceeded. -- ``maxConn`` – Maximum number of simultaneous TCP connections this - load balancer has processed at any one time. - -.. code:: php - - /** @var $stats OpenCloud\LoadBalancer\Resource\Stats **/ - - $stats = $loadBalancer->stats(); - -Usage Reports -------------- - -The load balancer usage reports provide a view of all transfer activity, -average number of connections, and number of virtual IPs associated with -the load balancing service. Current usage represents all usage recorded -within the preceding 24 hours. Values for both incomingTransfer and -outgoingTransfer are expressed in bytes transferred. - -The optional startTime and endTime parameters can be used to filter all -usage. If the startTime parameter is supplied but the endTime parameter -is not, then all usage beginning with the startTime will be provided. -Likewise, if the endTime parameter is supplied but the startTime -parameter is not, then all usage will be returned up to the endTime -specified. - -.. code:: php - - # View billable LBs - $billable = $service->billableLoadBalancerList(); - - foreach ($billable as $loadBalancer) { - /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ - - # View usage - /** @var $usage OpenCloud\LoadBalancer\Resource\UsageRecord **/ - $usage = $loadBalancer->usage(); - - echo $usage->averageNumConnections, PHP_EOL; - } - diff --git a/doc/services/load-balancer/access.rst b/doc/services/load-balancer/access.rst new file mode 100644 index 000000000..4387dd8de --- /dev/null +++ b/doc/services/load-balancer/access.rst @@ -0,0 +1,79 @@ +Allowed Domains +=============== + +List Allowed Domains +-------------------- + +You can list all allowed domains using a load balancer service object. +An instance of ``OpenCloud\Common\Collection\PaginatedIterator`` is +returned. + +.. code-block:: php + + $allowedDomains = $service->allowedDomainList(); + + foreach ($allowedDomains as $allowedDomain) { + /** @var $allowedDomain OpenCloud\LoadBalancer\Resource\AllowedDomain **/ + } + + +Access Lists +============ + +Access Lists allow fine-grained network access to a load balancer's VIP. Using +access lists, network traffic to a load balancer's VIP can be allowed or denied +from a single IP address, multiple IP addresses or entire network subnets. + +Note that ``ALLOW`` network items will take precedence over ``DENY`` network +items in an access list. + +To reject traffic from all network items except those with the ``ALLOW`` +type, add a ``DENY`` network item with the address of ``0.0.0.0/0``. + +.. include:: lb-setup.sample.rst + + +View Access List +---------------- + +You can view a load balancer's access list: + +.. code-block:: php + + $accessList = $loadBalancer->accessList(); + + foreach ($accessList as $networkItem) { + /** @var $networkItem OpenCloud\LoadBalancer\Resource\Access **/ + } + + +Add Network Items To Access List +-------------------------------- + +You can add network items to a load balancer's access list very easily: + +.. code-block:: php + + $loadBalancer->createAccessList(array( + (object) array( + 'type' => 'ALLOW', + 'address' => '206.160.165.1/24' + ), + (object) array( + 'type' => 'DENY', + 'address' => '0.0.0.0/0' + ) + )); + +In the above example, we allowed access for 1 IP address, and used the +"0.0.0.0" wildcard to blacklist all other traffic. + + +Remove Network Item From Access List +------------------------------------ + +You an remove a network item from a load balancer's access list: + +.. code-block:: php + + $networkItem->delete(); diff --git a/doc/services/load-balancer/caching.rst b/doc/services/load-balancer/caching.rst new file mode 100644 index 000000000..6678e048a --- /dev/null +++ b/doc/services/load-balancer/caching.rst @@ -0,0 +1,35 @@ +Content Caching +=============== + +When content caching is enabled on a load balancer, recently-accessed files are +stored on the load balancer for easy retrieval by web clients. Requests to the +load balancer for these files are serviced by the load balancer itself, which +reduces load off its back-end nodes and improves response times as well. + + +.. include:: lb-setup.sample.rst + + +Check Configuration +------------------- + +.. code-block:: php + + // TRUE if enabled, FALSE if not + $contentCaching = $loadBalancer->hasContentCaching(); + + +Enable Content Caching +---------------------- + +.. code-block:: php + + $loadBalancer->enableContentCaching(true); + + +Disable Content Caching +----------------------- + +.. code-block:: php + + $loadBalancer->enableContentCaching(false); diff --git a/doc/services/load-balancer/errors.rst b/doc/services/load-balancer/errors.rst new file mode 100644 index 000000000..041c19d45 --- /dev/null +++ b/doc/services/load-balancer/errors.rst @@ -0,0 +1,44 @@ +Error Pages +=========== + +.. include:: lb-setup.sample.rst + +An error page is the html file that is shown to the end user when an error in +the service has been thrown. By default every virtual server is provided with +the default error file. It is also possible to set a custom error page for a +load balancer. + + +View Error Page Content +----------------------- + +.. code-block:: php + + $errorPage = $loadBalancer->errorPage(); + $errorPageContent = $errorPage->content; + + /** @var $errorPageContent string **/ + +In the example above the value of ``$errorPageContent`` is the HTML for +that page. This could either be the HTML of the default error page or of +your custom error page. + + +Set Custom Error Page +--------------------- + +.. code-block:: php + + $errorPage = $loadBalancer->errorPage(); + $errorPage->update(array( + 'content' => '' + )); + + +Delete Custom Error Page +------------------------ + +.. code-block:: php + + $errorPage = $loadBalancer->errorPage(); + $errorPage->delete(); diff --git a/doc/services/load-balancer/index.rst b/doc/services/load-balancer/index.rst index e69de29bb..bf2b6dd0c 100644 --- a/doc/services/load-balancer/index.rst +++ b/doc/services/load-balancer/index.rst @@ -0,0 +1,93 @@ +Load Balancer v1 +================ + +.. note:: + + This service is only available for Rackspace users. + + +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now, set up the Load Balancer service: + +.. code-block:: php + + $service = $client->loadBalancerService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + +.. toctree:: + + load-balancers + nodes + virtual-ips + access + caching + errors + logging + monitors + metadata + sessions + ssl + stats + + +Glossary +-------- + + allowed domain + Allowed domains are a restricted set of domain names that are allowed to add + load balancer nodes. + + content caching + When content caching is enabled on a load balancer, recently-accessed files + are stored on the load balancer for easy retrieval by web clients. Requests to + the load balancer for these files are serviced by the load balancer itself, + which reduces load off its back-end nodes and improves response times as well. + + health monitor + The load balancing service includes a health monitoring operation which + periodically checks your back-end nodes to ensure they are responding + correctly. If a node is not responding, it is removed from rotation until the + health monitor determines that the node is functional. In addition to being + performed periodically, the health check also is performed against every node + that is added to ensure that the node is operating properly before allowing it + to service traffic. Only one health monitor is allowed to be enabled on a load + balancer at a time. + + load balancer + A load balancer is a device that distributes incoming network + traffic amongst multiple back-end systems. These back-end systems are + called the nodes of the load balancer. + + metadata + Metadata can be associated with each load balancer and each node for the + client's personal use. It is defined using key-value pairs where the key + and value consist of alphanumeric characters. A key is unique per load + balancer. + + node + A node is a backend device that provides a service on specified IP and port. + An example of a load balancer node might be a web server serving HTTP + traffic on port 8080. A load balancer typically has multiple nodes attached + to it so it can distribute incoming network traffic amongst them. + + session persistence + Session persistence is a feature of the load balancing service that forces + multiple requests, of the same protocol, from clients to be directed to the + same node. This is common with many web applications that do not inherently + share application state between back-end servers. + + virtual IP + A virtual IP (VIP) makes a load balancer accessible by clients. The + load balancing service supports either a public VIP address + (``PUBLIC``), routable on the public Internet, or a ServiceNet VIP + address (``SERVICENET``), routable only within the region in which the + load balancer resides. diff --git a/doc/services/load-balancer/lb-setup.sample.rst b/doc/services/load-balancer/lb-setup.sample.rst new file mode 100644 index 000000000..96e228b8d --- /dev/null +++ b/doc/services/load-balancer/lb-setup.sample.rst @@ -0,0 +1,9 @@ +Setup +----- + +In order to interact with this feature you must first retrieve a particular +load balancer, like so: + +.. code-block:: php + + $loadBalancer = $service->loadBalancer('{id}'); diff --git a/doc/services/load-balancer/load-balancer.rst b/doc/services/load-balancer/load-balancer.rst new file mode 100644 index 000000000..7071794df --- /dev/null +++ b/doc/services/load-balancer/load-balancer.rst @@ -0,0 +1,165 @@ +Load Balancer +============= + +.. note:: + + Many of the examples in this document use two cloud servers as nodes for + the load balancer. The variables ``$serverOne`` and ``$serverTwo`` refer + to these two cloud servers. + + +Create Load Balancer +-------------------- + +The first step is to instantiate an empty object, like so: + +.. code-block:: php + + $loadBalancer = $service->loadBalancer(); + +In essence, all a load balancer does is evenly distribute traffic between +various back-end nodes - which can be Compute or Database instances. So we will +need to add a few when creating our load balancer: + +.. code-block:: php + + $serverOneNode = $loadBalancer->node(); + $serverOneNode->address = $serverOne->addresses->private[0]->addr; + $serverOneNode->port = 8080; + $serverOneNode->condition = 'ENABLED'; + + $serverTwoNode = $loadBalancer->node(); + $serverTwoNode->address = $serverTwo->addresses->private[0]->addr; + $serverTwoNode->port = 8080; + $serverTwoNode->condition = 'ENABLED'; + + +All that remains is apply final configuration touches, such as name and the +port number, before submitting to the API: + +.. code-block:: php + + $loadBalancer->addVirtualIp('PUBLIC'); + $loadBalancer->create(array( + 'name' => 'My load balancer', + 'port' => 80, + 'protocol' => 'HTTP', + 'nodes' => array($serverOneNode, $serverTwoNode), + 'algorithm' => 'ROUND_ROBIN', + )); + +For a full list of available `protocols <#protocols>`_ and `algorithms <#algorithms>`_ +please see the sections below. + + +List Load Balancer Details +-------------------------- + +You can retrieve a single load balancer's details by using its ID: + +.. code-block:: php + + /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ + $loadBalancer = $service->loadBalancer('{loadBalancerId}'); + + +List Load Balancers +~~~~~~~~~~~~~~~~~~~ + +You can retrieve a list of all your load balancers: + +.. code-block:: php + + $loadBalancers = $service->loadBalancerList(); + + foreach ($loadBalancers as $loadBalancer) { + /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ + } + + +Update a Load Balancer +---------------------- + +You can update one or more of the following load balancer attributes: + +- ``name``: The name of the load balancer +- ``algorithm``: The algorithm used by the load balancer to distribute + traffic amongst its nodes. See also: `Load balancing + algorithms <#algorithms>`__. +- ``protocol``: The network protocol used by traffic coming in to the + load balancer. See also: `Protocols <#protocols>`__. +- ``port``: The network port on which the load balancer listens for + incoming traffic. +- ``halfClosed``: Enable or Disable Half-Closed support for the load + balancer. +- ``timeout``: The timeout value for the load balancer to communicate + with its nodes. +- ``httpsRedirect``: Enable or disable HTTP to HTTPS redirection for + the load balancer. When enabled, any HTTP request will return status + code 301 (Moved Permanently), and the requestor will be redirected to + the requested URL via the HTTPS protocol on port 443. For example, + http://example.com/page.html would be redirected to https:// + example.com/page.html. Only available for HTTPS protocol (``port`` = + 443), or HTTP Protocol with a properly configured SSL Termination + (\`secureTrafficOnly=true, securePort=443). See also: `SSL + Termination <#ssl-termination>`__. + +.. code-block:: php + + $loadBalancer->update(array( + 'name' => 'New name', + 'algorithm' => 'ROUND_ROBIN' + )); + + +Remove Load Balancer +~~~~~~~~~~~~~~~~~~~~ + +When you no longer have a need for the load balancer, you can remove it: + +.. code-block:: php + + $loadBalancer->delete(); + + +Protocols +--------- + +When a load balancer is created a network protocol must be specified. +This network protocol should be based on the network protocol of the +back-end service being load balanced. Common protocols are ``HTTP``, ``HTTPS`` +and ``MYSQL``. A full list is available `here `_. + +List Load Balancing Protocols +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can list all supported network protocols like so: + +.. code-block:: php + + $protocols = $service->protocolList(); + + foreach ($protocols as $protocol) { + /** @var $protocol OpenCloud\LoadBalancer\Resource\Protocol **/ + } + + +Algorithms +---------- + +Load balancers use an **algorithm** to determine how incoming traffic is +distributed amongst the back-end nodes. A full list is available `here +`_. + +List Load Balancing Algorithms +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can programmatically list all supported load balancing algorithms: + +.. code-block:: php + + $algorithms = $service->algorithmList(); + + foreach ($algorithms as $algorithm) { + /** @var $algorithm OpenCloud\LoadBalancer\Resource\Algorithm **/ + } diff --git a/doc/services/load-balancer/logging.rst b/doc/services/load-balancer/logging.rst new file mode 100644 index 000000000..29c37aee2 --- /dev/null +++ b/doc/services/load-balancer/logging.rst @@ -0,0 +1,33 @@ +Connection Logging +================== + +The connection logging feature allows logs to be delivered to a Cloud Files +account every hour. For HTTP-based protocol traffic, these are Apache-style +access logs. For all other traffic, this is connection and transfer logging. + +.. include:: lb-setup.sample.rst + + +Check Configuration +------------------- + +.. code-block:: php + + // TRUE if enabled, FALSE if not + $connectionLogging = $loadBalancer->hasConnectionLogging(); + + +Enable Connection Logging +------------------------- + +.. code-block:: php + + $loadBalancer->enableConnectionLogging(true); + + +Disable Connection Logging +-------------------------- + +.. code-block:: php + + $loadBalancer->enableConnectionLogging(false); diff --git a/doc/services/load-balancer/metadata.rst b/doc/services/load-balancer/metadata.rst new file mode 100644 index 000000000..2b38de129 --- /dev/null +++ b/doc/services/load-balancer/metadata.rst @@ -0,0 +1,46 @@ +Metadata +======== + +.. include:: lb-setup.sample.rst + +List metadata +------------- + +.. code-block:: php + + $metadataList = $loadBalancer->metadataList(); + + foreach ($metadataList as $metadataItem) { + printf("Key: %s, Value: %s", $metadataItem->key, $metadataItem->value); + } + + +Add metadata +------------ + +.. code-block:: php + + $metadataItem = $loadBalancer->metadata(); + $metadataItem->create(array( + 'key' => 'foo', + 'value' => 'bar' + )); + + +Modify metadata +--------------- + +.. code-block:: php + + $metadataItem = $loadBalancer->metadata('foo'); + $metadataItem->update(array( + 'value' => 'baz' + )); + + +Remove metadata +--------------- + +.. code-block:: php + + $metadataItem->delete(); diff --git a/doc/services/load-balancer/monitors.rst b/doc/services/load-balancer/monitors.rst new file mode 100644 index 000000000..9c463f270 --- /dev/null +++ b/doc/services/load-balancer/monitors.rst @@ -0,0 +1,43 @@ +Health Monitors +=============== + +.. include:: lb-setup.sample.rst + +Retrieve monitor details +------------------------ + +.. code-block:: php + + /** @var $healthMonitor OpenCloud\LoadBalancer\Resource\HealthMonitor **/ + + $healthMonitor = $loadBalancer->healthMonitor(); + + printf( + "Monitoring type: %s, delay: %s, timeout: %s, attempts before deactivation: %s", + $healthMonitor->type, $healthMonitor->delay, $healthMonitor->timeout + ); + +For a full list, with explanations, of required and optional attributes, +please consult the `official +documentation `__ + + +Update monitor +-------------- + +.. code-block:: php + + $healthMonitor->update(array( + 'delay' => 120, + 'timeout' => 60, + 'type' => 'CONNECT' + 'attemptsBeforeDeactivation' => 3 + )); + + +Delete monitor +-------------- + +.. code-block:: php + + $healthMonitor->delete(); diff --git a/doc/services/load-balancer/nodes.rst b/doc/services/load-balancer/nodes.rst new file mode 100644 index 000000000..dfaadc404 --- /dev/null +++ b/doc/services/load-balancer/nodes.rst @@ -0,0 +1,124 @@ +Nodes +===== + +.. include:: lb-setup.sample.rst + +List Nodes +---------- + +You can list the nodes attached to a load balancer: + +.. code-block:: php + + $nodes = $loadBalancer->nodeList(); + + foreach ($nodes as $node) { + /** @var $node OpenCloud\LoadBalancer\Resource\Node **/ + } + + +Add Nodes +--------- + +You can attach additional nodes to a load balancer. Assume +``$loadBalancer`` already has two nodes attached to it - ``$serverOne`` +and ``$serverTwo`` - and you want to attach a third node to it, say +``$serverThree``, which provides a service on port 8080. + +**Important:** Remember to call ``$loadBalancer->addNodes()`` after all +the calls to ``$loadBalancer->addNode()`` as shown below. + +.. code-block:: php + + $address = $serverThree->addresses->private[0]->addr; + $loadBalancer->addNode($address, 8080); + $loadBalancer->addNodes(); + + +The signature for ``addNodes`` is as follows: + +.. function:: addNodes($address, $port[, $condition = 'ENABLED'[, $type = null[, $weight = null]]]) + + Add a node to a load balancer + + :param string $address: the IP address of the node + :param integer $port: the port number of the node + :param string $condition: the initial condition of the code. Defaults to ``ENABLED`` + :param string $type: either ``PRIMARY`` or ``SECONDARY`` + :param integer $weight: the node weight (for round-robin algorithm) + +The ``addNode`` method accepts three more optional parameters, in +addition to the two shown above: + +Modify Nodes +------------ + +You can modify one or more of the following node attributes: + +- ``condition``: The condition of the load balancer: + + - ``ENABLED`` – Node is ready to receive traffic from the load + balancer. + - ``DISABLED`` – Node should not receive traffic from the load + balancer. + - ``DRAINING`` – Node should process any traffic it is already + receiving but should not receive any further traffic from the load + balancer. + +- ``type``: The type of the node: + + - ``PRIMARY`` – Nodes defined as PRIMARY are in the normal rotation + to receive traffic from the load balancer. + - ``SECONDARY`` – Nodes defined as SECONDARY are only in the + rotation to receive traffic from the load balancer when all the + primary nodes fail. + +- ``weight``: The weight, between 1 and 100, given to node when + distributing traffic using either the ``WEIGHTED_ROUND_ROBIN`` or the + ``WEIGHTED_LEAST_CONNECTIONS`` load balancing algorithm. + +.. code-block:: php + + use OpenCloud\LoadBalancer\Enum\NodeCondition; + use OpenCloud\LoadBalancer\Enum\NodeType; + + $node->update(array( + 'condition' => NodeCondition::DISABLED, + 'type' => NodeType::SECONDARY + )); + + +Remove Nodes +------------ + +There are two ways to remove a node. The first way is on an +``OpenCloud\LoadBalancer\Resource\Node`` instance, like so: + + +.. code-block:: php + + $node->delete(); + +The second is with an ``OpenCloud\LoadBalancer\Resource\LoadBalancer`` +instance and the node's ID, like so: + +.. code-block:: php + + $loadBalancer->removeNode('{nodeId}'); + +where '{nodeId}' is the integer ID of the node itself - this is a required value. + + +View Node Service Events +------------------------ + +You can view events associated with the activity between a node and a +load balancer: + +.. code-block:: php + + $nodeEvents = $loadBalancer->nodeEventList(); + + foreach ($nodeEvents as $nodeEvent) { + /** @var $nodeEvent OpenCloud\LoadBalancer\Resource\NodeEvent **/ + } diff --git a/doc/services/load-balancer/sessions.rst b/doc/services/load-balancer/sessions.rst new file mode 100644 index 000000000..3d7f71cfe --- /dev/null +++ b/doc/services/load-balancer/sessions.rst @@ -0,0 +1,53 @@ +Session Persistence +=================== + +There are two types (or modes) of session persistence: + ++-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Name | Description | ++===================+===================================================================================================================================================================================================================================+ +| ``HTTP_COOKIE`` | A session persistence mechanism that inserts an HTTP cookie and is used to determine the destination back-end node. This is supported for HTTP load balancing only. | ++-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| ``SOURCE_IP`` | A session persistence mechanism that will keep track of the source IP address that is mapped and is able to determine the destination back-end node. This is supported for HTTPS pass-through and non-HTTP load balancing only. | ++-------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +.. include:: lb-setup.sample.rst + + +List Session Persistence Configuration +-------------------------------------- + +.. code-block:: php + + $sessionPersistence = $loadBalancer->sessionPersistence(); + + /** @var $sessionPersistenceType null | 'HTTP_COOKIE' | 'SOURCE_IP' **/ + $sessionPersistenceType = $sessionPersistence->persistenceType; + +In the example above: + +- If session persistence is enabled, the value of + ``$sessionPersistenceType`` is the type of session persistence: + either ``HTTP_COOKIE`` or ``SOURCE_IP``. +- If session persistence is disabled, the value of + ``$sessionPersistenceType`` is ``null``. + + +Enable Session Persistence +-------------------------- + +.. code-block:: php + + $sessionPersistence = $loadBalancer->sessionPersistence(); + $sessionPersistence->update(array( + 'persistenceType' => 'HTTP_COOKIE' + )); + + +Disable Session Persistence +--------------------------- + +.. code-block:: php + + $sessionPersistence = $loadBalancer->sessionPersistence(); + $sessionPersistence->delete(); diff --git a/doc/services/load-balancer/ssl.rst b/doc/services/load-balancer/ssl.rst new file mode 100644 index 000000000..12b28a6af --- /dev/null +++ b/doc/services/load-balancer/ssl.rst @@ -0,0 +1,52 @@ +SSL Termination +=============== + +The SSL Termination feature allows a load balancer user to terminate SSL +traffic at the load balancer layer versus at the web server layer. A +user may choose to configure SSL Termination using a key and an SSL +certificate or an (Intermediate) SSL certificate. + +When SSL Termination is configured on a load balancer, a secure shadow +server is created that listens only for secure traffic on a +user-specified port. This shadow server is only visible to and +manageable by the system. Existing or updated attributes on a load +balancer with SSL Termination will also apply to its shadow server. For +example, if Connection Logging is enabled on an SSL load balancer, it +will also be enabled on the shadow server and Cloud Files logs will +contain log files for both. + +.. include:: lb-setup.sample.rst + + +View configuration +------------------ + +.. code-block:: php + + /** @var $sslConfig OpenCloud\LoadBalancer\Resource\SSLTermination **/ + $sslConfig = $loadBalancer->SSLTermination(); + + +Update configuration +-------------------- + +.. code-block:: php + + $sslConfig->update(array( + 'enabled' => true, + 'securePort' => 443, + 'privateKey' => $key, + 'certificate' => $cert + )); + +For a full list, with explanations, of required and optional attributes, +please consult the `official +documentation `__ + + +Delete configuration +-------------------- + +.. code-block:: php + + $sslConfig->delete(); diff --git a/doc/services/load-balancer/stats.rst b/doc/services/load-balancer/stats.rst new file mode 100644 index 000000000..65077643f --- /dev/null +++ b/doc/services/load-balancer/stats.rst @@ -0,0 +1,59 @@ +Statistics and Usage Reports +============================ + +.. include:: lb-setup.sample.rst + +Retrieve LB stats +----------------- + +You can retrieve detailed stats about your load balancer, including the +following information: + +- ``connectTimeOut`` – Connections closed by this load balancer because + the 'connect_timeout' interval was exceeded. +- ``connectError`` – Number of transaction or protocol errors in this + load balancer. +- ``connectFailure`` – Number of connection failures in this load balancer. +- ``dataTimedOut`` – Connections closed by this load balancer because + the 'timeout' interval was exceeded. +- ``keepAliveTimedOut`` – Connections closed by this load balancer + because the 'keepalive_timeout' interval was exceeded. +- ``maxConn`` – Maximum number of simultaneous TCP connections this + load balancer has processed at any one time. + +.. code-block:: php + + /** @var $stats OpenCloud\LoadBalancer\Resource\Stats **/ + $stats = $loadBalancer->stats(); + + +Usage Reports +------------- + +The load balancer usage reports provide a view of all transfer activity, +average number of connections, and number of virtual IPs associated with +the load balancing service. Current usage represents all usage recorded +within the preceding 24 hours. Values for both incomingTransfer and +outgoingTransfer are expressed in bytes transferred. + +The optional startTime and endTime parameters can be used to filter all +usage. If the startTime parameter is supplied but the endTime parameter +is not, then all usage beginning with the startTime will be provided. +Likewise, if the endTime parameter is supplied but the startTime +parameter is not, then all usage will be returned up to the endTime +specified. + +.. code-block:: php + + # View billable LBs + $billable = $service->billableLoadBalancerList(); + + foreach ($billable as $loadBalancer) { + /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ + + # View usage + /** @var $usage OpenCloud\LoadBalancer\Resource\UsageRecord **/ + $usage = $loadBalancer->usage(); + + echo $usage->averageNumConnections, PHP_EOL; + } diff --git a/doc/services/load-balancer/virtual-ips.rst b/doc/services/load-balancer/virtual-ips.rst new file mode 100644 index 000000000..fa0add613 --- /dev/null +++ b/doc/services/load-balancer/virtual-ips.rst @@ -0,0 +1,74 @@ +Virtual IPs +=========== + +.. include:: lb-setup.sample.rst + + +List Virtual IPs +---------------- + +You can list the VIPs associated with a load balancer like so: + +.. code-block:: php + + $vips = $loadBalancer->virtualIpList(); + + foreach ($vips as $vip) { + /** @var $vip of OpenCloud\LoadBalancer\Resource\VirtualIp **/ + } + + +Get existing VIP +---------------- + +To retrieve the details of an existing VIP on a load balancer, you will need +its ID: + +.. code-block:: + + $vip = $loadBalancer->virtualIp('{virtualIpId}'); + + +Add Virtual IPv6 +---------------- + +You can add additional IPv6 VIPs to a load balancer using the following method: + +.. code-block:: php + + use OpenCloud\LoadBalancer\Enum\IpType; + + $loadBalancer->addVirtualIp(IpType::PUBLIC, 6); + +the first argument is the type of network your IP address will server traffic in +- and can either be ``PUBLIC`` or ``PRIVATE``. The second argument is the version +of IP address, either ``4`` or ``6``. + + +Add Virtual IPv4 +---------------- + +Similar to above: + +.. code-block:: php + + use OpenCloud\LoadBalancer\Enum\IpType; + + $loadBalancer->addVirtualIp(IpType::PUBLIC, 4); + + +Remove Virtual IP +----------------- + +You can remove a VIP from a load balancer. + +.. code-block:: php + + $vip->remove(); + + +.. note:: + + A load balancer must have at least one VIP associated with it. If you try to + remove a load balancer's last VIP, a ``ClientErrorResponseException`` will be + thrown. From 19d081e22e35fe48ba4bd3543196dba4b9132a78 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 15:29:32 +0100 Subject: [PATCH 128/181] Add monitoring docs --- doc/services/monitoring/Agents.md.rst | 202 -------------- doc/services/monitoring/Entities.md.rst | 77 ------ doc/services/monitoring/Service.md.rst | 23 -- doc/services/monitoring/agents.rst | 188 +++++++++++++ .../monitoring/{Alarms.md.rst => alarms.rst} | 84 +++--- .../{Changelogs.md.rst => changelogs.rst} | 17 +- .../monitoring/{Checks.md.rst => checks.rst} | 189 +++++++------ doc/services/monitoring/entities.rst | 77 ++++++ doc/services/monitoring/index.rst | 34 +++ .../{Metrics.md.rst => metrics.rst} | 54 ++-- ...Notifications.md.rst => notifications.rst} | 252 ++++++++++-------- .../monitoring/{Views.md.rst => views.rst} | 20 +- .../monitoring/{Zones.md.rst => zones.rst} | 42 ++- 13 files changed, 661 insertions(+), 598 deletions(-) delete mode 100644 doc/services/monitoring/Agents.md.rst delete mode 100644 doc/services/monitoring/Entities.md.rst delete mode 100644 doc/services/monitoring/Service.md.rst create mode 100644 doc/services/monitoring/agents.rst rename doc/services/monitoring/{Alarms.md.rst => alarms.rst} (66%) rename doc/services/monitoring/{Changelogs.md.rst => changelogs.rst} (52%) rename doc/services/monitoring/{Checks.md.rst => checks.rst} (80%) create mode 100644 doc/services/monitoring/entities.rst rename doc/services/monitoring/{Metrics.md.rst => metrics.rst} (83%) rename doc/services/monitoring/{Notifications.md.rst => notifications.rst} (64%) rename doc/services/monitoring/{Views.md.rst => views.rst} (58%) rename doc/services/monitoring/{Zones.md.rst => zones.rst} (71%) diff --git a/doc/services/monitoring/Agents.md.rst b/doc/services/monitoring/Agents.md.rst deleted file mode 100644 index 943983f7e..000000000 --- a/doc/services/monitoring/Agents.md.rst +++ /dev/null @@ -1,202 +0,0 @@ -Agents -====== - -Intro ------ - -The Monitoring Agent resides on the host server being monitored. The -agent allows you to gather on-host metrics based on agent checks and -push them to Cloud Monitoring where you can analyze them, use them with -the Cloud Monitoring infrastructure (such as alarms), and archive them. - -For more information about this feature, including a brief overview of -its core design principles and security layers, see the `official API -documentation `__. - -Setup ------ - -.. code:: php - - $agentId = '00-agent.example.com'; - $agent = $service->getAgent($agentId); - -You can view the `service page `__ for more information -about setting up the Cloud Monitoring service. - -List agents ------------ - -.. code:: php - - $agents = $service->getAgents(); - - foreach ($agents as $agent) { - echo $agent->getLastConnected(); - } - -Please consult the `iterator doc `__ for -more information about iterators. - -List connections ----------------- - -.. code:: php - - $connections = $agent->getConnections(); - -Please consult the `iterator doc `__ for -more information about iterators. - -Get connection --------------- - -.. code:: php - - /** @var \OpenCloud\CloudMonitoring\Resource\AgentConnection */ - $connection = $agent->getConnection('cntl4qsIbA'); - -Agent Connection properties -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -+--------------------+---------------+--------+---------------------------+ -| Name | Description | Type | Method | -+====================+===============+========+===========================+ -| id | - | - | ``getId()`` | -+--------------------+---------------+--------+---------------------------+ -| guid | - | - | ``getGuid()`` | -+--------------------+---------------+--------+---------------------------+ -| agent\_id | - | - | ``getAgentId()`` | -+--------------------+---------------+--------+---------------------------+ -| endpoint | - | - | ``getEndpoint()`` | -+--------------------+---------------+--------+---------------------------+ -| process\_version | - | - | ``getProcessVersion()`` | -+--------------------+---------------+--------+---------------------------+ -| bundle\_version | - | - | ``getBundleVersion()`` | -+--------------------+---------------+--------+---------------------------+ -| agent\_ip | - | - | ``getAgentIp()`` | -+--------------------+---------------+--------+---------------------------+ - -Agent tokens -============ - -Intro ------ - -Agent tokens are used to authenticate Monitoring agents to the -Monitoring Service. Multiple agents can share a single token. - -Setup ------ - -.. code:: php - - $tokenId = '4c5e28f0-0b3f-11e1-860d-c55c4705a286:1234'; - $agentToken = $service->getAgentToken($tokenId); - -Create agent token ------------------- - -.. code:: php - - $newToken = $service->getAgentToken(); - $newToken->create(array('label' => 'Foobar')); - -List agent tokens ------------------ - -.. code:: php - - $agentTokens = $service->getAgentTokens(); - - foreach ($agentTokens as $token) { - echo $token->getLabel(); - } - -Please consult the `iterator doc `__ for -more information about iterators. - -Update and delete Agent Token ------------------------------ - -.. code:: php - - // Update - $token->update(array( - 'label' => 'New label' - )); - - // Delete - $token->delete(); - -Agent Host Information -====================== - -Info ----- - -An agent can gather host information, such as process lists, network -configuration, and memory usage, on demand. You can use the -host-information API requests to gather this information for use in -dashboards or other utilities. - -Setup ------ - -.. code:: php - - $host = $monitoringService->getAgentHost(); - -Get some metrics ----------------- - -.. code:: php - - $cpuInfo = $host->info('cpus'); - $diskInfo = $host->info('disks'); - $filesystemInfo = $host->info('filesystems'); - $memoryInfo = $host->info('memory'); - $networkIntInfo = $host->info('network_interfaces'); - $processesInfo = $host->info('processes'); - $systemInfo = $host->info('system'); - $userInfo = $host->info('who'); - - // What CPU models do we have? - foreach ($cpuInfo as $cpuMetric) { - echo $cpuMetric->model, PHP_EOL; - } - - // How many disks do we have? - echo $diskInfo->count(); - - // What's the available space on our ext4 filesystem? - foreach ($filesystemInfo as $filesystemMetric) { - if ($filesystemMetric->sys_type_name == 'ext4') { - echo $filesystemMetric->avail; - } - } - -Agent targets -============= - -Info ----- - -Each agent check type gathers data for a related set of target devices -on the server where the agent is installed. For example, -``agent.network`` gathers data for network devices. The actual list of -target devices is specific to the configuration of the host server. By -focusing on specific targets, you can efficiently narrow the metric data -that the agent gathers. - -List agent targets -~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $targets = $service->getAgentTargets(); - - foreach ($targets as $target) { - echo $target->getType(); - } - diff --git a/doc/services/monitoring/Entities.md.rst b/doc/services/monitoring/Entities.md.rst deleted file mode 100644 index 068aec122..000000000 --- a/doc/services/monitoring/Entities.md.rst +++ /dev/null @@ -1,77 +0,0 @@ - Entities -========= - -Info ----- - -An entity is the target of what you are monitoring. For example, you can -create an entity to monitor your website, a particular web service, or -your Rackspace server. Note that an entity represents only one item in -the monitoring system -- if you wanted to monitor each server in a -cluster, you would create an entity for each of the servers. You would -not create a single entity to represent the entire cluster. - -An entity can have multiple checks associated with it. This allows you -to check multiple services on the same host by creating multiple checks -on the same entity, instead of multiple entities each with a single -check. - -Setup ------ - -.. code:: php - - $entity = $service->getEntity(); - -For more information about setting up the ``$service`` object, please -see the userguide tutorial for `services `__. - -Attributes ----------- - -+-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ -| Name | Description | Required? | Data type | Method | -+=================+=========================================================================+=============+=====================================================+========================+ -| label | Defines a name for the entity. | Required | String (1..255 chars) | ``getLabel()`` | -+-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ -| agent\_id | Agent to which this entity is bound to. | Optional | String matching the regex: ``/^[-\.\w]{1,255}$/`` | ``getAgentId()`` | -+-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ -| ip\_addresses | Hash of IP addresses that can be referenced by checks on this entity. | Optional | Array | ``getIpAddresses()`` | -+-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ -| metadata | Arbitrary key/value pairs that are passed during the alerting phase. | Optional | ``OpenCloud\Common\Metadata`` | ``getMetadata()`` | -+-----------------+-------------------------------------------------------------------------+-------------+-----------------------------------------------------+------------------------+ - -Create Entity -------------- - -.. code:: php - - $service->createEntity(array( - 'label' => 'Brand New Entity', - 'ip_addresses' => array( - 'default' => '127.0.0.4', - 'b' => '127.0.0.5', - 'c' => '127.0.0.6', - 'test' => '127.0.0.7' - ), - 'metadata' => array( - 'all' => 'kinds', - 'of' => 'stuff', - 'can' => 'go', - 'here' => 'null is not a valid value' - ) - )); - -Update and delete Entity ------------------------- - -.. code:: php - - // Update - $entity->update(array( - 'label' => 'New label for my entity' - )); - - // Delete - $entity->delete(); - diff --git a/doc/services/monitoring/Service.md.rst b/doc/services/monitoring/Service.md.rst deleted file mode 100644 index 09c25c21d..000000000 --- a/doc/services/monitoring/Service.md.rst +++ /dev/null @@ -1,23 +0,0 @@ -Cloud Monitoring Service -======================== - -Initializing the Cloud Monitoring is easy - and can be done in a similar -way to all other Rackspace services: - -1. Create client and pass in auth details. For more information about - creating clients, please consult the `Client - documentation <../Clients.md>`__. -2. Use the factory method, specifying additional parameters where - necessary: - -.. code:: php - - $service = $client->cloudMonitoringService('cloudMonitoring', 'ORD', 'publicURL'); - -All three parameters are optional - if not specified, it will revert to -the service's default values which are: - -- Name = ``cloudMonitoring`` -- Region = ``DFW`` -- URL type = ``publicURL`` - diff --git a/doc/services/monitoring/agents.rst b/doc/services/monitoring/agents.rst new file mode 100644 index 000000000..f4c673608 --- /dev/null +++ b/doc/services/monitoring/agents.rst @@ -0,0 +1,188 @@ +Agents +====== + +The Monitoring Agent resides on the host server being monitored. The +agent allows you to gather on-host metrics based on agent checks and +push them to Cloud Monitoring where you can analyze them, use them with +the Cloud Monitoring infrastructure (such as alarms), and archive them. + +For more information about this feature, including a brief overview of +its core design principles and security layers, see the `official API +documentation `__. + +Retrieve details about an agent +------------------------------- + +.. code-block:: php + + $agent = $service->getAgent('{agentId}'); + + +List agents +----------- + +.. code-block:: php + + $agents = $service->getAgents(); + + foreach ($agents as $agent) { + echo $agent->getLastConnected(); + } + + +List connections +---------------- + +.. code-block:: php + + $connections = $agent->getConnections(); + + +Get connection +-------------- + +.. code-block:: php + + /** @var \OpenCloud\CloudMonitoring\Resource\AgentConnection */ + $connection = $agent->getConnection('{connectionId}'); + + +Once you have access to an agent's ``OpenCloud\CloudMonitoring\Resource\AgentConnection`` +object, these are the attributes you can access: + ++--------------------+---------------------------+ +| Name | Method | ++====================+===========================+ +| id | ``getId()`` | ++--------------------+---------------------------+ +| guid | ``getGuid()`` | ++--------------------+---------------------------+ +| agent_id | ``getAgentId()`` | ++--------------------+---------------------------+ +| endpoint | ``getEndpoint()`` | ++--------------------+---------------------------+ +| process_version | ``getProcessVersion()`` | ++--------------------+---------------------------+ +| bundle_version | ``getBundleVersion()`` | ++--------------------+---------------------------+ +| agent_ip | ``getAgentIp()`` | ++--------------------+---------------------------+ + +Agent tokens +============ + +Agent tokens are used to authenticate Monitoring agents to the +Monitoring Service. Multiple agents can share a single token. + +Retrieve an agent token +----------------------- + +.. code-block:: php + + $agentToken = $service->getAgentToken('{tokenId}'); + + +Create agent token +------------------ + +.. code-block:: php + + $newToken = $service->getAgentToken(); + $newToken->create(array('label' => 'Foobar')); + + +List agent tokens +----------------- + +.. code-block:: php + + $agentTokens = $service->getAgentTokens(); + + foreach ($agentTokens as $token) { + echo $token->getLabel(); + } + + +Update agent token +------------------ + +.. code-block:: php + + $token->update(array( + 'label' => 'New label' + )); + + +Update agent token +------------------ + +.. code-block:: php + + $token->delete(); + + +Agent Host Information +====================== + +An agent can gather host information, such as process lists, network +configuration, and memory usage, on demand. You can use the +host-information API requests to gather this information for use in +dashboards or other utilities. + +Setup +----- + +.. code-block:: php + + $host = $service->getAgentHost(); + + +Get some metrics +---------------- + +.. code-block:: php + + $cpuInfo = $host->info('cpus'); + $diskInfo = $host->info('disks'); + $filesystemInfo = $host->info('filesystems'); + $memoryInfo = $host->info('memory'); + $networkIntInfo = $host->info('network_interfaces'); + $processesInfo = $host->info('processes'); + $systemInfo = $host->info('system'); + $userInfo = $host->info('who'); + + // What CPU models do we have? + foreach ($cpuInfo as $cpuMetric) { + echo $cpuMetric->model, PHP_EOL; + } + + // How many disks do we have? + echo $diskInfo->count(); + + // What's the available space on our ext4 filesystem? + foreach ($filesystemInfo as $filesystemMetric) { + if ($filesystemMetric->sys_type_name == 'ext4') { + echo $filesystemMetric->avail; + } + } + +Agent targets +============= + +Each agent check type gathers data for a related set of target devices +on the server where the agent is installed. For example, +``agent.network`` gathers data for network devices. The actual list of +target devices is specific to the configuration of the host server. By +focusing on specific targets, you can efficiently narrow the metric data +that the agent gathers. + +List agent targets +------------------ + +.. code-block:: php + + $targets = $service->getAgentTargets(); + + foreach ($targets as $target) { + echo $target->getType(); + } diff --git a/doc/services/monitoring/Alarms.md.rst b/doc/services/monitoring/alarms.rst similarity index 66% rename from doc/services/monitoring/Alarms.md.rst rename to doc/services/monitoring/alarms.rst index 2918637e9..297a57407 100644 --- a/doc/services/monitoring/Alarms.md.rst +++ b/doc/services/monitoring/alarms.rst @@ -1,9 +1,6 @@ Alarms ====== -Info ----- - Alarms bind alerting rules, entities, and notification plans into a logical unit. Alarms are responsible for determining a state (``OK``, ``WARNING`` or ``CRITICAL``) based on the result of a Check, and @@ -15,25 +12,39 @@ documentation getEntity('{entityId}'); + +and then a particular check, about which you can configure alarms: + +.. code-block:: php + + $check = $entity->getCheck('{checkId}'); + +For more information about these resource types, please consult the documentation +about `entities `_ and `checks `_. + +Retrieve alarm +-------------- -.. code:: php +.. code-block:: php - $alarmId = 'alAAAA'; - $alarm = $check->getAlarm(); + $alarm = $check->getAlarm('{alarmId}'); -For more information about working with Checks, please see the -`appropriate documentation `__. -Attributes ----------- +Once you have access to a ``OpenCloud\Monitoring\Resource\Alarm`` object, these +are the attributes you can access: +--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ | Name | Description | Required? | Method | +==========================+=============================================================================+=============+=================================+ -| check\_id | The ID of the check to alert on. | Required | ``getCheckId()`` | +| check_id | The ID of the check to alert on. | Required | ``getCheckId()`` | +--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ -| notification\_plan\_id | The ID of the notification plan to execute when the state changes. | Optional | ``getNotificationPlanId()`` | +| notification_plan_id | The ID of the notification plan to execute when the state changes. | Optional | ``getNotificationPlanId()`` | +--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ | criteria | The alarm DSL for describing alerting conditions and their output states. | Optional | ``getCriteria()`` | +--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ @@ -44,38 +55,45 @@ Attributes | metadata | Arbitrary key/value pairs. | Optional | ``getMetadata()`` | +--------------------------+-----------------------------------------------------------------------------+-------------+---------------------------------+ + Create Alarm ------------ -.. code:: php +.. code-block:: php + + $alarm = $check->getAlarm(); + $alarm->create(array( + 'check_id' => 'chAAAA', + 'criteria' => 'if (metric["duration"] >= 2) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);', + 'notification_plan_id' => 'npAAAAA' + )); - $alarm->create(array( - 'check_id' => 'chAAAA', - 'criteria' => 'if (metric["duration"] >= 2) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);', - 'notification_plan_id' => 'npAAAAA' - )); List Alarms ----------- -.. code:: php +.. code-block:: php - $alarms = $entity->getAlarms(); + $alarms = $entity->getAlarms(); - foreach ($alarms as $alarm) { - echo $alarm->getId(); - } + foreach ($alarms as $alarm) { + echo $alarm->getId(); + } -Update and delete Alarm ------------------------ -.. code:: php +Update Alarm +------------ + +.. code-block:: php - // Update - $alarm->update(array( - 'criteria' => 'if (metric["duration"] >= 5) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);' - )); + $alarm->update(array( + 'criteria' => 'if (metric["duration"] >= 5) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);' + )); + + +Delete alarm +------------ - // Delete - $alarm->delete(); +.. code-block:: php + $alarm->delete(); diff --git a/doc/services/monitoring/Changelogs.md.rst b/doc/services/monitoring/changelogs.rst similarity index 52% rename from doc/services/monitoring/Changelogs.md.rst rename to doc/services/monitoring/changelogs.rst index 2e9059e26..a6b26af25 100644 --- a/doc/services/monitoring/Changelogs.md.rst +++ b/doc/services/monitoring/changelogs.rst @@ -1,21 +1,18 @@ Changelogs ========== -Info ----- - The monitoring service records changelogs for alarm statuses. Changelogs are accessible as a Time Series Collection. By default the API queries the last 7 days of changelog information. -Working with Changelogs ------------------------ -.. code:: php +View Changelog +-------------- - $changelog = $service->getChangelog(); +.. code-block:: php - foreach ($changelog as $item) { - $entity = $item->getEntityId(); - } + $changelog = $service->getChangelog(); + foreach ($changelog as $item) { + $entity = $item->getEntityId(); + } diff --git a/doc/services/monitoring/Checks.md.rst b/doc/services/monitoring/checks.rst similarity index 80% rename from doc/services/monitoring/Checks.md.rst rename to doc/services/monitoring/checks.rst index 0e8e902a5..73474c170 100644 --- a/doc/services/monitoring/Checks.md.rst +++ b/doc/services/monitoring/checks.rst @@ -1,8 +1,6 @@ Checks ====== -Info ----- A check is one of the foundational building blocks of the monitoring system. The check determines the parts or pieces of the entity that you @@ -23,18 +21,31 @@ servers stops responding) or multiple alarms off of a single check. (e.g. ensure both that a HTTPS server is responding and that it has a valid certificate). -Setup ------ +Create a check +-------------- + +There are various attributes available to you when creating a new monitoring +check: -Checks are sub-resources of Entities: +.. code-block:: php -.. code:: php + $params = array( + 'type' => 'remote.http', + 'details' => array( + 'url' => 'http://example.com', + 'method' => 'GET' + ), + 'monitoring_zones_poll' => array('mzlon'), + 'period' => '100', + 'timeout' => '30', + 'target_alias' => 'default', + 'label' => 'Website check 1' + ); - $checkId = 'chAAAA'; - $check = $entity->getCheck($checkId); +For a full list of available attributes, consult the list below. Attributes ----------- +~~~~~~~~~~ +------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ | Name | Description | Required? | Data type | @@ -54,92 +65,90 @@ Attributes | timeout | The timeout in seconds for a check. This has to be less than the period. | Optional | Integer (2..1800) | +------------+-------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------+ -Attributes used for remote Checks -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Optional attributes to be used with remote checks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ | Name | Description | Required? | Data type | +===========================+========================================================================================================================================================+=============+============================================================+ -| monitoring\_zones\_poll | List of monitoring zones to poll from. Note: This argument is only required for remote (non-agent) checks | Optional | Array | +| monitoring_zones_poll | List of monitoring zones to poll from. Note: This argument is only required for remote (non-agent) checks | Optional | Array | +---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ -| target\_alias | A key in the entity's ``ip_addresses`` hash used to resolve this check to an IP address. This parameter is mutually exclusive with target\_hostname. | Optional | String (1..64 chars) | +| target_alias | A key in the entity's ``ip_addresses`` hash used to resolve this check to an IP address. This parameter is mutually exclusive with target\_hostname. | Optional | String (1..64 chars) | +---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ -| target\_hostname | The hostname this check should target. This parameter is mutually exclusive with ``target_alias``. | Optional | Valid FQDN, IPv4 or IPv6 address. String (1..256 chars). | +| target_hostname | The hostname this check should target. This parameter is mutually exclusive with ``target_alias``. | Optional | Valid FQDN, IPv4 or IPv6 address. String (1..256 chars). | +---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ -| target\_resolver | Determines how to resolve the check target. | Optional | ``IPv4`` or ``IPv6`` | +| target_resolver | Determines how to resolve the check target. | Optional | ``IPv4`` or ``IPv6`` | +---------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+------------------------------------------------------------+ -Test parameters (before create) -------------------------------- - -.. code:: php - - $params = array( - 'type' => 'remote.http', - 'details' => array( - 'url' => 'http://example.com', - 'method' => 'GET' - ), - 'monitoring_zones_poll' => array('mzlon'), - 'period' => '100', - 'timeout' => '30', - 'target_alias' => 'default', - 'label' => 'Website check 1' - ); - - // You can do a test to see what would happen - // if a Check is launched with these params - $response = $entity->testNewCheckParams($params); - - echo $response->timestamp; // When was it executed? - echo $response->available; // Was it available? - echo $response->status; // Status code - -Create a Check --------------- -.. code:: php +Test parameters +--------------- + +Sometimes it can be useful to test out the parameters before sending them as a +create call. To do this, pass in the ``$params`` like so: + +.. code-block:: php + + $response = $entity->testNewCheckParams($params); + + echo $response->timestamp; // When was it executed? + echo $response->available; // Was it available? + echo $response->status; // Status code + + +Send parameters +~~~~~~~~~~~~~~~ + +Once you are satisfied with your configuration parameters, you can complete the +operation and send it to the API like so: + +.. code-block:: php + + $entity->createCheck($params); - $entity->createCheck($params); Test existing Check ------------------- -.. code:: php +.. code-block:: php - // Set arg to TRUE for debug information - $response = $check->test(true); + // Set arg to TRUE for debug information + $response = $check->test(true); + + echo $response->debug_info; - echo $response->debug_info; List Checks ----------- -.. code:: php +.. code-block:: php + + $checks = $entity->getChecks(); - $checks = $entity->getChecks(); + foreach ($checks as $check) { + echo $check->getId(); + } - foreach ($checks as $check) { - echo $check->getId(); - } -Update and delete Check -~~~~~~~~~~~~~~~~~~~~~~~ +Update Check +------------ -.. code:: php +.. code-block:: php - // Update - $check->update(array('period' => 500)); + $check->update(array('period' => 500)); + + +Delete check +------------ + +.. code-block:: php + + $check->delete(); - // Delete - $check->delete(); Check types =========== -Info ----- - Each check within the Rackspace Cloud Monitoring has a designated check type. The check type instructs the monitoring system how to check the monitored resource. **Note:** Users cannot create, update or delete @@ -168,26 +177,46 @@ using the 'extract' attribute on the remote.http check, however the default metrics will always be present. To determine the exact metrics available, the Test Check API is provided. -Setup ------ +Find an existing check's type +----------------------------- + +If you want to see the type for an existing Check resource: + +.. code-block:: php + + /** @var \OpenCloud\CloudMonitoring\Resource\CheckType */ + $checkType = $check->getCheckType(); + + +List all possible check types +----------------------------- + +.. code-block:: php + + $checkTypes = $service->getCheckTypes(); -If you want to see the type for an existing Check: + foreach ($checkTypes as $checkType) { + echo $checkType->getId(); + } -.. code:: php - /** @var \OpenCloud\CloudMonitoring\Resource\CheckType */ - $checkType = $check->getCheckType(); +Retrieve details about a Type by its ID +--------------------------------------- Alternatively, you can retrieve a specific type based on its ID: -.. code:: php +.. code-block:: php + + $checkTypeId = 'remote.dns'; + $checkType = $service->getCheckType($checkTypeId); - $checkTypeId = 'remote.dns'; - $checkType = $service->getCheckType($checkTypeId); Attributes ---------- +Once you have access to a ``OpenCloud\CloudMonitoring\Resource\CheckType`` object, +you can query these attributes: + +------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ | Name | Description | Data type | Method | +========================+==========================================================================================================================================================================================+=============+===============================+ @@ -195,17 +224,5 @@ Attributes +------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ | fields | Check type fields. | Array | ``getFields()`` | +------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ -| supported\_platforms | Platforms on which an agent check type is supported. This is advisory information only - the check may still work on other platforms, or report that check execution failed at runtime | Array | ``getSupportedPlatforms()`` | +| supported_platforms | Platforms on which an agent check type is supported. This is advisory information only - the check may still work on other platforms, or report that check execution failed at runtime | Array | ``getSupportedPlatforms()`` | +------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------+-------------------------------+ - -List all possible check types ------------------------------ - -.. code:: php - - $checkTypes = $service->getCheckTypes(); - - foreach ($checkTypes as $checkType) { - echo $checkType->getId(); - } - diff --git a/doc/services/monitoring/entities.rst b/doc/services/monitoring/entities.rst new file mode 100644 index 000000000..7e4132af1 --- /dev/null +++ b/doc/services/monitoring/entities.rst @@ -0,0 +1,77 @@ + Entities +========= + +An entity is the target of what you are monitoring. For example, you can +create an entity to monitor your website, a particular web service, or +your Rackspace server. Note that an entity represents only one item in +the monitoring system -- if you wanted to monitor each server in a +cluster, you would create an entity for each of the servers. You would +not create a single entity to represent the entire cluster. + +An entity can have multiple checks associated with it. This allows you +to check multiple services on the same host by creating multiple checks +on the same entity, instead of multiple entities each with a single +check. + +Create Entity +------------- + +.. code-block:: php + + $service->createEntity(array( + 'label' => 'Brand New Entity', + 'ip_addresses' => array( + 'default' => '127.0.0.4', + 'b' => '127.0.0.5', + 'c' => '127.0.0.6', + 'test' => '127.0.0.7' + ), + 'metadata' => array( + 'all' => 'kinds', + 'of' => 'stuff', + 'can' => 'go', + 'here' => 'null is not a valid value' + ) + )); + + +Retrive an entity +----------------- + +.. code-block:: php + + $entity = $service->getEntity('{entityId}'); + + +Attributes +~~~~~~~~~~ + ++-----------------+-------------------------------------------------------------------------+-----------------------------------------------------+------------------------+ +| Name | Description | Data type | Method | ++=================+=========================================================================+=====================================================+========================+ +| label | Defines a name for the entity. | String (1..255 chars) | ``getLabel()`` | ++-----------------+-------------------------------------------------------------------------+-----------------------------------------------------+------------------------+ +| agent_id | Agent to which this entity is bound to. | String matching the regex: ``/^[-\.\w]{1,255}$/`` | ``getAgentId()`` | ++-----------------+-------------------------------------------------------------------------+-----------------------------------------------------+------------------------+ +| ip_addresses | Hash of IP addresses that can be referenced by checks on this entity. | Array | ``getIpAddresses()`` | ++-----------------+-------------------------------------------------------------------------+-----------------------------------------------------+------------------------+ +| metadata | Arbitrary key/value pairs that are passed during the alerting phase. | ``OpenCloud\Common\Metadata`` | ``getMetadata()`` | ++-----------------+-------------------------------------------------------------------------+-----------------------------------------------------+------------------------+ + + +Update an entity +---------------- + +.. code-block:: php + + $entity->update(array( + 'label' => 'New label for my entity' + )); + + +Delete entity +------------- + +.. code-block:: php + + $entity->delete(); diff --git a/doc/services/monitoring/index.rst b/doc/services/monitoring/index.rst index e69de29bb..df0597e8c 100644 --- a/doc/services/monitoring/index.rst +++ b/doc/services/monitoring/index.rst @@ -0,0 +1,34 @@ +Monitoring v1 +============= + +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now, set up the Cloud Monitoring service: + +.. code-block:: php + + $service = $client->monitoringService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + +Operations +---------- + +.. toctree:: + + entities + checks + alarms + agents + changelogs + metrics + notifications + views + zones + + +Glossary +-------- diff --git a/doc/services/monitoring/Metrics.md.rst b/doc/services/monitoring/metrics.rst similarity index 83% rename from doc/services/monitoring/Metrics.md.rst rename to doc/services/monitoring/metrics.rst index 4231cf914..0b412a6a3 100644 --- a/doc/services/monitoring/Metrics.md.rst +++ b/doc/services/monitoring/metrics.rst @@ -1,9 +1,6 @@  Metrics ======== -Info ----- - When Monitoring checks run, they generate metrics. These metrics are stored as full resolution data points in the Cloud Monitoring system. Full resolution data points are periodically rolled up (condensed) into @@ -13,6 +10,7 @@ Depending on your needs, you can use the metrics API to fetch individual data points (fine-grained) or rolled up data points (coarse-grained) over a period of time. + Data Granularity ---------------- @@ -42,7 +40,7 @@ elapsed since January 1, 1970** ). The following table shows the number of points that the API returns for a given resolution. Specifying resolution to retrieve data in 48 hour period -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-----------------------------+-------------------------+ | You specify resolution... | API returns points... | @@ -61,7 +59,7 @@ Specifying resolution to retrieve data in 48 hour period +-----------------------------+-------------------------+ Specifying number of points to retrieve data in 48 hour period -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +--------------------------------------+-----------------------------+ | You specify points in the range... | API calculates resolution | @@ -80,7 +78,7 @@ Specifying number of points to retrieve data in 48 hour period +--------------------------------------+-----------------------------+ Data Point Expiration -^^^^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~~~~ Cloud Monitoring expires data points according to the following schedule: @@ -101,31 +99,45 @@ schedule: | MIN1440 | 365 days | +--------------+--------------+ - Setup +Setup ------ -Metrics are sub-resources of Checks. For more information about working -with Checks, please see the `relevant documentation `__. +In order to interact with this feature, you must first retrieve an entity by +its ID: + +.. code-block:: php + + $entity = $service->getEntity('{entityId}'); + +and then a particular check, about which you can configure alarms: + +.. code-block:: php + + $check = $entity->getCheck('{checkId}'); + +For more information about these resource types, please consult the documentation +about `entities `_ and `checks `_. + List all metrics ---------------- -.. code:: php +.. code-block:: php - $metrics = $check->getMetrics(); + $metrics = $check->getMetrics(); + + foreach ($metrics as $metric) { + echo $metric->getName(); + } - foreach ($metrics as $metric) { - echo $metric->getName(); - } Fetch data points ----------------- -.. code:: php - - $data = $check->fetchDataPoints('mzdfw.available', array( - 'resolution' => 'FULL', - 'from' => 1369756378450, - 'to' => 1369760279018 - )); +.. code-block:: php + $data = $check->fetchDataPoints('mzdfw.available', array( + 'resolution' => 'FULL', + 'from' => 1369756378450, + 'to' => 1369760279018 + )); diff --git a/doc/services/monitoring/Notifications.md.rst b/doc/services/monitoring/notifications.rst similarity index 64% rename from doc/services/monitoring/Notifications.md.rst rename to doc/services/monitoring/notifications.rst index f361e3c9c..d7e289ad5 100644 --- a/doc/services/monitoring/Notifications.md.rst +++ b/doc/services/monitoring/notifications.rst @@ -1,9 +1,6 @@ Notifications ============= -Info ----- - A notification is a destination to send an alarm; it can be a variety of different types, and will evolve over time. @@ -11,16 +8,15 @@ For instance, with a webhook type notification, Cloud Monitoring posts JSON formatted data to a user-specified URL on an alert condition (Check goes from ``OK`` -> ``CRITICAL`` and so on). -Setup ------ +Get notification +---------------- -.. code:: php +.. code-block:: php - $id = 'ntAAAA'; - $notification = $service->getNotification($id); + $notification = $service->getNotification('{id}'); -Attributes ----------- +Once you have access to a ``OpenCloud\Monitoring\Resource\Notification`` object, +these are the attributes available for use: +-----------+---------------------------------------------------------------------------+-----------------------------------------------------------+--------------------+ | Name | Description | Data type | Method | @@ -32,76 +28,96 @@ Attributes | type | The notification type to send. | String. Either ``webhook``, ``email``, or ``pagerduty`` | ``getType()`` | +-----------+---------------------------------------------------------------------------+-----------------------------------------------------------+--------------------+ +Creating notifications +---------------------- + +The first thing to do when creating a new notification is configure the +parameters which will define the behaviour of your resource: + +.. code-block:: php + + $params = array( + 'label' => 'My webhook #1', + 'type' => 'webhook', + 'details' => array( + 'url' => 'http://example.com' + ) + ); + + Test parameters ---------------- +~~~~~~~~~~~~~~~ + +Once this is done, it is often useful to test them out to check whether they +will result in a successful creation: -.. code:: php +.. code-block:: php - $params = array( - 'label' => 'My webhook #1', - 'type' => 'webhook', - 'details' => array( - 'url' => 'http://example.com' - ) - ); + // Test it + $response = $notification->testParams($params); - // Test it - $response = $notification->testParams($params); + if ($response->status == 'Success') { + echo $response->message; + } - if ($response->status == 'Success') { - echo $response->message; - } -Create Notification -------------------- +Send parameters +~~~~~~~~~~~~~~~ -.. code:: php +When you're happy with the parameters you've defined, you can complete the +operation by sending them to the API like so: + +.. code-block:: php + + $notification->create($params); - $notification->create($params); Test existing notification -------------------------- -.. code:: php +.. code-block:: php + + $response = $notification->testExisting(true); + echo $response->debug_info; - $response = $notification->testExisting(true); - echo $response->debug_info; List Notifications ------------------ -.. code:: php +.. code-block:: php - $notifications = $service->getNotifications(); + $notifications = $service->getNotifications(); - foreach ($notifications as $notification) { - echo $notification->getId(); - } + foreach ($notifications as $notification) { + echo $notification->getId(); + } -Update and delete Notifications -------------------------------- -.. code:: php +Update a Notification +--------------------- - // Update - $notification->update(array( - 'label' => 'New notification label' - )); +.. code-block:: php + + $notification->update(array( + 'label' => 'New notification label' + )); + + +Delete a Notification +--------------------- + +.. code-block:: php + + $notification->delete(); - // Delete - $notification->delete(); Notification types ================== -Info ----- - -Pretty self-explanatory. Rackspace Cloud Monitoring currently supports -the following notification types: +Rackspace Cloud Monitoring currently supports the following notification types: Webhook -^^^^^^^ +~~~~~~~ Industry-standard web hooks, where JSON is posted to a configurable URL. It has these attributes: @@ -113,7 +129,7 @@ It has these attributes: +-----------+------------------------------------------+---------------+ Email -^^^^^ +~~~~~ Email alerts where the message is delivered to a specified address. It has these attributes: @@ -124,6 +140,7 @@ has these attributes: | url | An HTTP or HTTPS URL to POST to | Valid URL | +--------+-----------------------------------+-------------+ + Setup ----- @@ -131,34 +148,33 @@ If you've already set up a main Notification object, and want to access functionality for this Notification's particular Notification Type, you can access its property: -.. code:: php +.. code-block:: php - $type = $notification->getNotificationType(); + $type = $notification->getNotificationType(); Alternatively, you can retrieve an independent resource using the ID: -.. code:: php +.. code-block:: php + + $typeId = 'pagerduty'; + $type = $service->getNotificationType($typeId); - $typeId = 'pagerduty'; - $type = $service->getNotificationType($typeId); List all possible notification types ------------------------------------ -.. code:: php +.. code-block:: php + + $types = $service->getNotificationTypes(); - $types = $service->getNotificationTypes(); + foreach ($types as $type) { + echo sprintf('%s %s', $type->getName(), $type->getDescription()); + } - foreach ($types as $type) { - echo sprintf('%s %s', $type->getName(), $type->getDescription()); - } Notification plans ================== -Info ----- - A notification plan contains a set of notification actions that Rackspace Cloud Monitoring executes when triggered by an alarm. Rackspace Cloud Monitoring currently supports webhook and email @@ -180,60 +196,62 @@ A notification plan, ``npTechnicalContactsEmail``, is provided by default which will email all of the technical contacts on file for an account whenever there is a state change. -Setup ------ +Get a notification plan +----------------------- -.. code:: php +.. code-block:: php - $planId = 'npAAAA'; - $plan = $service->getNotificationPlan(); + $plan = $service->getNotificationPlan('{planId}'); -Attributes ----------- +Once you have access to a ``OpenCloud\\Monitoring\\Resource\\NotificationPlan`` +object, you can access these resources: +-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ | Name | Description | Required? | Data type | Method | +===================+====================================================================+=============+=========================+==========================+ | label | Friendly name for the notification plan. | Required | String (1..255 chars) | ``getLabel()`` | +-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ -| critical\_state | The notification list to send to when the state is ``CRITICAL``. | Optional | Array | ``getCriticalState()`` | +| critical_state | The notification list to send to when the state is ``CRITICAL``. | Optional | Array | ``getCriticalState()`` | +-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ -| ok\_state | The notification list to send to when the state is ``OK``. | Optional | Array | ``getOkState()`` | +| ok_state | The notification list to send to when the state is ``OK``. | Optional | Array | ``getOkState()`` | +-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ -| warning\_state | The notification list to send to when the state is ``WARNING``. | Optional | Array | ``getWarningState()`` | +| warning_state | The notification list to send to when the state is ``WARNING``. | Optional | Array | ``getWarningState()`` | +-------------------+--------------------------------------------------------------------+-------------+-------------------------+--------------------------+ Create Notification Plan ------------------------ -.. code:: php +.. code-block:: php + + $plan->create(array( + 'label' => 'New Notification Plan', + 'critical_state' => array('ntAAAA'), + 'ok_state' => array('ntBBBB'), + 'warning_state' => array('ntCCCC') + )); + + +Update notification plan +------------------------ + +.. code-block:: php - $plan->create(array( - 'label' => 'New Notification Plan', - 'critical_state' => array('ntAAAA'), - 'ok_state' => array('ntBBBB'), - 'warning_state' => array('ntCCCC') - )); + $plan->update(array( + 'label' => 'New label for my plan' + )); -Update and delete Notification Plan ------------------------------------ -.. code:: php +Delete notification plan +------------------------ + +.. code-block:: php - // Update - $plan->update(array( - 'label' => 'New label for my plan' - )); + $plan->delete(); - // Delete - $plan->delete(); Alarm Notification History ========================== -Info ----- - The monitoring service keeps a record of notifications sent for each alarm. This history is further subdivided by the check on which the notification occurred. Every attempt to send a notification is recorded, @@ -245,12 +263,31 @@ Alarm notification history is accessible as a Time Series Collection. By default alarm notification history is stored for 30 days and the API queries the last 7 days of information. - Setup +Setup ------ -Notification History is a sub-resource of an Alarm. For more information -about working with Alarms, please consult the relevant -`documentation `__. +In order to interact with this feature, you must first retrieve an entity by +its ID: + +.. code-block:: php + + $entity = $service->getEntity('{entityId}'); + +and then a particular check, about which you can configure alarms: + +.. code-block:: php + + $check = $entity->getCheck('{checkId}'); + +and finally, retrieve the alarm: + +.. code-block:: php + + $alarm = $check->getAlarm('{alarmId}'); + +For more information about these resource types, please consult the documentation +about `entities `_ and `checks `_. + Discover which Checks have a Notification History ------------------------------------------------- @@ -258,24 +295,25 @@ Discover which Checks have a Notification History This operation list checks for which alarm notification history is available: -.. code:: php +.. code-block:: php + + $checks = $alarm->getRecordedChecks(); - $checks = $alarm->getRecordedChecks(); List Alarm Notification History for a particular Check ------------------------------------------------------ -.. code:: php +.. code-block:: php + + $checkHistory = $alarm->getNotificationHistoryForCheck('chAAAA'); - $checkHistory = $alarm->getNotificationHistoryForCheck('chAAAA'); Get a particular Notification History item ------------------------------------------ -.. code:: php - - $checkId = 'chAAAA'; - $itemUuid = '646ac7b0-0b34-11e1-a0a1-0ff89fa2fa26'; +.. code-block:: php - $singleItem = $history->getNotificationHistoryItem($checkId, $itemUuid); + $checkId = 'chAAAA'; + $itemUuid = '646ac7b0-0b34-11e1-a0a1-0ff89fa2fa26'; + $singleItem = $history->getNotificationHistoryItem($checkId, $itemUuid); diff --git a/doc/services/monitoring/Views.md.rst b/doc/services/monitoring/views.rst similarity index 58% rename from doc/services/monitoring/Views.md.rst rename to doc/services/monitoring/views.rst index a5b7245fa..e83b97154 100644 --- a/doc/services/monitoring/Views.md.rst +++ b/doc/services/monitoring/views.rst @@ -1,27 +1,21 @@ Views ===== -Info ----- - Views contain a combination of data that usually includes multiple, different objects. The primary purpose of a view is to save API calls and make data retrieval more efficient. Instead of doing multiple API calls and then combining the result yourself, you can perform a single API call against the view endpoint. + List all Views -------------- -\`\`\`php $views = $service->getViews(); - -foreach ($views as $view) { $entity = $view->getEntity(); - -:: - - echo $view->getTimestamp(); +.. code-block:: php -} \`\`\` + $views = $service->getViews(); -Please consult the `iterator doc `__ for -more information about iterators. + foreach ($views as $view) { + $entity = $view->getEntity(); + echo $view->getTimestamp(); + } diff --git a/doc/services/monitoring/Zones.md.rst b/doc/services/monitoring/zones.rst similarity index 71% rename from doc/services/monitoring/Zones.md.rst rename to doc/services/monitoring/zones.rst index ffe4bba1e..bb588a303 100644 --- a/doc/services/monitoring/Zones.md.rst +++ b/doc/services/monitoring/zones.rst @@ -1,9 +1,6 @@ Zones ===== -Info ----- - A monitoring zone is a location that Rackspace Cloud Monitoring collects data from. Examples of monitoring zones are "US West", "DFW1" or "ORD1". It is an abstraction for a general location from which data is @@ -18,50 +15,43 @@ addresses or unrelated machines within that IP address range. A check references a list of monitoring zones it should be run from. - Setup ------- - -.. code:: php +Get details about a zone +------------------------ - $zoneId = 'mzAAAAA'; - $zone = $monitoringService->getMonitoringZone($zoneId); +.. code-block:: php -Attributes ----------- + $zone = $monitoringService->getMonitoringZone('{zoneId}'); +-----------------+------------------+-----------------------------------+------------------------+ | Name | Description | Data type | Method | +=================+==================+===================================+========================+ -| country\_code | Country Code | String longer than 2 characters | ``getCountryCode()`` | +| country_code | Country Code | String longer than 2 characters | ``getCountryCode()`` | +-----------------+------------------+-----------------------------------+------------------------+ | label | Label | String | ``getLabel()`` | +-----------------+------------------+-----------------------------------+------------------------+ -| source\_ips | Source IP list | Array | ``getSourceIps()`` | +| source_ips | Source IP list | Array | ``getSourceIps()`` | +-----------------+------------------+-----------------------------------+------------------------+  List all zones --------------- -.. code:: php +.. code-block:: php $zones = $service->getMonitoringZones(); -Please consult the `iterator doc `__ for -more information about iterators. Perform a traceroute -------------------- -.. code:: php - - $traceroute = $zone->traceroute(array( - 'target' => 'http://test.com', - 'target_resolver' => 'IPv4' - )); +.. code-block:: php - // How many hops? - echo count($traceroute); + $traceroute = $zone->traceroute(array( + 'target' => 'http://test.com', + 'target_resolver' => 'IPv4' + )); - // What was the first hop's IP? - echo $traceroute[0]->ip; + // How many hops? + echo count($traceroute); + // What was the first hop's IP? + echo $traceroute[0]->ip; From 7481ea1989c15b56b75263acf395300b8fe7b39d Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 15:29:41 +0100 Subject: [PATCH 129/181] Networking docs --- doc/services/networking/README.md.rst | 108 ----- doc/services/networking/USERGUIDE.md.rst | 582 ----------------------- doc/services/networking/index.rst | 50 ++ doc/services/networking/networks.rst | 128 +++++ doc/services/networking/ports.rst | 150 ++++++ doc/services/networking/subnets.rst | 152 ++++++ 6 files changed, 480 insertions(+), 690 deletions(-) delete mode 100644 doc/services/networking/README.md.rst delete mode 100644 doc/services/networking/USERGUIDE.md.rst create mode 100644 doc/services/networking/networks.rst create mode 100644 doc/services/networking/ports.rst create mode 100644 doc/services/networking/subnets.rst diff --git a/doc/services/networking/README.md.rst b/doc/services/networking/README.md.rst deleted file mode 100644 index 605805fe1..000000000 --- a/doc/services/networking/README.md.rst +++ /dev/null @@ -1,108 +0,0 @@ -Networking -========== - -**Networking** is a service that you can use to create virtual networks -and attach cloud devices such as servers to these networks. - -Concepts --------- - -Concepts --------- - -To use the Networking service effectively, you should understand the -following key concepts: - -- **Network**: A network is an isolated virtual layer-2 broadcast - domain that is typically reserved for the tenant who created it - unless you configure the network to be shared. The network is the - main entity in the Networking service. Ports and subnets are always - associated with a network. - -- **Subnet**: A subnet represents an IP address block that can be used - to assign IP addresses to virtual instances (such as servers created - using the Compute service). Each subnet must have a CIDR and must be - associated with a network. - -- **Port**: A port represents a virtual switch port on a logical - network switch. Virtual instances (such as servers created using the - Compute service) attach their interfaces into ports. The port also - defines the MAC address and the IP address(es) to be assigned to the - interfaces plugged into them. When IP addresses are associated to a - port, this also implies the port is associated with a subet, as the - IP address is taken from the allocation pool for a specific subnet. - -Getting started ---------------- - -1. Instantiate an OpenStack or Rackspace client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To use the Networking service, you must first instantiate a -``OpenStack`` or ``Rackspace`` client object. - -- If you are working with an OpenStack cloud, instantiate an - ``OpenCloud\OpenStack`` client as follows: - - .. code:: php - - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - -- If you are working with the Rackspace cloud, instantiate a - ``OpenCloud\Rackspace`` client as follows: - - .. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -2. Obtain an Networking service object from the client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -All Networking operations are done via an *networking service object*. -To instantiate this object, call the ``networkingService`` method on the -``$client`` object. This method takes two arguments: - -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ -| Position | Description | Data type | Required? | Default value | Example value | -+============+=============================================================+=============+=============+====================================================+=====================+ -| 1 | Name of the service, as it appears in the service catalog | String | No | ``null``; automatically determined when possible | ``cloudNetworks`` | -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ -| 2 | Cloud region | String | Yes | - | ``DFW`` | -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ - -.. code:: php - - $region = ''; - $networkingService = $client->networkingService(null, $region); - -Any networks, subnets, and ports created with this -``$networkingService`` instance will be stored in the cloud region -specified by ``$region``. - -3. Create a network. -~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $network = $networkingService->createNetwork(array( - 'name' => 'My private backend network' - )); - -[ `Get the executable PHP script for this -example `__ ] - -Next steps ----------- - -Once you have created a network, there is more you can do with it. See -`complete user guide for networking `__. diff --git a/doc/services/networking/USERGUIDE.md.rst b/doc/services/networking/USERGUIDE.md.rst deleted file mode 100644 index bfeb27774..000000000 --- a/doc/services/networking/USERGUIDE.md.rst +++ /dev/null @@ -1,582 +0,0 @@ -Complete User Guide for the Networking Service -============================================== - -Networking is a service that you can use to create virtual networks and -attach cloud devices such as servers to these networks. - -This user guide introduces you the entities in the Networking service — -networks, subnets, and ports — and shows you how to create and manage -these entities. - -Table of contents ------------------ - -- `Concepts <#concepts>`__ -- `Prerequisites <#prerequisites>`__ - - - `Client <#client>`__ - - `Networking service <#networking-service>`__ - -- `Networks <#networks>`__ - - - `Create a network <#create-a-network>`__ - - `Create multiple networks <#create-multiple-networks>`__ - - `List networks <#list-networks>`__ - - `Get a network <#get-a-network>`__ - - `Update a network <#update-a-network>`__ - - `Delete a network <#delete-a-network>`__ - -- `Subnets <#subnets>`__ - - - `Create a subnet <#create-a-subnet>`__ - - `Create multiple subnets <#create-multiple-subnets>`__ - - `List subnets <#list-subnets>`__ - - `Get a subnet <#get-a-subnet>`__ - - `Update a subnet <#update-a-subnet>`__ - - `Delete a subnet <#delete-a-subnet>`__ - -- `Ports <#ports>`__ - - - `Create a port <#create-a-port>`__ - - `Create multiple ports <#create-multiple-ports>`__ - - `List ports <#list-ports>`__ - - `Get a port <#get-a-port>`__ - - `Update a port <#update-a-port>`__ - - `Delete a port <#delete-a-port>`__ - -Concepts --------- - -To use the Networking service effectively, you should understand the -following key concepts: - -- **Network**: An isolated virtual layer-2 broadcast domain that is - typically reserved for the tenant who created it unless it is - configured to be shared. The network is the main entity in the - Networking service. Ports and subnets are always associated with a - network. - -- **Subnet**: An IP address block that can be used to assign IP - addresses to virtual instances (such as servers created using the - Compute service). Each subnet must have a CIDR and must be associated - with a network. - -- **Port**: A virtual switch port on a logical network switch. Virtual - instances (such as servers created using the Compute service) attach - their interfaces into ports. The port also defines the MAC address - and the IP address or addresses to be assigned to the interfaces - plugged into them. When IP addresses are associated with a port, this - also implies the port is associated with a subnet because the IP - address is taken from the allocation pool for a specific subnet. - -Prerequisites -------------- - -Client -~~~~~~ - -To use the Networking service, you must first instantiate a -``OpenStack`` or ``Rackspace`` client object. - -- If you are working with an OpenStack cloud, instantiate an - ``OpenCloud\OpenStack`` client as follows: - - .. code:: php - - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - -- If you are working with the Rackspace cloud, instantiate an - ``OpenCloud\Rackspace`` client as follows: - - .. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -Networking service -~~~~~~~~~~~~~~~~~~ - -All Networking operations are done via a *networking service object*. To -instantiate this object, call the ``networkingService`` method on the -``$client`` object. This method takes the following arguments: - -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ -| Position | Description | Data type | Required? | Default value | Example value | -+============+=============================================================+=============+=============+====================================================+=====================+ -| 1 | Name of the service, as it appears in the service catalog | String | No | ``null``; automatically determined when possible | ``cloudNetworks`` | -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ -| 2 | Cloud region | String | Yes | - | ``DFW`` | -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+---------------------+ - -.. code:: php - - $region = ''; - $networkingService = $client->networkingService(null, $region); - -Any networks, subnets, and ports created with this -``$networkingService`` instance are stored in the cloud region specified -by ``$region``. - -Networks --------- - -A network is an isolated virtual layer-2 broadcast domain that is -typically reserved for the tenant who created it unless it is configured -to be shared. The network is the main entity in the Networking service. -Ports and subnets are always associated with a network. - -Create a network -~~~~~~~~~~~~~~~~ - -This operation takes one parameter, an associative array, with the -following keys: - -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+====================+===================================================================================================+=============+=============+=======================================+==================================+ -| ``name`` | A human-readable name for the network. This name might not be unique. | String | No | ``null`` | ``My private backend network`` | -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ -| ``adminStateUp`` | The administrative state of network. If ``false`` (down), the network does not forward packets. | Boolean | No | ``true`` | ``true`` | -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ -| ``shared`` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | ``false`` | ``false`` | -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ -| ``tenantId`` | Owner of network. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the network | ``123456`` | -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ - -You can create a network as shown in the following example: - -.. code:: php - - $network = $networkingService->createNetwork(array( - 'name' => 'My private backend network' - )); - /** @var $network OpenCloud\Networking\Resource\Network **/ - -[ `Get the executable PHP script for this -example `__ ] - -Create multiple networks -~~~~~~~~~~~~~~~~~~~~~~~~ - -This operation takes one parameter, an indexed array. Each element of -this array must be an associative array with the keys shown in `the -preceding table <#create-a-network>`__. - -You can create multiple networks as shown in the following example: - -.. code:: php - - $networks = $networkingService->createNetworks(array( - array( - 'name' => 'My private backend network #1' - ), - array( - 'name' => 'My private backend network #2' - ) - )); - - foreach ($networks as $network) { - /** @var $network OpenCloud\Networking\Resource\Network **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -List networks -~~~~~~~~~~~~~ - -You can list all the networks to which you have access as shown in the -following example: - -.. code:: php - - $networks = $networkingService->listNetworks(); - foreach ($networks as $network) { - /** @var $network OpenCloud\Networking\Resource\Network **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Get a network -~~~~~~~~~~~~~ - -You can retrieve a specific network by using that network's ID, as shown -in the following example: - -.. code:: php - - $network = $networkingService->getNetwork('eb60583c-57ea-41b9-8d5c-8fab2d22224c'); - /** @var $network OpenCloud\Networking\Resource\Network **/ - -[ `Get the executable PHP script for this -example `__ ] - -Update a network -~~~~~~~~~~~~~~~~ - -This operation takes one parameter, an associative array, with the -following keys: - -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+====================+===================================================================================================+=============+=============+=================+==========================================+ -| ``name`` | A human-readable name for the network. This name might not be unique. | String | No | ``null`` | ``My updated private backend network`` | -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ -| ``adminStateUp`` | The administrative state of network. If ``false`` (down), the network does not forward packets. | Boolean | No | ``true`` | ``true`` | -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ -| ``shared`` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | ``false`` | ``false`` | -+--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ - -You can update a network as shown in the following example: - -.. code:: php - - $network->update(array( - 'name' => 'My updated private backend network' - )); - -[ `Get the executable PHP script for this -example `__ ] - -Delete a network -~~~~~~~~~~~~~~~~ - -You can delete a network as shown in the following example: - -.. code:: php - - $network->delete(); - -[ `Get the executable PHP script for this -example `__ ] - -Subnets -------- - -A subnet represents an IP address block that can be used to assign IP -addresses to virtual instances (such as servers created using the -Compute service). Each subnet must have a CIDR and must be associated -with a network. - -Create a subnet -~~~~~~~~~~~~~~~ - -This operation takes one parameter, an associative array, with the -following keys: - -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+=======================+===================================================================================================================+=======================================+=============+========================================================================+=================================================================================+ -| ``networkId`` | Network this subnet is associated with | String | Yes | - | ``eb60583c-57ea-41b9-8d5c-8fab2d22224c`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``ipVersion`` | IP version | Integer (``4`` or ``6``) | Yes | - | ``4`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``cidr`` | CIDR representing the IP address range for this subnet | String (CIDR) | Yes | - | ``192.168.199.0/25`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``name`` | A human-readable name for the subnet. This name might not be unique. | String | No | ``null`` | ``My subnet`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``gatewayIp`` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | ``192.168.199.128`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``dnsNameservers`` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | ``array('4.4.4.4', '8.8.8.8')`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``allocationPools`` | Subranges of the CIDR available for dynamic allocation to ports | Indexed array of associative arrays | No | Every IP address in CIDR, excluding gateway IP address if configured | ``array(array('start' => '192.168.199.2', 'end' => '192.168.199.127'))`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``hostRoutes`` | Routes that should be used by devices with IP addresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | ``array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.19.20'))`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``enableDhcp`` | Specifies whether DHCP is enabled for this subnet | Boolean | No | ``true`` | ``false`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ -| ``tenantId`` | Owner of the subnet. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the subnet | ``123456`` | -+-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ - -You can create a subnet as shown in the following example: - -.. code:: php - - $subnet = $networkingService->createSubnet(array( - 'name' => 'My subnet', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c', - 'ipVersion' => 4, - 'cidr' => '192.168.199.0/25' - )); - /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ - -[ `Get the executable PHP script for this -example `__ ] - -Create multiple subnets -~~~~~~~~~~~~~~~~~~~~~~~ - -This operation takes one parameter, an indexed array. Each element of -this array must be an associative array with the keys shown in `the -preceding table <#create-a-subnet>`__. - -You can create multiple subnets as shown in the following example: - -.. code:: php - - $subnets = $networkingService->createSubnets(array( - array( - 'name' => 'My subnet #1' - ), - array( - 'name' => 'My subnet #2' - ) - )); - - foreach ($subnets as $subnet) { - /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -List subnets -~~~~~~~~~~~~ - -You can list all the subnets to which you have access as shown in the -following example: - -.. code:: php - - $subnets = $networkingService->listSubnets(); - foreach ($subnets as $subnet) { - /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Get a subnet -~~~~~~~~~~~~ - -You can retrieve a specific subnet by using that subnet's ID, as shown -in the following example: - -.. code:: php - - $subnet = $networkingService->getSubnet('d3f15879-fb11-49bd-a30b-7704fb98ab1e'); - /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ - -[ `Get the executable PHP script for this -example `__ ] - -Update a subnet -~~~~~~~~~~~~~~~ - -This operation takes one parameter, an associative array, with the -following keys: - -+----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+======================+==================================================================================================================+=======================================+=============+============================+=================================================================================+ -| ``name`` | A human-readable name for the subnet. This name might not be unique. | String | No | ``null`` | ``My updated subnet`` | -+----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ -| ``gatewayIp`` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | ``192.168.62.155`` | -+----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ -| ``dnsNameservers`` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | ``array('4.4.4.4', '8.8.8.8')`` | -+----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ -| ``hostRoutes`` | Routes that should be used by devices with IP adresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | ``array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.17.19'))`` | -+----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ -| ``enableDhcp`` | Specifies whether DHCP is enabled for this subnet | Boolean | No | ``true`` | ``false`` | -+----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ - -You can update a subnet as shown in the following example: - -.. code:: php - - $subnet->update(array( - 'name' => 'My updated subnet', - 'hostRoutes' => array( - array( - 'destination' => '1.1.1.0/24', - 'nexthop' => '192.168.17.19' - ) - ), - 'gatewayIp' => '192.168.62.155' - )); - -[ `Get the executable PHP script for this -example `__ ] - -Delete a subnet -~~~~~~~~~~~~~~~ - -You can delete a subnet as shown in the following example: - -.. code:: php - - $subnet->delete(); - -[ `Get the executable PHP script for this -example `__ ] - -Ports ------ - -A port represents a virtual switch port on a logical network switch. -Virtual instances (such as servers created using the Compute service) -attach their interfaces into ports. The port also defines the MAC -address and the IP address or addresses to be assigned to the interfaces -plugged into them. When IP addresses are associated with a port, this -also implies the port is associated with a subnet because the IP address -is taken from the allocation pool for a specific subnet. - -Create a port -~~~~~~~~~~~~~ - -This operation takes one parameter, an associative array, with the -following keys: - -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+======================+=============================================================================================+============================================================+=============+=========================================+===========================================================================================================+ -| ``networkId`` | Network this port is associated with | String | Yes | - | ``eb60583c-57ea-41b9-8d5c-8fab2d22224c`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``name`` | A human-readable name for the port. This name might not be unique. | String | No | ``null`` | ``My port`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``adminStateUp`` | The administrative state of port. If ``false`` (down), the port does not forward packets. | Boolean | No | ``true`` | ``true`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``macAddress`` | MAC address to use on this port | String (MAC address in 6-octet form separated by colons) | No | Generated | ``0F:5A:6F:70:E9:5C`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``fixedIps`` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | ``array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.17'))`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``deviceId`` | Identifies the device (for example, virtual server) using this port | String | No | ``null`` | ``5e3898d7-11be-483e-9732-b2f5eccd2b2e`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``deviceOwner`` | Identifies the entity (for example, DHCP agent) using this port | String | No | ``null`` | ``network:router_interface`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``securityGroups`` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | ``array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``tenantId`` | Owner of the port. Only admin users can specify a tenant ID other than their own. | String | No | Same as the tenant creating the port | ``123456`` | -+----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ - -You can create a port as shown in the following example: - -.. code:: php - - $port = $networkingService->createPort(array( - 'name' => 'My port', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' - )); - /** @var $port OpenCloud\Networking\Resource\Port **/ - -[ `Get the executable PHP script for this -example `__ ] - -Create multiple ports -~~~~~~~~~~~~~~~~~~~~~ - -This operation takes one parameter, an indexed array. Each element of -this array must be an associative array with the keys shown in `the -preceding table <#create-a-port>`__. - -You can create multiple ports as shown in the following example: - -.. code:: php - - $ports = $networkingService->createPorts(array( - array( - 'name' => 'My port #1', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' - ), - array( - 'name' => 'My port #2', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' - ) - )); - - foreach ($ports as $port) { - /** @var $port OpenCloud\Networking\Resource\Port **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -List ports -~~~~~~~~~~ - -You can list all the ports to which you have access as shown in the -following example: - -.. code:: php - - $ports = $networkingService->listPorts(); - foreach ($ports as $port) { - /** @var $port OpenCloud\Networking\Resource\Port **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Get a port -~~~~~~~~~~ - -You can retrieve a specific port by using that port's ID, as shown in -the following example: - -.. code:: php - - $port = $networkingService->getPort('75906d20-6625-11e4-9803-0800200c9a66'); - /** @var $port OpenCloud\Networking\Resource\Port **/ - -[ `Get the executable PHP script for this -example `__ ] - -Update a port -~~~~~~~~~~~~~ - -This operation takes one parameter, an associative array, with the -following keys: - -+----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+======================+=============================================================================================+=======================================+=============+=========================================+===========================================================================================================+ -| ``name`` | A human-readable name for the port. This name might not be unique. | String | No | ``null`` | ``My port`` | -+----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``adminStateUp`` | The administrative state of port. If ``false`` (down), the port does not forward packets. | Boolean | No | ``true`` | ``true`` | -+----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``fixedIps`` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | ``array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.59'))`` | -+----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``deviceId`` | Identifies the device (for example, virtual server) using this port | String | No | ``null`` | ``5e3898d7-11be-483e-9732-b2f5eccd2b2e`` | -+----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``deviceOwner`` | Identifies the entity (for example, DHCP agent) using this port | String | No | ``null`` | ``network:router_interface`` | -+----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ -| ``securityGroups`` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | ``array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')`` | -+----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ - -You can update a port as shown in the following example: - -.. code:: php - - $port->update(array( - 'fixedIps' => array( - array( - 'subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', - 'ipAddress' => '192.168.199.59' - ) - ) - )); - -[ `Get the executable PHP script for this -example `__ ] - -Delete a port -~~~~~~~~~~~~~ - -You can delete a port as shown in the following example: - -.. code:: php - - $port->delete(); - -[ `Get the executable PHP script for this -example `__ ] diff --git a/doc/services/networking/index.rst b/doc/services/networking/index.rst index e69de29bb..92270fe86 100644 --- a/doc/services/networking/index.rst +++ b/doc/services/networking/index.rst @@ -0,0 +1,50 @@ +Networking v2 +============= + +Setup +----- + +.. include:: rs-client.sample.rst + +Now, set up the Cloud Monitoring service: + +.. code-block:: php + + $service = $client->networkingService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + +.. toctree:: + + networks + subnets + ports + +Glossary +-------- + +.. glossary:: + + network + A network is an isolated virtual layer-2 broadcast domain that is typically + reserved for the tenant who created it unless you configure the network to + be shared. The network is the main entity in the Networking service. Ports + and subnets are always associated with a network. + + subnet + A subnet represents an IP address block that can be used to assign IP + addresses to virtual instances (such as servers created using the Compute + service). Each subnet must have a CIDR and must be associated with a network. + + port + A port represents a virtual switch port on a logical network switch. + Virtual instances (such as servers created using the Compute service) + attach their interfaces into ports. The port also defines the MAC address + and the IP address(es) to be assigned to the interfaces plugged into them. + When IP addresses are associated to a port, this also implies the port is + associated with a subet, as the IP address is taken from the allocation + pool for a specific subnet. diff --git a/doc/services/networking/networks.rst b/doc/services/networking/networks.rst new file mode 100644 index 000000000..a290a34e7 --- /dev/null +++ b/doc/services/networking/networks.rst @@ -0,0 +1,128 @@ +Networks +======== + +Create a network +---------------- + +This operation takes one parameter, an associative array, with the +following keys: + ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++====================+===================================================================================================+=============+=============+=======================================+==================================+ +| ``name`` | A human-readable name for the network. This name might not be unique. | String | No | ``null`` | ``My private backend network`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| ``adminStateUp`` | The administrative state of network. If ``false`` (down), the network does not forward packets. | Boolean | No | ``true`` | ``true`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| ``shared`` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | ``false`` | ``false`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ +| ``tenantId`` | Owner of network. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the network | ``123456`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+---------------------------------------+----------------------------------+ + +You can create a network as shown in the following example: + +.. code-block:: php + + /** @var $network OpenCloud\Networking\Resource\Network **/ + $network = $networkingService->createNetwork(array( + 'name' => 'My private backend network' + )); + +`Get the executable PHP script for this example `__ + + +Create multiple networks +------------------------ + +This operation takes one parameter, an indexed array. Each element of +this array must be an associative array with the keys shown in `the +preceding table <#create-a-network>`__. + +You can create multiple networks as shown in the following example: + +.. code-block:: php + + $networks = $networkingService->createNetworks(array( + array( + 'name' => 'My private backend network #1' + ), + array( + 'name' => 'My private backend network #2' + ) + )); + + foreach ($networks as $network) { + /** @var $network OpenCloud\Networking\Resource\Network **/ + } + +`Get the executable PHP script for this example `_ + +List networks +------------- + +You can list all the networks to which you have access as shown in the +following example: + +.. code-block:: php + + $networks = $networkingService->listNetworks(); + + foreach ($networks as $network) { + /** @var $network OpenCloud\Networking\Resource\Network **/ + } + + +`Get the executable PHP script for this example `_ + + +Get a network +------------- + +You can retrieve a specific network by using that network's ID, as shown +in the following example: + +.. code-block:: php + + /** @var $network OpenCloud\Networking\Resource\Network **/ + $network = $networkingService->getNetwork('{networkId}'); + +`Get the executable PHP script for this example `_ + + +Update a network +---------------- + +This operation takes one parameter, an associative array, with the +following keys: + ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++====================+===================================================================================================+=============+=============+=================+==========================================+ +| ``name`` | A human-readable name for the network. This name might not be unique. | String | No | ``null`` | ``My updated private backend network`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ +| ``adminStateUp`` | The administrative state of network. If ``false`` (down), the network does not forward packets. | Boolean | No | ``true`` | ``true`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ +| ``shared`` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | ``false`` | ``false`` | ++--------------------+---------------------------------------------------------------------------------------------------+-------------+-------------+-----------------+------------------------------------------+ + +You can update a network as shown in the following example: + +.. code-block:: php + + $network->update(array( + 'name' => 'My updated private backend network' + )); + +`Get the executable PHP script for this example `_ + + +Delete a network +~~~~~~~~~~~~~~~~ + +You can delete a network as shown in the following example: + +.. code-block:: php + + $network->delete(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/networking/ports.rst b/doc/services/networking/ports.rst new file mode 100644 index 000000000..06d2ec2cf --- /dev/null +++ b/doc/services/networking/ports.rst @@ -0,0 +1,150 @@ +Ports +===== + +Create a port +------------- + +This operation takes one parameter, an associative array, with the following keys: + ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++======================+=============================================================================================+============================================================+=============+=========================================+===========================================================================================================+ +| ``networkId`` | Network this port is associated with | String | Yes | - | ``eb60583c-57ea-41b9-8d5c-8fab2d22224c`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``name`` | A human-readable name for the port. This name might not be unique. | String | No | ``null`` | ``My port`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``adminStateUp`` | The administrative state of port. If ``false`` (down), the port does not forward packets. | Boolean | No | ``true`` | ``true`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``macAddress`` | MAC address to use on this port | String (MAC address in 6-octet form separated by colons) | No | Generated | ``0F:5A:6F:70:E9:5C`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``fixedIps`` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | ``array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.17'))`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceId`` | Identifies the device (for example, virtual server) using this port | String | No | ``null`` | ``5e3898d7-11be-483e-9732-b2f5eccd2b2e`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceOwner`` | Identifies the entity (for example, DHCP agent) using this port | String | No | ``null`` | ``network:router_interface`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``securityGroups`` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | ``array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``tenantId`` | Owner of the port. Only admin users can specify a tenant ID other than their own. | String | No | Same as the tenant creating the port | ``123456`` | ++----------------------+---------------------------------------------------------------------------------------------+------------------------------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ + +You can create a port as shown in the following example: + +.. code-block:: php + + /** @var $port OpenCloud\Networking\Resource\Port **/ + $port = $networkingService->createPort(array( + 'name' => 'My port', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' + )); + + +`Get the executable PHP script for this example `_ + + +Create multiple ports +--------------------- + +This operation takes one parameter, an indexed array. Each element of +this array must be an associative array with the keys shown in `the +preceding table <#create-a-port>`__. + +You can create multiple ports as shown in the following example: + +.. code-block:: php + + $ports = $networkingService->createPorts(array( + array( + 'name' => 'My port #1', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' + ), + array( + 'name' => 'My port #2', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' + ) + )); + + foreach ($ports as $port) { + /** @var $port OpenCloud\Networking\Resource\Port **/ + } + +`Get the executable PHP script for this example `_ + + +List ports +---------- + +You can list all the ports to which you have access as shown in the following example: + +.. code-block:: php + + $ports = $networkingService->listPorts(); + + foreach ($ports as $port) { + /** @var $port OpenCloud\Networking\Resource\Port **/ + } + +`Get the executable PHP script for this example `_ + + +Get a port +---------- + +You can retrieve a specific port by using that port's ID, as shown in +the following example: + +.. code-block:: php + + /** @var $port OpenCloud\Networking\Resource\Port **/ + $port = $networkingService->getPort('{portId}'); + +`Get the executable PHP script for this example `_ + + +Update a port +------------- + +This operation takes one parameter, an associative array, with the following keys: + ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++======================+=============================================================================================+=======================================+=============+=========================================+===========================================================================================================+ +| ``name`` | A human-readable name for the port. This name might not be unique. | String | No | ``null`` | ``My port`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``adminStateUp`` | The administrative state of port. If ``false`` (down), the port does not forward packets. | Boolean | No | ``true`` | ``true`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``fixedIps`` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | ``array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.59'))`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceId`` | Identifies the device (for example, virtual server) using this port | String | No | ``null`` | ``5e3898d7-11be-483e-9732-b2f5eccd2b2e`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``deviceOwner`` | Identifies the entity (for example, DHCP agent) using this port | String | No | ``null`` | ``network:router_interface`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ +| ``securityGroups`` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | ``array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')`` | ++----------------------+---------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------------------------------+-----------------------------------------------------------------------------------------------------------+ + +You can update a port as shown in the following example: + +.. code-block:: php + + $port->update(array( + 'fixedIps' => array( + array( + 'subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', + 'ipAddress' => '192.168.199.59' + ) + ) + )); + +`Get the executable PHP script for this example `_ + + +Delete a port +------------- + +You can delete a port as shown in the following example: + +.. code-block:: php + + $port->delete(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/networking/subnets.rst b/doc/services/networking/subnets.rst new file mode 100644 index 000000000..e8d6951a0 --- /dev/null +++ b/doc/services/networking/subnets.rst @@ -0,0 +1,152 @@ +Subnets +======= + +Create a subnet +--------------- + +This operation takes one parameter, an associative array, with the following keys: + ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++=======================+===================================================================================================================+=======================================+=============+========================================================================+=================================================================================+ +| ``networkId`` | Network this subnet is associated with | String | Yes | - | ``eb60583c-57ea-41b9-8d5c-8fab2d22224c`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``ipVersion`` | IP version | Integer (``4`` or ``6``) | Yes | - | ``4`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``cidr`` | CIDR representing the IP address range for this subnet | String (CIDR) | Yes | - | ``192.168.199.0/25`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``name`` | A human-readable name for the subnet. This name might not be unique. | String | No | ``null`` | ``My subnet`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``gatewayIp`` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | ``192.168.199.128`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``dnsNameservers`` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | ``array('4.4.4.4', '8.8.8.8')`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``allocationPools`` | Subranges of the CIDR available for dynamic allocation to ports | Indexed array of associative arrays | No | Every IP address in CIDR, excluding gateway IP address if configured | ``array(array('start' => '192.168.199.2', 'end' => '192.168.199.127'))`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``hostRoutes`` | Routes that should be used by devices with IP addresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | ``array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.19.20'))`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``enableDhcp`` | Specifies whether DHCP is enabled for this subnet | Boolean | No | ``true`` | ``false`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ +| ``tenantId`` | Owner of the subnet. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the subnet | ``123456`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+------------------------------------------------------------------------+---------------------------------------------------------------------------------+ + +You can create a subnet as shown in the following example: + +.. code-block:: php + + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + $subnet = $networkingService->createSubnet(array( + 'name' => 'My subnet', + 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c', + 'ipVersion' => 4, + 'cidr' => '192.168.199.0/25' + )); + +`Get the executable PHP script for this example `_ + + +Create multiple subnets +----------------------- + +This operation takes one parameter, an indexed array. Each element of +this array must be an associative array with the keys shown in `the +preceding table <#create-a-subnet>`__. + +You can create multiple subnets as shown in the following example: + +.. code-block:: php + + $subnets = $networkingService->createSubnets(array( + array( + 'name' => 'My subnet #1' + ), + array( + 'name' => 'My subnet #2' + ) + )); + + foreach ($subnets as $subnet) { + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + } + +`Get the executable PHP script for this example `_ + + +List subnets +------------ + +You can list all the subnets to which you have access as shown in the +following example: + +.. code-block:: php + + $subnets = $networkingService->listSubnets(); + foreach ($subnets as $subnet) { + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + } + +`Get the executable PHP script for this example `_ + + +Get a subnet +------------ + +You can retrieve a specific subnet by using that subnet's ID, as shown +in the following example: + +.. code-block:: php + + /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ + $subnet = $networkingService->getSubnet('{subnetId}'); + +`Get the executable PHP script for this example `_ + + +Update a subnet +--------------- + +This operation takes one parameter, an associative array, with the +following keys: + ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++======================+==================================================================================================================+=======================================+=============+============================+=================================================================================+ +| ``name`` | A human-readable name for the subnet. This name might not be unique. | String | No | ``null`` | ``My updated subnet`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``gatewayIp`` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | ``192.168.62.155`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``dnsNameservers`` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | ``array('4.4.4.4', '8.8.8.8')`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``hostRoutes`` | Routes that should be used by devices with IP adresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | ``array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.17.19'))`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ +| ``enableDhcp`` | Specifies whether DHCP is enabled for this subnet | Boolean | No | ``true`` | ``false`` | ++----------------------+------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+----------------------------+---------------------------------------------------------------------------------+ + +You can update a subnet as shown in the following example: + +.. code-block:: php + + $subnet->update(array( + 'name' => 'My updated subnet', + 'hostRoutes' => array( + array( + 'destination' => '1.1.1.0/24', + 'nexthop' => '192.168.17.19' + ) + ), + 'gatewayIp' => '192.168.62.155' + )); + +`Get the executable PHP script for this example `_ + + +Delete a subnet +--------------- + +You can delete a subnet as shown in the following example: + +.. code-block:: php + + $subnet->delete(); + +`Get the executable PHP script for this example `_ From 1bd1c2a21c1261b472eabfc9fd304f2917db2d40 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 15:29:50 +0100 Subject: [PATCH 130/181] Object Store docs --- doc/services/object-store/Account.md.rst | 33 - .../object-store/Container.md.cdn.rst | 90 -- doc/services/object-store/Object.md.cdn.rst | 25 - .../object-store/Object.md.storage.rst | 330 ------- doc/services/object-store/README.md.rst | 86 -- doc/services/object-store/USERGUIDE.md.rst | 900 ------------------ .../{Access.md.rst => access.rst} | 69 +- doc/services/object-store/account.rst | 46 + doc/services/object-store/cdn.rst | 124 +++ ...ontainer.md.storage.rst => containers.rst} | 193 ++-- doc/services/object-store/index.rst | 57 ++ ...d.storage.rst => migrating-containers.rst} | 64 +- doc/services/object-store/objects.rst | 427 +++++++++ doc/services/object-store/rs-only.rst | 3 + 14 files changed, 834 insertions(+), 1613 deletions(-) delete mode 100644 doc/services/object-store/Account.md.rst delete mode 100644 doc/services/object-store/Container.md.cdn.rst delete mode 100644 doc/services/object-store/Object.md.cdn.rst delete mode 100644 doc/services/object-store/Object.md.storage.rst delete mode 100644 doc/services/object-store/README.md.rst delete mode 100644 doc/services/object-store/USERGUIDE.md.rst rename doc/services/object-store/{Access.md.rst => access.rst} (52%) create mode 100644 doc/services/object-store/account.rst create mode 100644 doc/services/object-store/cdn.rst rename doc/services/object-store/{Container.md.storage.rst => containers.rst} (53%) rename doc/services/object-store/{Migrating.md.storage.rst => migrating-containers.rst} (82%) create mode 100644 doc/services/object-store/objects.rst create mode 100644 doc/services/object-store/rs-only.rst diff --git a/doc/services/object-store/Account.md.rst b/doc/services/object-store/Account.md.rst deleted file mode 100644 index a2d380b2a..000000000 --- a/doc/services/object-store/Account.md.rst +++ /dev/null @@ -1,33 +0,0 @@ -Setup ------ - -.. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(RACKSPACE_US, array( - - )); - - $service = $client->objectStoreService('cloudFiles'); - -View Account Details --------------------- - -To see how many containers you have in your account -(X-Account-Container-Count), how many objects are in your account -(X-Account-Object-Count), and how many total bytes your account uses -(X-Account-Bytes-Used): - -.. code:: php - - $account = $service->getAccount(); - - // Either return the full Metadata object - $details = $account->getDetails(); - - // or individual values - $account->getContainerCount(); - $account->getObjectCount(); - $account->getBytesUsed(); - diff --git a/doc/services/object-store/Container.md.cdn.rst b/doc/services/object-store/Container.md.cdn.rst deleted file mode 100644 index 2f1c8ea68..000000000 --- a/doc/services/object-store/Container.md.cdn.rst +++ /dev/null @@ -1,90 +0,0 @@ -Setup ------ - -.. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(RACKSPACE_US, array( - - )); - - $service = $client->objectStoreService('cloudFiles'); - -To access the CDN functionality of a particular container: - -.. code:: php - - $container = $service->getContainer('foo_bar'); - - $cdn = $container->getCdn(); - -List CDN-enabled container --------------------------- - -To list CDN-only containers, follow the same operation for Storage which -lists all containers. The only difference is which service object you -execute the method on: - -.. code:: php - - $cdnService = $service->getCdnService(); - $cdnContainers = $cdnService->listContainers(); - - foreach ($cdnContainers as $cdnContainer) { - - } - -CDN-enable and -disable a container ------------------------------------ - -Before a container can be CDN-enabled, it must exist in the storage -system. When a container is CDN-enabled, any objects stored in it are -publicly accessible over the Content Delivery Network by combining the -container's CDN URL with the object name. - -Any CDN-accessed objects are cached in the CDN for the specified amount -of time called the TTL. The default TTL value is 259200 seconds, or 72 -hours. Each time the object is accessed after the TTL expires, the CDN -refetches and caches the object for the TTL period. - -.. code:: php - - $container->enableCdn(); - $container->disableCdn(); - -Serving containers through SSL ------------------------------- - -.. code:: php - - $cdn->getCdnSslUri(); - -Streaming CDN-enabled containers --------------------------------- - -.. code:: php - - $cdn->getCdnStreamingUri(); - -iOS streaming -------------- - -The Cloud Files CDN allows you to stream video to iOS devices without -needing to convert your video. Once you CDN-enable your container, you -have the tools necessary for streaming media to multiple devices. - -.. code:: php - - $cdn->getIosStreamingUri(); - -CDN logging ------------ - -To enable and disable logging for your CDN: - -.. code:: php - - $cdn->enableCdnLogging(); - $cdn->disableCdnLogging(); - diff --git a/doc/services/object-store/Object.md.cdn.rst b/doc/services/object-store/Object.md.cdn.rst deleted file mode 100644 index 64ac143b3..000000000 --- a/doc/services/object-store/Object.md.cdn.rst +++ /dev/null @@ -1,25 +0,0 @@ -Setup ------ - -You will need to instantiate the container object and access its CDN -functionality as `documented -here `__. - -Purge CDN-enabled objects -------------------------- - -To remove a CDN object from public access: - -.. code:: php - - $object->purge(); - -You can also provide an optional e-mail address (or comma-delimeted list -of e-mails), which the API will send a confirmation message to once the -object has been completely purged: - -.. code:: php - - $object->purge('jamie.hannaford@rackspace.com'); - $object->purge('hello@example.com,hallo@example.com'); - diff --git a/doc/services/object-store/Object.md.storage.rst b/doc/services/object-store/Object.md.storage.rst deleted file mode 100644 index 16dab18f4..000000000 --- a/doc/services/object-store/Object.md.storage.rst +++ /dev/null @@ -1,330 +0,0 @@ -Setup ------ - -Conceptually, a container contains objects (also known as files). In -order to work with objects, you will need to instantiate a container -object first as `documented -here `__. - -Note on object properties -------------------------- - -Please be aware that you cannot directly access the properties of -DataObject anymore, you **must** use appropriate getter/ setter methods: - -+----------------------+------------------------+ -| Property | Method | -+======================+========================+ -| Parent container | ``getContainer`` | -+----------------------+------------------------+ -| Name | ``getName`` | -+----------------------+------------------------+ -| Body of file | ``getContent`` | -+----------------------+------------------------+ -| Size of file | ``getContentLength`` | -+----------------------+------------------------+ -| Type of file | ``getContentType`` | -+----------------------+------------------------+ -| ETag checksum | ``getEtag`` | -+----------------------+------------------------+ -| Last modified date | ``getLastModified`` | -+----------------------+------------------------+ - -Create an object ----------------- - -There are three ways to upload a new file, each of which has different -business needs. - - **Note:** Unlike previous versions, you do not need to manually - specify your object's content type. The API will do this for you. - - **Note:** when working with names that contain non-standard - alphanumerical characters (such as spaces or non-English - characters), you must ensure they are encoded with - ```urlencode`` `__ before passing them in - -To upload a single/basic file: -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - use OpenCloud\ObjectStore\Resource\DataObject; - - $data = fopen('/path/to/sample.mp3', 'r+'); - - // alternatively, you can pass in a string as the file contents `$data` argument (instead of a resource) - - $meta = array( - 'Author' => 'Camera Obscura', - 'Origin' => 'Glasgow' - ); - - $metaHeaders = DataObject::stockHeaders($meta); - $customHeaders = array(); - $allHeaders = $metaHeaders + $customHeaders; - - $container->uploadObject('sample.mp3', $data, $allHeaders); - -To upload multiple small-to-mid sized files: -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $files = array( - array( - 'name' => 'apache.log', - 'path' => '/etc/httpd/logs/error_log' - ), - array( - 'name' => 'mysql.log', - 'body' => fopen('/tmp/mysql.log', 'r+') - ), - array( - 'name' => 'to_do_list.txt', - 'body' => 'PHONE HOME' - ) - ); - - $container->uploadObjects($files); - -As you can see, the ``name`` key is required for every file. You must -also specify *either* a path key (to an existing file), or a ``body``. -The ``body`` can either be a PHP resource or a string representation of -the content you want to upload. - -To upload large files -~~~~~~~~~~~~~~~~~~~~~ - -For files over 5GB, you will need to use the -``OpenCloud\ObjectStore\Upload\TransferBuilder`` factory to build your -transfer, upon which you can execute your upload functionality. For your -convenience, the Container resource object contains a simple method to -do this heavy lifting for you: - -.. code:: php - - $transfer = $container->setupObjectTransfer(array( - 'name' => 'video.mov', - 'path' => '/home/jamie/video.mov', - 'metadata' => array( - 'Author' => 'Jamie' - ), - 'concurrency' => 4, - 'partSize' => 1.5 * Size::GB - )); - - $transfer->upload(); - -You can specify how many concurrent cURL connections are used to upload -parts of your file. The file is fragmented into chunks, each of which is -uploaded individually as a separate file (the filename of each part will -indicate that it's a segment rather than the full file). After all parts -are uploaded, a manifest is uploaded. When the end-user accesses the 5GB -by its true filename, it actually references the manifest file which -concatenates each segment into a streaming download. - -List objects in a container ---------------------------- - -To return a list of objects: - -.. code:: php - - $files = $container->objectList(); - - foreach ($files as $file) { - // ... do something - } - -By default, 10,000 objects are returned as a maximum. To get around -this, you can construct a query which refines your result set. For a -full specification of query parameters relating to collection filtering, -see the `official -docs `__. - -.. code:: php - - $container->objectList(array('prefix' => 'logFile_')); - -Get object ----------- - -To retrieve a specific file from Cloud Files: - -.. code:: php - - $file = $container->getObject('summer_vacation.mp4'); - -Conditional requests -~~~~~~~~~~~~~~~~~~~~ - -You can also perform conditional requests according to `RFC 2616 -specification `__ (§§ 14.24-26). -Supported headers are ``If-Match``, ``If-None-Match``, -``If-Modified-Since`` and ``If-Unmodified-Since``. - -So, to retrieve a file's contents only if it's been recently changed - -.. code:: php - - $file = $container->getObject('error_log.txt', array( - 'If-Modified-Since' => 'Tue, 15 Nov 1994 08:12:31 GMT' - )); - - if ($file->getContentLength()) { - echo 'Has been changed since the above date'; - } else { - echo 'Has not been changed'; - } - -Retrieve a file only if it has NOT been modified (and expect a 412 on -failure): - -:: - - use Guzzle\Http\Exception\ClientErrorResponseException; - - try { - $oldImmutableFile = $container->getObject('payroll_2001.xlsx', array( - 'If-Unmodified-Since' => 'Mon, 31 Dec 2001 23:00:00 GMT' - )); - } catch (ClientErrorResponseException $e) { - echo 'This file has been modified...'; - } - -Finally, you can specify a range - which will return a subset of bytes -from the file specified. To return the last 20B of a file: - -.. code:: php - - $snippet = $container->getObject('output.log', array('range' => 'bytes=-20')); - -Update an existing object -------------------------- - -Updating content is easy: - -.. code:: php - - $file->setContent(fopen('/path/to/new/content', 'r+')); - $file->update(); - -Bear in mind that updating a file name will result in a new file being -generated (under the new name). You will need to delete the old file. - -Copy object ------------ - -To copy a file to another location, you need to specify a string-based -destination path: - -.. code:: php - - $object->copy('/container_2/new_object_name'); - -Delete object -------------- - -.. code:: php - - $object->delete(); - -Get object metadata -------------------- - -You can fetch just the object metadata without fetching the full -content: - -.. code:: php - - $container->getPartialObject('summer_vacation.mp4'); - -In order to access the metadata on a partial or complete object, use: - -.. code:: php - - $object->getMetadata(); - -You can turn a partial object into a full object to get the content -after looking at the metadata: - -.. code:: php - - $object->refresh(); - -You can also update to get the latest metadata: - -.. code:: php - - $object->retrieveMetadata(); - -Update object metadata ----------------------- - -Similarly, with setting metadata there are two options: you can update -the metadata values of the local object (i.e. no HTTP request) if you -anticipate you'll be executing one soon (an update operation for -example): - -.. code:: php - - // There's no need to execute a HTTP request, because we'll soon do one anyway for the update operation - $object->setMetadata(array( - 'Author' => 'Hemingway' - )); - - // ... code here - - $object->update(); - -Alternatively, you can update the API straight away - so that everything -is retained: - -.. code:: php - - $object->saveMetadata(array( - 'Author' => 'Hemingway' - )); - -Please be aware that these methods override and wipe existing values. If -you want to append values to your metadata, use the correct method: - -.. code:: php - - $metadata = $object->appendToMetadata(array( - 'Author' => 'Hemingway' - )); - - $object->saveMetadata($metadata); - -Extract archive ---------------- - -CloudFiles provides you the ability to extract uploaded archives to -particular destinations. The archive will be extracted and its contents -will populate the particular area specified. To upload file (which might -represent a directory structure) into a particular container: - -.. code:: php - - use OpenCloud\ObjectStore\Constants\UrlType; - - $service->bulkExtract('container_1', fopen('/home/jamie/files.tar.gz','r'), UrlType::TAR_GZ); - -You can also omit the container name (i.e. provide an empty string as -the first argument). If you do this, the API will create the containers -necessary to house the extracted files - this is done based on the -filenames inside the archive. - -Bulk delete ------------ - -Bulk delete a set of paths: - -.. code:: php - - $pathsToBeDeleted = array('/container_1/old_file', '/container_2/notes.txt', '/container_1/older_file.log'); - - $service->bulkDelete($pathsToBeDeleted); - diff --git a/doc/services/object-store/README.md.rst b/doc/services/object-store/README.md.rst deleted file mode 100644 index 01cf26733..000000000 --- a/doc/services/object-store/README.md.rst +++ /dev/null @@ -1,86 +0,0 @@ -Object Store -============ - -**Object Store** is an object-based storage system that stores content -and metadata as objects in a cloud. - -Specifically, a cloud is made up of one or more regions. Each region can -have several **containers**, created by a user. Each container can -container several **objects** (sometimes referred to as files), uploaded -by the user. - -Getting started ---------------- - -1. Instantiate an OpenStack or Rackspace client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Choose one of the following two options: - -- If you are working with a vanilla OpenStack cloud, instantiate an - ``OpenCloud\OpenStack`` client as shown below. - - .. code:: php - - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - -- If you are working with the Rackspace cloud, instantiate a - ``OpenCloud\Rackspace`` client as shown below. - - .. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -2. Obtain an Object Store service object from the client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $region = 'DFW'; - $objectStoreService = $client->objectStoreService(null, $region); - -In the example above, you are connecting to the ``DFW`` region of the -cloud. Any containers and objects created with this -``$objectStoreService`` instance will be stored in that cloud region. - -3. Create a container for your objects (also referred to as files). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $container = $objectStoreService->createContainer('logos'); - - **Note:** when working with names that contain non-standard - alphanumerical characters (such as spaces or non-English - characters), you must ensure they are encoded with - ```urlencode`` `__ before passing them in - -4. Upload an object to the container. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $localFileName = '/path/to/local/php-elephant.jpg'; - $remoteFileName = 'php-elephant.jpg'; - - $fileData = fopen($localFileName, 'r'); - $container->uploadObject($remoteFileName, $fileData); - -[ `Get the executable PHP script for this -example `__ ] - -Next steps ----------- - -There is a lot more you can do with containers and objects. See the -`complete user guide to the Object Store service `__. diff --git a/doc/services/object-store/USERGUIDE.md.rst b/doc/services/object-store/USERGUIDE.md.rst deleted file mode 100644 index d9732ea36..000000000 --- a/doc/services/object-store/USERGUIDE.md.rst +++ /dev/null @@ -1,900 +0,0 @@ -The Complete User Guide to the Object Store Service -=================================================== - -**Object Store** is an object-based storage system that stores content -and metadata as objects in a cloud. - -Prerequisites -------------- - -Client -~~~~~~ - -To use the object store service, you must first instantiate a -``OpenStack`` or ``Rackspace`` client object. - -- If you are working with a vanilla OpenStack cloud, instantiate an - ``OpenCloud\OpenStack`` client as shown below. - - .. code:: php - - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'apiKey' => '' - )); - -- If you are working with the Rackspace cloud, instantiate a - ``OpenCloud\Rackspace`` client as shown below. - - .. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -Object Store Service -~~~~~~~~~~~~~~~~~~~~ - -All operations on the object store are done via an object store service -object. - -.. code:: php - - $region = 'DFW'; - $objectStoreService = $client->objectStoreService(null, $region); - -In the example above, you are connecting to the ``DFW`` region of the -cloud. Any containers and objects created with this -``$objectStoreService`` instance will be stored in that cloud region. - -Containers ----------- - -A **container** defines a namespace for **objects**. An object with the -same name in two different containers represents two different objects. - -For example, you may create a container called ``logos`` to hold all the -image files for your blog. - -A container may contain zero or more objects in it. - - **Note:** when working with names that contain non-standard - alphanumerical characters (such as spaces or non-English - characters), you must ensure they are encoded with - ```urlencode`` `__ before passing them in - -Create Container -~~~~~~~~~~~~~~~~ - -.. code:: php - - $container = $objectStoreService->createContainer('logos'); - -[ `Get the executable PHP script for this -example `__ ] - -Get Container Details -~~~~~~~~~~~~~~~~~~~~~ - -You can retrieve a single container's details by using its name. An -instance of ``OpenCloud\ObjectStore\Resource\Container`` is returned. - -.. code:: php - - $container = $objectStoreService->getContainer('logos'); - - /** @var $container OpenCloud\ObjectStore\Resource\Container **/ - -[ `Get the executable PHP script for this -example `__ ] - -List Containers -~~~~~~~~~~~~~~~ - -You can retrieve a list of all your containers. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $containers = $objectStoreService->listContainers(); - foreach ($containers as $container) { - /** @var $container OpenCloud\ObjectStore\Resource\Container **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Set or Update Container Metadata -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can set metadata on a container. - -.. code:: php - - $container->saveMetadata(array( - 'author' => 'John Doe' - )); - -[ `Get the executable PHP script for this -example `__ ] - -Get Container Metadata -~~~~~~~~~~~~~~~~~~~~~~ - -You can retrieve the metadata for a container. - -.. code:: php - - $containerMetadata = $container->getMetadata(); - -[ `Get the executable PHP script for this -example `__ ] - -Delete Container -~~~~~~~~~~~~~~~~ - -When you no longer have a need for the container, you can remove it. - -If the container is empty (that is, it has no objects in it), you can -remove it as shown below: - -.. code:: php - - $container->delete(); - -[ `Get the executable PHP script for this -example `__ ] - -If the container is not empty (that is, it has objects in it), you have -two choices in how to remove it: - -- `Individually remove each object <#delete-object>`__ in the - container, then remove the container itself as shown above, or - -- Remove the container and all the objects within it as shown below: - - .. code:: php - - $container->delete(true); - - [ `Get the executable PHP script for this - example `__ ] - -Get Object Count -~~~~~~~~~~~~~~~~ - -You can quickly find out how many objects are in a container. - -.. code:: php - - $containerObjectCount = $container->getObjectCount(); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, ``$containerObjectCount`` will contain the number -of objects in the container represented by ``$container``. - -Get Bytes Used -~~~~~~~~~~~~~~ - -You can quickly find out the space used by a container, in bytes. - -.. code:: php - - $containerSizeInBytes = $container->getBytesUsed(); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, ``$containerSizeInBytes`` will contain the space -used, in bytes, by the container represented by ``$container``. - -Container Quotas -~~~~~~~~~~~~~~~~ - -Set Quota for Number of Objects -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -You can set a quota for the maximum number of objects that may be stored -in a container. - -.. code:: php - - $maximumNumberOfObjectsAllowedInContainer = 25; - $container->setCountQuota($maximumNumberOfObjectsAllowedInContainer); - -[ `Get the executable PHP script for this -example `__ ] - -Set Quota for Total Size of Objects -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -You can set a quota for the maximum total space (in bytes) used by -objects in a container. - -.. code:: php - - use OpenCloud\Common\Constants\Size; - - $maximumTotalSizeOfObjectsInContainer = 5 * Size::GB; - $container->setBytesQuota($maximumTotalSizeOfObjectsInContainer); - -[ `Get the executable PHP script for this -example `__ ] - -Get Quota for Number of Objects -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -You can retrieve the quota for the maximum number of objects that may be -stored in a container. - -.. code:: php - - $maximumNumberOfObjectsAllowedInContainer = $container->getCountQuota(); - -[ `Get the executable PHP script for this -example `__ ] - -Get Quota for Total Size of Objects -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -You can retrieve the quota for the maximum total space (in bytes) used -by objects in a container. - -.. code:: php - - $maximumTotalSizeOfObjectsAllowedInContainer = $container->getBytesQuota(); - -[ `Get the executable PHP script for this -example `__ ] - -Objects -------- - -An **object** (sometimes referred to as a file) is the unit of storage -in an Object Store. An object is a combination of content (data) and -metadata. - -For example, you may upload an object named ``php-elephant.jpg``, a JPEG -image file, to the ``logos`` container. Further, you may assign metadata -to this object to indicate that the author of this object was someone -named Jane Doe. - - **Note:** when working with names that contain non-standard - alphanumerical characters (such as spaces or non-English - characters), you must ensure they are encoded with - ```urlencode`` `__ before passing them in - -Upload Object -~~~~~~~~~~~~~ - -Once you have created a container, you can upload objects to it. - -.. code:: php - - $localFileName = '/path/to/local/php-elephant.jpg'; - $remoteFileName = 'php-elephant.jpg'; - - $fileData = fopen($localFileName, 'r'); - $container->uploadObject($remoteFileName, $fileData); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, an image file from the local filesystem -(``path/to/local/php-elephant.jpg``) is uploaded to a container in the -Object Store. - -Note that while we call ``fopen`` to open the file resource, we do not -call ``fclose`` at the end. The file resource is automatically closed -inside the ``uploadObject`` call. - -It is also possible to upload an object and associate metadata with it. - -.. code:: php - - use OpenCloud\ObjectStore\Resource\DataObject; - - $localFileName = '/path/to/local/php-elephant.jpg'; - $remoteFileName = 'php-elephant.jpg'; - $metadata = array('author' => 'Jane Doe'); - - $customHeaders = array(); - $metadataHeaders = DataObject::stockHeaders($metadata); - $allHeaders = $customHeaders + $metadataHeaders; - - $fileData = fopen($localFileName, 'r'); - $container->uploadObject($remoteFileName, $fileData, $allHeaders); - -[ `Get the executable PHP script for this -example `__ ] - -Note that while we call ``fopen`` to open the file resource, we do not -call ``fclose`` at the end. The file resource is automatically closed -inside the ``uploadObject`` call. - -Pseudo-hierarchical Folders -^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Although you cannot nest directories in an Object Store, you can -simulate a hierarchical structure within a single container by adding -forward slash characters (``/``) in the object name. - -.. code:: php - - $localFileName = '/path/to/local/php-elephant.jpg'; - $remoteFileName = 'languages/php/elephant.jpg'; - - $fileData = fopen($localFileName, 'r'); - $container->uploadObject($remoteFileName, $fileData); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, an image file from the local filesystem -(``/path/to/local/php-elephant.jpg``) is uploaded to a container in the -Object Store. Within that container, the filename is -``languages/php/elephant.jpg``, where ``languages/php/`` is a -pseudo-hierarchical folder hierarchy. - -Note that while we call ``fopen`` to open the file resource, we do not -call ``fclose`` at the end. The file resource is automatically closed -inside the ``uploadObject`` call. - -Upload Multiple Objects -^^^^^^^^^^^^^^^^^^^^^^^ - -You can upload more than one object at a time to a container. - -.. code:: php - - $objects = array( - array( - 'name' => 'php-elephant.jpg', - 'path' => '/path/to/local/php-elephant.jpg' - ), - array( - 'name' => 'python-snake.jpg', - 'path' => '/path/to/local/python-snake.jpg' - ), - a - ); - - $container->uploadObjects($objects); - -[ `Get the executable PHP script for this -example `__ ] - -In the above example, the contents of two files present on the local -filesystem are uploaded as objects to the container referenced by -``$container``. - -Instead of specifying the ``path`` key in an element of the ``$objects`` -array, you can specify a ``body`` key whose value is a string or a -stream representation. - -Finally, you can pass headers as the second parameter to the -``uploadObjects`` method. These headers will be applied to every object -that is uploaded. - -:: - - $metadata = array('author' => 'Jane Doe'); - - $customHeaders = array(); - $metadataHeaders = DataObject::stockHeaders($metadata); - $allHeaders = $customHeaders + $metadataHeaders; - - $container->uploadObjects($objects, $allHeaders); - -[ `Get the executable PHP script for this -example `__ -] - -In the example above, every object referenced within the ``$objects`` -array will be uploaded with the same metadata. - -Large Objects -~~~~~~~~~~~~~ - -If you want to upload objects larger than 5GB in size, you must use a -different upload process. - -.. code:: php - - $options = array( - 'name' => 'san_diego_vacation_video.mp4', - 'path' => '/path/to/local/videos/san_diego_vacation.mp4' - ); - $objectTransfer = $container->setupObjectTransfer($options); - $objectTransfer->upload(); - -[ `Get the executable PHP script for this -example `__ ] - -The process shown above will automatically partition your large object -into small chunks and upload them concurrently to the container -represented by ``$container``. - -You can tune the parameters of this process by specifying additional -options in the ``$options`` array. Here is a complete listing of keys -that can be specified in the ``$options`` array: - -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ -| Key name | Description | Data Type | Required? | Default Value | Example | -+===================+================================================================================================================================================================================================================================================================================================================+=================================================+=================================================+==================================================+====================================================+ -| ``name`` | Name of large object in container | String | Yes | - | ``san_diego_vacation_video.mp4`` | -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ -| ``path`` | Path to file containing object data on local filesystem | String | One of ``path`` or ``body`` must be specified | - | ``/path/to/local/videos/san_diego_vacation.mp4`` | -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ -| ``body`` | String or stream representation of object data | String \| Stream | One of ``path`` or ``body`` must be specified | - | ``... lots of data ...`` | -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ -| ``metadata`` | Metadata for the object | Associative array of metadata key-value pairs | No | ``array()`` | ``array( "Author" => "Jane Doe" )`` | -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ -| ``partSize`` | The size, in bytes, of each chunk that the large object is partitioned into prior to uploading | Integer | No | ``1073741824`` (1GB) | ``52428800`` (50MB) | -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ -| ``concurrency`` | The number of concurrent transfers to execute as part of the upload | Integer | No | ``1`` (no concurrency; upload chunks serially) | ``10`` | -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ -| ``progress`` | A `callable function or method `__ which is called to report progress of the the upload. See ```CURLOPT_PROGRESSFUNCTION`` documentation `__ for details on parameters passed to this callable function or method. | String (callable function or method name) | No | None | ``reportProgress`` | -+-------------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+-------------------------------------------------+--------------------------------------------------+----------------------------------------------------+ - -Auto-extract Archive Files -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can upload a tar archive file and have the Object Store service -automatically extract it into a container. - -.. code:: php - - use OpenCloud\ObjectStore\Constants\UrlType; - - $localArchiveFileName = '/path/to/local/image_files.tar.gz'; - $remotePath = 'images/'; - - $fileData = fopen($localArchiveFileName, 'r'); - $objectStoreService->bulkExtract($remotePath, $fileData, UrlType::TAR_GZ); - -[ `Get the executable PHP script for this -example `__ ] - -In the above example, a local archive file named ``image_files.tar.gz`` -is uploaded to an Object Store container named ``images`` (defined by -the ``$remotePath`` variable). - -Note that while we call ``fopen`` to open a file resource, we do not -call ``fclose`` at the end. The file resource is automatically closed -inside the ``bulkExtract`` call. - -The third parameter to ``bulkExtract`` is the type of the archive file -being uploaded. The acceptable values for this are: - -- ``UrlType::TAR`` for tar archive files, *or*, -- ``UrlType:TAR_GZ`` for tar archive files that are compressed with - gzip, *or* -- ``UrlType::TAR_BZ`` for tar archive file that are compressed with - bzip - -Note that the value of ``$remotePath`` could have been a -(pseudo-hierarchical folder)[#pseudo-hierarchical-folders] such as -``images/blog`` as well. - -List Objects in a Container -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can list all the objects stored in a container. An instance of -``OpenCloud\Common\Collection\PaginatedIterator`` is returned. - -.. code:: php - - $objects = $container->objectList(); - foreach ($objects as $object) { - /** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -You can list only those objects in the container whose names start with -a certain prefix. - -.. code:: php - - $options = array( - 'prefix' => 'php' - ); - - $objects = $container->objectList($options); - -[ `Get the executable PHP script for this -example `__ ] - -In general, the ``objectList()`` method described above takes an -optional parameter (``$options`` in the example above). This parameter -is an associative array of various options. Here is a complete listing -of keys that can be specified in the ``$options`` array: - -+------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ -| Key name | Description | Data Type | Required? | Default Value | Example | -+==================+=============================================================================+=============+=============+=================+=========================+ -| ``prefix`` | Given a string x, limits the results to object names beginning with x. | String | No | | ``php`` | -+------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ -| ``limit`` | Given an integer n, limits the number of results to at most n values. | Integer | No | | 10 | -+------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ -| ``marker`` | Given a string x, returns object names greater than the specified marker. | String | No | | ``php-elephant.jpg`` | -+------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ -| ``end_marker`` | Given a string x, returns object names less than the specified marker. | String | No | | ``python-snakes.jpg`` | -+------------------+-----------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------+ - -Retrieve Object -~~~~~~~~~~~~~~~ - -You can retrieve an object and its metadata, given the object's -container and name. - -.. code:: php - - $objectName = 'php-elephant.jpg'; - $object = $container->getObject($objectName); - - /** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ - - $objectContent = $object->getContent(); - - /** @var $objectContent Guzzle\Http\EntityBody **/ - - // Write object content to file on local filesystem. - $objectContent->rewind(); - $stream = $objectContent->getStream(); - $localFilename = tempnam("/tmp", 'php-opencloud-'); - file_put_contents($localFilename, $stream); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, ``$object`` is the object named -``php-elephant.jpg`` in the container represented by ``$container``. -Further, ``$objectContent`` represents the contents of the object. It is -of type -```Guzzle\Http\EntityBody`` `__. - -Retrieve Object Metadata -~~~~~~~~~~~~~~~~~~~~~~~~ - -You can retrieve just an object's metadata without retrieving its -contents. - -.. code:: php - - $objectName = 'php-elephant.jpg'; - $object = $container->getPartialObject($objectName); - $objectMetadata = $object->getMetadata(); - - /** @var $objectMetadata \OpenCloud\Common\Metadata **/ - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, while ``$object`` is an instance of -``OpenCloud\ObjectStore\Resource\DataObject``, that instance is only -partially populated. Specifically, only properties of the instance -relating to object metadata are populated. - -Temporary URLs -~~~~~~~~~~~~~~ - -The Temporary URL feature allows you to create limited-time Internet -addresses that allow you to grant limited access to your Object Store -account. Using this feature, you can allow others to retrieve or place -objects in your Object Store account for a specified amount of time. -Access to the temporary URL is independent of whether or not your -account is `CDN-enabled <#cdn-containers>`__. Even if you do not -CDN-enable a container, you can still grant temporary public access -through a temporary URL. - -First, you must set the temporary URL secret on your account. This is a -one-time operation; you only need to perform it the very first time you -wish to use the temporary URLs feature. - -.. code:: php - - $account->setTempUrlSecret(); - -[ `Get the executable PHP script for this -example `__ ] - -Note that this operation is carried out on ``$account``, which is an -instance of ``OpenCloud\ObjectStore\Resource\Account``, a class -representing `your object store account <#accounts>`__. - -The above operation will generate a random secret and set it on your -account. Instead of a random secret, if you wish to provide a secret, -you can supply it as a parameter to the ``setTempUrlSecret`` method. - -.. code:: php - - $account->setTempUrlSecret(''); - -[ `Get the executable PHP script for this -example `__ -] - -Once a temporary URL secret has been set on your account, you can -generate a temporary URL for any object in your Object Store. - -.. code:: php - - $expirationTimeInSeconds = 3600; // one hour from now - $httpMethodAllowed = 'GET'; - $tempUrl = $object->getTemporaryUrl($expirationTimeInSeconds, $httpMethodAllowed); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, a temporary URL for the object is generated. This -temporary URL will provide public access to the object for an hour (3600 -seconds), as specified by the ``$expirationTimeInSeconds`` variable. -Further, only GET HTTP methods will be allowed on this URL, as specified -by the ``$httpMethodAllowed`` variable. The other value allowed for the -``$httpMethodAllowed`` variable would be ``PUT``. - -You can also retrieve the temporary URL secret that has been set on your -account. - -.. code:: php - - $tempUrlSecret = $account->getTempUrlSecret(); - -[ `Get the executable PHP script for this -example `__ ] - -Update Object -~~~~~~~~~~~~~ - -You can update an object's contents (as opposed to `updating its -metadata <#update-object-metadata>`__) by simply re-\ `uploading the -object <#upload-object>`__ to its container using the same object name -as before. - -Update Object Metadata -~~~~~~~~~~~~~~~~~~~~~~ - -You can update an object's metadata after it has been uploaded to a -container. - -.. code:: php - - $object->saveMetadata(array( - 'author' => 'John Doe' - )); - -[ `Get the executable PHP script for this -example `__ ] - -Copy Object -~~~~~~~~~~~ - -You can copy an object from one container to another, provided the -destination container already exists. - -.. code:: php - - $object->copy('logos_copy/php.jpg'); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, both the name of the destination container -(``logos_copy``)and the name of the destination object (``php.jpg``) -have to be specified, separated by a ``/``. - -Delete Object -~~~~~~~~~~~~~ - -When you no longer need an object, you can delete it. - -.. code:: php - - $object->delete(); - -[ `Get the executable PHP script for this -example `__ ] - -Bulk Delete -~~~~~~~~~~~ - -While you can delete individual objects as shown above, you can also -delete objects and empty containers in bulk. - -.. code:: php - - $objectStoreService->bulkDelete(array( - 'logos/php-elephant.png', - 'logos/python-snakes.png', - 'some_empty_container' - )); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, two objects (``some_container/object_a.png``, -``some_other_container/object_z.png``) and one empty container -(``some_empty_container``) are all being deleted in bulk via a single -command. - -CDN Containers --------------- - -Note: The functionality described in this section is available only on -the Rackspace cloud. It will not work as described when working with a -vanilla OpenStack cloud. - -Any container can be converted to a CDN-enabled container. When this is -done, the objects within the container can be accessed from anywhere on -the Internet via a URL. - -Enable CDN Container -~~~~~~~~~~~~~~~~~~~~ - -To take advantage of CDN capabilities for a container and its objects, -you must CDN-enable that container. - -.. code:: php - - $container->enableCdn(); - -[ `Get the executable PHP script for this -example `__ ] - -Public URLs -~~~~~~~~~~~ - -Once you have CDN-enabled a container, you can retrieve a -publicly-accessible URL for any of its objects. There are four types of -publicly-accessible URLs for each object. Each type of URL is meant for -a different purpose. The sections below describe each of these URL types -and how to retrieve them. - -HTTP URL -^^^^^^^^ - -You can use this type of URL to access the object over HTTP. - -:: - - $httpUrl = $object->getPublicUrl(); - -[ `Get the executable PHP script for this -example `__ ] - -Secure HTTP URL -^^^^^^^^^^^^^^^ - -You can use this type of URL to access the object over HTTP + TLS/SSL. - -:: - - use OpenCloud\ObjectStore\Constants\UrlType; - - $httpsUrl = $object->getPublicUrl(UrlType::SSL); - -[ `Get the executable PHP script for this -example `__ ] - -Streaming URL -^^^^^^^^^^^^^ - -You can use this type of URL to stream a video or audio object using -Adobe's HTTP Dynamic Streaming. - -:: - - use OpenCloud\ObjectStore\Constants\UrlType; - - $streamingUrl = $object->getPublicUrl(UrlType::STREAMING); - -[ `Get the executable PHP script for this -example `__ ] - -IOS Streaming URL -^^^^^^^^^^^^^^^^^ - -You can use this type of URL to stream an audio or video object to an -iOS device. - -:: - - use OpenCloud\ObjectStore\Constants\UrlType; - - $iosStreamingUrl = $object->getPublicUrl(UrlType::IOS_STREAMING); - -[ `Get the executable PHP script for this -example `__ ] - -Update CDN Container TTL -~~~~~~~~~~~~~~~~~~~~~~~~ - -You can update the TTL of a CDN-enabled container. - -.. code:: php - - $cdnContainer = $container->getCdn(); - $cdnContainer->setTtl(); - -[ `Get the executable PHP script for this -example `__ ] - -Disable CDN Container -~~~~~~~~~~~~~~~~~~~~~ - -If you no longer need CDN capabilities for a container, you can disable -them. - -.. code:: php - - $container->disableCdn(); - -[ `Get the executable PHP script for this -example `__ ] - -Accounts --------- - -An **account** defines a namespace for **containers**. An account can -have zero or more containers in it. - -Retrieve Account -~~~~~~~~~~~~~~~~ - -You must retrieve the account before performing any operations on it. - -.. code:: php - - $account = $objectStoreService->getAccount(); - -Get Container Count -~~~~~~~~~~~~~~~~~~~ - -You can quickly find out how many containers are in your account. - -.. code:: php - - $accountContainerCount = $account->getContainerCount(); - -[ `Get the executable PHP script for this -example `__ ] - -Get Object Count -~~~~~~~~~~~~~~~~ - -You can quickly find out how many objects are in your account. - -.. code:: php - - $accountObjectCount = $account->getObjectCount(); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, ``$accountObjectCount`` will contain the number of -objects in the account represented by ``$account``. - -Get Bytes Used -~~~~~~~~~~~~~~ - -You can quickly find out the space used by your account, in bytes. - -.. code:: php - - $accountSizeInBytes = $account->getBytesUsed(); - -[ `Get the executable PHP script for this -example `__ ] - -In the example above, ``$accountSizeInBytes`` will contain the space -used, in bytes, by the account represented by ``$account``. diff --git a/doc/services/object-store/Access.md.rst b/doc/services/object-store/access.rst similarity index 52% rename from doc/services/object-store/Access.md.rst rename to doc/services/object-store/access.rst index ee85a938e..62cb541ca 100644 --- a/doc/services/object-store/Access.md.rst +++ b/doc/services/object-store/access.rst @@ -1,31 +1,19 @@ -Setup ------ - -.. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(RACKSPACE_US, array( - - )); - - $service = $client->objectStoreService('cloudFiles', 'IAD'); # Second argument is the region you want - Temporary URLs --------------- +============== Temporary URLs allow you to create time-limited Internet addresses that allow you to grant access to your Cloud Files account. Using Temporary URL, you may allow others to retrieve or place objects in your containers - regardless of whether they're CDN-enabled. + Set "temporary URL" metadata key -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-------------------------------- You must set this "secret" value on your account, where it can be used in a global state: -.. code:: php +.. code-block:: php $account = $service->getAccount(); $account->setTempUrlSecret('my_secret'); @@ -35,41 +23,64 @@ in a global state: The string argument of ``setTempUrlSecret()`` is optional - if left out, the SDK will generate a random hashed secret for you. + Create a temporary URL -~~~~~~~~~~~~~~~~~~~~~~ +---------------------- Once you've set an account secret, you can create a temporary URL for your object. To allow GET access to your object for 1 minute: -.. code:: php +.. code-block:: php $object->getTemporaryUrl(60, 'GET'); + To allow PUT access for 1 hour: -.. code:: php +.. code-block:: php $object->getTemporaryUrl(360, 'PUT'); -Hosting websites on CloudFiles ------------------------------- -To host a static (i.e. HTML) website on CloudFiles, you must follow +Hosting HTML sites on CDN +========================= + +.. include:: rs-only.rst + +To host a static (i.e. HTML) website on Cloud Files, you must follow these steps: -1. CDN-enable a container +1. CDN-enable a container: + +.. code-block:: php + + $container = $service->getContainer('html_site'); + $container->enableCdn(); + 2. Upload all HTML content. You can use nested directory structures. -3. Tell CloudFiles what to use for your default index page like this: -.. code:: php +.. code-block:: php + + $container->uploadObjects(array( + array('name' => 'index.html', 'path' => 'index.html'), + array('name' => 'contact.html', 'path' => 'contact.html'), + array('name' => 'error.html', 'path' => 'error.html'), + array('name' => 'styles.css', 'path' => 'styles.css'), + array('name' => 'main.js', 'path' => 'main.js'), + )); + +3. Tell Cloud Files what to use for your default index page like this: + +.. code-block:: php + + $container->setStaticIndexPage('index.html'); - $container->setStaticIndexPage('index.html'); +4. (Optional) Tell Cloud Files which error page to use by default: -4. (Optional) Tell CloudFiles which error page to use by default: +.. code-block:: php -.. code:: php + $container->setStaticErrorPage('error.html'); - $container->setStaticErrorPage('error.html'); Bear in mind that steps 3 & 4 do not upload content, but rather specify a reference to an existing page/CloudFiles object. diff --git a/doc/services/object-store/account.rst b/doc/services/object-store/account.rst new file mode 100644 index 000000000..fb51c8855 --- /dev/null +++ b/doc/services/object-store/account.rst @@ -0,0 +1,46 @@ +Account Details +=============== + +To see how many containers you have in your account +(X-Account-Container-Count), how many objects are in your account +(X-Account-Object-Count), and how many total bytes your account uses +(X-Account-Bytes-Used): + +Setup +----- + +.. code-block:: php + + $account = $service->getAccount(); + + +View all details +---------------- + +.. code-block:: php + + $details = $account->getDetails(); + + +Retrieve total container count +------------------------ + +.. code-block:: php + + $account->getContainerCount(); + + +Retrieve total object count +--------------------- + +.. code-block:: php + + $account->getObjectCount(); + + +Retrieve total bytes used +------------------------- + +.. code-block:: php + + $account->getBytesUsed(); diff --git a/doc/services/object-store/cdn.rst b/doc/services/object-store/cdn.rst new file mode 100644 index 000000000..5ad72b6cd --- /dev/null +++ b/doc/services/object-store/cdn.rst @@ -0,0 +1,124 @@ +CDN Containers +============== + +.. include:: rs-only.rst + +Setup +----- + +In order to interact with CDN containers, you first need to instantiate a +CDN service object: + +.. code-block:: php + + $cdnService = $service->getCdnService(); + + +List CDN-enabled containers +--------------------------- + +To list CDN-only containers, follow the same operation for Storage which +lists all containers. The only difference is which service object you +execute the method on: + +.. code-block:: php + + $cdnContainers = $cdnService->listContainers(); + + foreach ($cdnContainers as $cdnContainer) { + /** @var $cdnContainer OpenCloud\ObjectStore\Resource\CDNContainer */ + } + + +CDN-enable a container +---------------------- + +Before a container can be CDN-enabled, it must exist in the storage +system. When a container is CDN-enabled, any objects stored in it are +publicly accessible over the Content Delivery Network by combining the +container's CDN URL with the object name. + +Any CDN-accessed objects are cached in the CDN for the specified amount +of time called the TTL. The default TTL value is 259200 seconds, or 72 +hours. Each time the object is accessed after the TTL expires, the CDN +refetches and caches the object for the TTL period. + +.. code-block:: php + + $container->enableCdn(); + + +CDN-disable a container +----------------------- + +.. code-block:: php + + $container->disableCdn(); + + +Operations on CDN-enabled containers +------------------------------------ + +Once a container has been CDN-enabled, you can retrieve it like so: + +.. code-block:: php + + $cdnContainer = $cdnService->cdnContainer('{containerName}'); + + +Retrieve the SSL URL of a CDN container +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $cdnContainer->getCdnSslUri(); + + +Retrieve the streaming URL of a CDN container +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $cdnContainer->getCdnStreamingUri(); + + +Retrieve the iOS streaming URL of a CDN container +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The Cloud Files CDN allows you to stream video to iOS devices without +needing to convert your video. Once you CDN-enable your container, you +have the tools necessary for streaming media to multiple devices. + +.. code-block:: php + + $cdnContainer->getIosStreamingUri(); + + +CDN logging +~~~~~~~~~~~ + +To enable and disable logging for your CDN-enabled container: + +.. code-block:: php + + $cdnContainer->enableCdnLogging(); + $cdnContainer->disableCdnLogging(); + + +Purge CDN-enabled objects +------------------------- + +To remove a CDN object from public access: + +.. code-block:: php + + $object->purge(); + +You can also provide an optional e-mail address (or comma-delimeted list +of e-mails), which the API will send a confirmation message to once the +object has been completely purged: + +.. code-block:: php + + $object->purge('jamie.hannaford@rackspace.com'); + $object->purge('hello@example.com,hallo@example.com'); diff --git a/doc/services/object-store/Container.md.storage.rst b/doc/services/object-store/containers.rst similarity index 53% rename from doc/services/object-store/Container.md.storage.rst rename to doc/services/object-store/containers.rst index 89798fdd0..4b9c66ac3 100644 --- a/doc/services/object-store/Container.md.storage.rst +++ b/doc/services/object-store/containers.rst @@ -1,26 +1,12 @@ -Setup ------ - -.. code:: php - - use OpenCloud\Rackspace; - - // Create a client object to communicate with various Rackspace Cloud services. - $client = new Rackspace(RACKSPACE_US, array( - 'username' => 'Replace this with your Rackspace Cloud user name', - 'apiKey' => 'Replace this with your Rackspace Cloud API key' - )); - - // Create a service object to use the object store service. The sample code - // creates the object store in the 'DFW' region. - $service = $client->objectStoreService('cloudFiles', 'DFW'); +Containers +========== Create container ---------------- To create a new container, you just need to define its name: -.. code:: php +.. code-block:: php $container = $service->createContainer('my_amazing_container'); @@ -30,133 +16,153 @@ likely due to the fact you have a naming collision. Container names must be valid strings between 0 and 256 characters. Forward slashes are not currently permitted. - **Note:** when working with names that contain non-standard - alphanumerical characters (such as spaces or non-English - characters), you must ensure they are encoded with - ```urlencode`` `__ before passing them in +.. note:: + + When working with names that contain non-standard alphanumerical characters + (such as spaces or non-English characters), you must ensure they are encoded + with `urlencode `_ before passing them in List containers --------------- -Return a list of containers -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php +.. code-block:: php - $containerList = $service->listContainers(); + $containers = $service->listContainers(); - while ($container = $containerList->next()) { - // Do stuff; some examples below - printf("Container name: %s\n", $container->name); - printf("Number of objects within container: %d\n", $container->getObjectCount()); - } + foreach ($containers as $container) { + /** @param $container OpenCloud\ObjectStore\Resource\Container */ + printf("Container name: %s\n", $container->name); + printf("Number of objects within container: %d\n", $container->getObjectCount()); + } Container names are sorted based on a binary comparison, a single built-in collating sequence that compares string data using SQLite's memcmp() function, regardless of text encoding. -The list is limited to 10,000 containers at a time. See 1.3 for ways to -limit and navigate this list. +The list is limited to 10,000 containers at a time. To work with larger +collections, please read the next section. -Return a formatted list of containers -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Currently, the SDK only supports JSON-formatted responses. - -Controlling a large list of containers -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Filtering large collections +~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You may limit and control this list of results by using the ``marker`` +When you need more control over collections of containers, you can filter the +results and return back a subset of the total collection by using the ``marker`` and ``end_marker`` parameters. The former parameter (``marker``) tells the API where to begin the list, and the latter (``end_marker``) tells it where to end the list. You may use either of them independently or -together. You may also use the ``limit`` parameter to fix the number of +together. + +You may also use the ``limit`` parameter to fix the number of containers returned. To list a set of containers between two fixed points: -.. code:: php +.. code-block:: php - $someContainers = $service->listContainers(array( - 'marker' => 'container_55', - 'end_marker' => 'container_2001' - )); + $someContainers = $service->listContainers(array( + 'marker' => 'container_55', + 'end_marker' => 'container_2001' + )); Or to return a limited set: -.. code:: php +.. code-block:: php + + $someContainers = $service->listContainers(array('limit' => 560)); - $someContainers = $service->listContainers(array('limit' => 560)); Get container ------------- -To retrieve a certain container, either to access its object or -metadata: +To retrieve a certain container: + +.. code-block:: php + + /** @param $container OpenCloud\ObjectStore\Resource\Container */ + $container = $service->getContainer('{containerName}'); + + +Retrieve a container's name +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php -.. code:: php + $name = $container->name; - $container = $service->getContainer('container_name'); - echo $container->getObjectCount(); - echo $container->getBytesUsed(); +Retrieve a container's object count +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $count = $container->getObjectCount(); + + +Retrieve a container's total bytes used +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $bytes = $container->getBytesUsed(); + Delete container ---------------- -Deleting a container is easy: +Deleting an empty container is easy: -.. code:: php +.. code-block:: php + + $container->delete(); - $container->delete(); Please bear mind that you must delete all objects inside a container before deleting it. This is done for you if you set the ``$deleteObjects`` parameter to ``TRUE`` like so: -.. code:: php +.. code-block:: php + + $container->delete(true); - $container->delete(TRUE); -You can also do it manually: +You can also `delete all objects <#deleting-all-objects-inside-a-container>`_ +first, and then call ``delete``. -.. code:: php - $container->deleteAllObjects(); - $container->delete(); +Deleting all objects inside a container +--------------------------------------- + +.. code-block:: php + + $container->deleteAllObjects(); + Create or update container metadata ----------------------------------- -.. code:: php +.. code-block:: php - $container->saveMetadata(array( - 'Author' => 'Virginia Woolf', - 'Published' => '1931' - )); + $container->saveMetadata(array( + 'Author' => 'Virginia Woolf', + 'Published' => '1931' + )); Please bear in mind that this action will set metadata to this array - overriding existing values and wiping those left out. To *append* values to the current metadata: -.. code:: php - - $metadata = $container->appendToMetadata(array( - 'Publisher' => 'Hogarth' - )); +.. code-block:: php -If you only want to set the metadata to the local object, and not -immediately retain these values on the API, you can use a standard -setter method - which can contribute to eventual actions like an update: + $metadata = $container->appendToMetadata(array( + 'Publisher' => 'Hogarth' + )); -.. code:: php - - $container->setMetadata(array('Foo' => 'Bar')); Container quotas ---------------- -The container\_quotas middleware implements simple quotas that can be +The ``container_quotas`` middleware implements simple quotas that can be imposed on Cloud Files containers by a user. Setting container quotas can be useful for limiting the scope of containers that are delegated to non-admin users, exposed to formpost uploads, or just as a self-imposed @@ -164,19 +170,20 @@ sanity check. To set quotas for a container: -.. code:: php +.. code-block:: php - use OpenCloud\Common\Constants\Size; + use OpenCloud\Common\Constants\Size; - $container->setCountQuota(1000); - $container->setBytesQuota(2.5 * Size::GB); + $container->setCountQuota(1000); + $container->setBytesQuota(2.5 * Size::GB); And to retrieve them: -.. code:: php +.. code-block:: php + + echo $container->getCountQuota(); + echo $container->getBytesQuota(); - echo $container->getCountQuota(); - echo $container->getBytesQuota(); Access log delivery ------------------- @@ -186,10 +193,11 @@ access logs to analyze the number of people who access your objects, where they come from, how many requests for each object you receive, and time-based usage patterns (such as monthly or seasonal usage). -.. code:: php +.. code-block:: php + + $container->enableLogging(); + $container->disableLogging(); - $container->enableLogging(); - $container->disableLogging(); Syncing containers ------------------ @@ -198,9 +206,9 @@ You can synchronize local directories with your CloudFiles/Swift containers very easily. When you do this, the container will mirror exactly the nested file structure within your local directory: -.. code:: php +.. code-block:: php - $container->uploadDirectory('/home/Jamie/blog'); + $container->uploadDirectory('/home/user/my-blog'); There are four scenarios you should be aware of: @@ -215,4 +223,3 @@ There are four scenarios you should be aware of: +------------------------+-----------------------+----------------------+--------------------------------+ | Files does not exist | File exists | - | Remote file deleted | +------------------------+-----------------------+----------------------+--------------------------------+ - diff --git a/doc/services/object-store/index.rst b/doc/services/object-store/index.rst index e69de29bb..6b3a18b6f 100644 --- a/doc/services/object-store/index.rst +++ b/doc/services/object-store/index.rst @@ -0,0 +1,57 @@ +Object Store v1 +=============== + +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now, set up the Object Store service: + +.. code-block:: php + + $service = $client->objectStoreService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + +.. toctree:: + + account + containers + objects + cdn + migrating-containers + access + +Glossary +-------- + +.. glossary:: + + account + The portion of the system designated for your use. An Object Store system is + typically designed to be used by many different customers, and your user + account is your portion of it. + + container + A storage compartment that provides a way for you to organize data. A + container is similar to a folder in Windows or a directory in UNIX. The + primary difference between a container and these other file system concepts + is that containers cannot be nested. + + cdn + A system of distributed servers (network) that delivers web pages and other + web content to a user based on the geographic locations of the user, the + origin of the web page, and a content delivery server. + + metadata + Optional information that you can assign to Cloud Files accounts, + containers, and objects through the use of a metadata header. + + object + An object (sometimes referred to as a file) is the unit of storage in an + Object Store. An object is a combination of content (data) and metadata. diff --git a/doc/services/object-store/Migrating.md.storage.rst b/doc/services/object-store/migrating-containers.rst similarity index 82% rename from doc/services/object-store/Migrating.md.storage.rst rename to doc/services/object-store/migrating-containers.rst index 99738554b..22adb839b 100644 --- a/doc/services/object-store/Migrating.md.storage.rst +++ b/doc/services/object-store/migrating-containers.rst @@ -1,8 +1,5 @@ -Migrating containers (across regions) -===================================== - -Introduction ------------- +Migrating containers across regions +=================================== Currently, there exists no single API operation to copy containers across geographic endpoints. Although the API offers a ``COPY`` @@ -12,6 +9,7 @@ copying. The SDK, however, does offer this functionality. You **will** be charged for bandwidth between regions, so it's advisable to use ServiceNet where possible (which is free). + Requirements ------------ @@ -20,71 +18,84 @@ Requirements requests to be batched for greater efficiency). You can do this by running: -.. code:: bash +.. code-block:: bash - php composer.phar install --dev + composer require guzzle/guzzle - Depending on the size and number of transfer items, you will need to raise PHP's memory limit: -.. code:: php +.. code-block:: php - ini_set('memory_limit', '512M'); + ini_set('memory_limit', '512M'); - You will need to enact some kind of backoff/retry strategy for rate limits. Guzzle comes with a convenient feature that just needs to be added as a normal subscriber: -.. code:: php +.. code-block:: php use Guzzle\Plugin\Backoff\BackoffPlugin; - $client->addSubscriber(BackoffPlugin::getExponentialBackoff(10, array(500, 503, 408))); + // set timeout in secs + $timeout = 10; + + // set HTTP error codes + $httpErrors = array(500, 503, 408); + + $backoffPlugin = BackoffPlugin::getExponentialBackoff($timeout, $httpErrors); + $client->addSubscriber($backoffPlugin); + This tells the client to retry up to ``10`` times for failed requests have resulted in these HTTP status codes: ``500``, ``503`` or ``408``. + Setup ----- You can access all this functionality by executing: -.. code:: php +.. code-block:: php + + $ordService = $client->objectStoreService('cloudFiles', 'ORD'); + $iadService = $client->objectStoreService('cloudFiles', 'IAD'); - $ordService = $client->objectStoreService('cloudFiles', 'ORD'); - $iadService = $client->objectStoreService('cloudFiles', 'IAD'); + $oldContainer = $ordService->getContainer('old_container'); + $newContainer = $iadService->getContainer('new_container'); - $oldContainer = $ordService->getContainer('old_container'); - $newContainer = $iadService->getContainer('new_container'); + $iadService->migrateContainer($oldContainer, $newContainer); - $iadService->migrateContainer($oldContainer, $newContainer); It's advisable to do this process in a Cloud Server in one of the two regions you're migrating to/from. This allows you to use ``privateURL`` as the third argument in the ``objectStoreService`` methods like this: -.. code:: php +.. code-block:: php + + $client->objectStoreService('cloudFiles', 'IAD', 'privateURL'); - $client->objectStoreService('cloudFiles', 'IAD', 'privateURL'); This will ensure that traffic between your server and your new IAD container will be held over the internal Rackspace network which is free. + Options ------- You can pass in an array of arguments to the method: -.. code:: php +.. code-block:: php + + $options = array( + 'read.batchLimit' => 100, + 'read.pageLimit' => 100, + 'write.batchLimit' => 50 + ); - $options = array( - 'read.batchLimit' => 100, - 'read.pageLimit' => 100, - 'write.batchLimit' => 50 - ); + $iadService->migrateContainer($oldContainer, $newContainer, $options); - $iadService->migrateContainer($oldContainer, $newContainer, $options); Options explained ~~~~~~~~~~~~~~~~~ @@ -98,4 +109,3 @@ Options explained +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ | ``write.batchLimit`` | Once each file has been retrieved from the API, a PUT request is executed against the new container. Similar to above, these PUT requests are batched - and this number refers to the amount of PUT requests batched together. | 100 | +------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------+ - diff --git a/doc/services/object-store/objects.rst b/doc/services/object-store/objects.rst new file mode 100644 index 000000000..e38e0eb8b --- /dev/null +++ b/doc/services/object-store/objects.rst @@ -0,0 +1,427 @@ +Objects +======= + +Setup +----- + +In order to interact with this feature, you must first retrieve a particular +container using its unique name: + +.. code-block:: php + + $container = $service->getContainer('{containerName}'); + + +Create an object +---------------- + +There are three ways to upload a new file, each of which has different +business needs. + +.. note:: + + Unlike previous versions, you do not need to manually specify your object's + content type. The API will do this for you. + +.. note:: + + When working with names that contain non-standard alphanumerical characters + (such as spaces or non-English characters), you must ensure they are encoded + with `urlencode `_ before passing them in. + +Upload a single file (under 5GB) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The simplest way to upload a local object, without additional metadata, is by +its path: + +.. code-block:: php + + $container->uploadObject('example.txt', fopen('/path/to/file.txt', 'r+')); + + +The resource handle will be automatically closed by Guzzle in its destructor, +so there is no need to execute ``fclose``. + + +Upload a single file (under 5GB) with metadata +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Although the previous section handles most use cases, there are times when you +want greater control over what is being uploaded. For example, you might want +to control the object's metadata, or supply additional HTTP headers to coerce +browsers to handle the download a certain way. To add metadata to a new object: + +.. code-block:: php + + use OpenCloud\ObjectStore\Resource\DataObject; + + // specify optional metadata + $metadata = array( + 'Author' => 'Camera Obscura', + 'Origin' => 'Glasgow', + ); + + // specify optional HTTP headers + $httpHeaders = array( + 'Content-Type' => 'application/json', + ); + + // merge the two + $allHeaders = array_merge(DataObject::stockHeaders($metadata), $httpHeaders); + + // upload as usual + $container->uploadObject('example.txt', fopen('/path/to/file.txt', 'r+'), $allHeaders); + + +As you will notice, the first argument to ``uploadObject`` is the remote object +name, i.e. the name it will be uploaded as. The second argument is either a +file handle resource, or a string representation of object content (a temporary +resource will be created in memory), and the third is an array of additional +headers. + + +Batch upload multiple files (each under 5GB) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + $files = array( + array( + 'name' => 'apache.log', + 'path' => '/etc/httpd/logs/error_log' + ), + array( + 'name' => 'mysql.log', + 'body' => fopen('/tmp/mysql.log', 'r+') + ), + array( + 'name' => 'to_do_list.txt', + 'body' => 'PHONE HOME' + ) + ); + + $container->uploadObjects($files); + +As you can see, the ``name`` key is required for every file. You must +also specify *either* a path key (to an existing file), or a ``body``. +The ``body`` can either be a PHP resource or a string representation of +the content you want to upload. + + +Upload large files (over 5GB) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For files over 5GB, you will need to use the +``OpenCloud\ObjectStore\Upload\TransferBuilder`` factory to build and execute your +transfer. For your convenience, the Container resource object contains a simple +method to do this heavy lifting for you: + +.. code-block:: php + + $transfer = $container->setupObjectTransfer(array( + 'name' => 'video.mov', + 'path' => '/home/user/video.mov', + 'metadata' => array('Author' => 'Jamie'), + 'concurrency' => 4, + 'partSize' => 1.5 * Size::GB + )); + + $transfer->upload(); + + +You can specify how many concurrent cURL connections are used to upload +parts of your file. The file is fragmented into chunks, each of which is +uploaded individually as a separate file (the filename of each part will +indicate that it's a segment rather than the full file). After all parts +are uploaded, a manifestfile is uploaded. When the end-user accesses the 5GB +by its true filename, it actually references the manifest file which +concatenates each segment into a streaming download. + +In Swift terminology, the name for this process is *Dynamic Large Object (DLO)*. +To find out more details, please consult the `official documentation +`_. + + +List objects in a container +--------------------------- + +To return a list of objects: + +.. code-block:: php + + $files = $container->objectList(); + + foreach ($files as $file) { + /** @var $file OpenCloud\ObjectStore\Resource\DataObject */ + } + +By default, 10,000 objects are returned as a maximum. To get around +this, you can construct a query which refines your result set. For a +full specification of query parameters relating to collection filtering, +see the `official +docs `__. + +.. code-block:: php + + $container->objectList(array('prefix' => 'logFile_')); + + +Get object +---------- + +To retrieve a specific file from Cloud Files: + +.. code-block:: php + + /** @var $file OpenCloud\ObjectStore\Resource\DataObject */ + $file = $container->getObject('summer_vacation.mp4'); + +Once you have access to this ``OpenCloud\ObjectStore\Resource\DataObject`` +object, you can access these attributes: + +Get object's parent container +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + /** @param $container OpenCloud\ObjectStore\Resource\Container */ + $container = $object->getContainer(); + + +Get file name +~~~~~~~~~~~~~ + +.. code-block:: php + + /** @param $container OpenCloud\ObjectStore\Resource\Container */ + $container = $object->getContainer(); + + +Get file size +~~~~~~~~~~~~~ + +.. code-block:: php + + /** @param $size int */ + $size = $object->getContentLength(); + + +Get content of file +~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + /** @param $content Guzzle\Http\EntityBody */ + $content = $object->getContainer(); + + +Get type of file +~~~~~~~~~~~~~~~~ + +.. code-block:: php + + /** @param $type string */ + $type = $object->getContentType(); + + +Get file checksum +~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + /** @param $etag string */ + $etag = $object->getEtag(); + + +Get last modified date of file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: php + + /** @param $lastModified string */ + $lastModified = $object->getLastModified(); + + +Conditional requests +~~~~~~~~~~~~~~~~~~~~ + +You can also perform conditional requests according to `RFC 2616 +specification `__ (§§ 14.24-26). +Supported headers are ``If-Match``, ``If-None-Match``, +``If-Modified-Since`` and ``If-Unmodified-Since``. + +So, to retrieve a file's contents only if it's been recently changed + +.. code-block:: php + + $file = $container->getObject('error_log.txt', array( + 'If-Modified-Since' => 'Tue, 15 Nov 1994 08:12:31 GMT' + )); + + if ($file->getContentLength()) { + echo 'Has been changed since the above date'; + } else { + echo 'Has not been changed'; + } + +Retrieve a file only if it has NOT been modified (and expect a 412 on +failure): + +.. code-block:: php + + use Guzzle\Http\Exception\ClientErrorResponseException; + + try { + $oldImmutableFile = $container->getObject('payroll_2001.xlsx', array( + 'If-Unmodified-Since' => 'Mon, 31 Dec 2001 23:00:00 GMT' + )); + } catch (ClientErrorResponseException $e) { + echo 'This file has been modified...'; + } + +Finally, you can specify a range - which will return a subset of bytes +from the file specified. To return the last 20B of a file: + +.. code-block:: php + + $snippet = $container->getObject('output.log', array('range' => 'bytes=-20')); + + +Update an existing object +------------------------- + +.. code-block:: php + + $file->setContent(fopen('/path/to/new/content', 'r+')); + $file->update(); + +Bear in mind that updating a file name will result in a new file being +generated (under the new name). You will need to delete the old file. + + +Copy object to new location +--------------------------- + +To copy a file to another location, you need to specify a string-based +destination path: + +.. code-block:: php + + $object->copy('/container_2/new_object_name'); + +Where ``container_2`` is the name of the container, and ``new_object_name`` is +the name of the object inside the container that does not exist yet. + + +Get object metadata +------------------- + +You can fetch just the object metadata without fetching the full +content: + +.. code-block:: php + + $container->getPartialObject('summer_vacation.mp4'); + + +In order to access the metadata on a partial or complete object, use: + +.. code-block:: php + + $object->getMetadata(); + + +You can turn a partial object into a full object to get the content +after looking at the metadata: + +.. code-block:: php + + $object->refresh(); + + +You can also update to get the latest metadata: + +.. code-block:: php + + $object->retrieveMetadata(); + + +Update object metadata +---------------------- + +Similarly, with setting metadata there are two options: you can update +the metadata values of the local object (i.e. no HTTP request) if you +anticipate you'll be executing one soon (an update operation for +example): + +.. code-block:: php + + // There's no need to execute a HTTP request, because we'll soon do one anyway for the update operation + $object->setMetadata(array( + 'Author' => 'Hemingway' + )); + + // ... code here + + $object->update(); + +Alternatively, you can update the API straight away - so that everything +is retained: + +.. code-block:: php + + $object->saveMetadata(array( + 'Author' => 'Hemingway' + )); + +Please be aware that these methods override and wipe existing values. If +you want to append values to your metadata, use the correct method: + +.. code-block:: php + + $metadata = $object->appendToMetadata(array( + 'Author' => 'Hemingway' + )); + + $object->saveMetadata($metadata); + + +Extract archive +--------------- + +CloudFiles provides you the ability to extract uploaded archives to +particular destinations. The archive will be extracted and its contents +will populate the particular area specified. To upload file (which might +represent a directory structure) into a particular container: + +.. code-block:: php + + use OpenCloud\ObjectStore\Constants\UrlType; + + $service->bulkExtract('container_1', fopen('/home/jamie/files.tar.gz','r'), UrlType::TAR_GZ); + +You can also omit the container name (i.e. provide an empty string as +the first argument). If you do this, the API will create the containers +necessary to house the extracted files - this is done based on the +filenames inside the archive. + + +Delete object +------------- + +.. code-block:: php + + $object->delete(); + + +Delete multiple objects +----------------------- + +Bulk delete a set of paths: + +.. code-block:: php + + $pathsToBeDeleted = array('/container_1/old_file', '/container_2/notes.txt', '/container_1/older_file.log'); + + $service->bulkDelete($pathsToBeDeleted); diff --git a/doc/services/object-store/rs-only.rst b/doc/services/object-store/rs-only.rst new file mode 100644 index 000000000..fab4e423f --- /dev/null +++ b/doc/services/object-store/rs-only.rst @@ -0,0 +1,3 @@ +.. note:: + + This feature is only available to Rackspace users. From b869d8fbbd445d60d45763b70d541161d739307e Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 15:29:57 +0100 Subject: [PATCH 131/181] Modify toctree --- doc/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/index.rst b/doc/index.rst index 45c453a40..9c06b86e8 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -10,7 +10,7 @@ Contents: .. toctree:: :glob: - :maxdepth: 2 + :maxdepth: 1 services/**/index From f441dd6da5bdd7e461a6fd9f0a20708983ef42cb Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 17:58:16 +0100 Subject: [PATCH 132/181] Add orchestration docs --- doc/services/orchestration/README.md.rst | 98 --- doc/services/orchestration/USERGUIDE.md.rst | 672 ------------------ doc/services/orchestration/build-info.rst | 15 + doc/services/orchestration/events.rst | 53 ++ doc/services/orchestration/index.rst | 50 ++ doc/services/orchestration/resource-types.rst | 48 ++ doc/services/orchestration/resources.rst | 50 ++ doc/services/orchestration/stacks.rst | 299 ++++++++ doc/services/orchestration/templates.rst | 55 ++ 9 files changed, 570 insertions(+), 770 deletions(-) delete mode 100644 doc/services/orchestration/README.md.rst delete mode 100644 doc/services/orchestration/USERGUIDE.md.rst create mode 100644 doc/services/orchestration/build-info.rst create mode 100644 doc/services/orchestration/events.rst create mode 100644 doc/services/orchestration/resource-types.rst create mode 100644 doc/services/orchestration/resources.rst create mode 100644 doc/services/orchestration/stacks.rst create mode 100644 doc/services/orchestration/templates.rst diff --git a/doc/services/orchestration/README.md.rst b/doc/services/orchestration/README.md.rst deleted file mode 100644 index 1a983d187..000000000 --- a/doc/services/orchestration/README.md.rst +++ /dev/null @@ -1,98 +0,0 @@ -Orchestration -============= - -**Orchestration** is a service that can be used to create and manage -cloud resources. Examples of such resources are databases, load -balancers, servers and software installed on them. - -Concepts --------- - -To use the Orchestration service effectively, you should understand -several key concepts: - -- **Template**: An Orchestration template is a JSON or YAML document - that describes how a set of resources should be assembled to produce - a working deployment. The template specifies what resources should be - used, what attributes of these resources are parameterized and what - information is output to the user when a template is instantiated. - -- **Resource**: A resource is a template artifact that represents some - component of your desired architecture (a Cloud Server, a group of - scaled Cloud Servers, a load balancer, some configuration management - system, and so forth). - -- **Stack**: A stack is a running instance of a template. When a stack - is created, the resources specified in the template are created. - -Getting started ---------------- - -1. Instantiate an OpenStack or Rackspace client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To use the Orchestration service, you must first instantiate a -``OpenStack`` or ``Rackspace`` client object. - -- If you are working with an OpenStack cloud, instantiate an - ``OpenCloud\OpenStack`` client as follows: - - .. code:: php - - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - -- If you are working with the Rackspace cloud, instantiate a - ``OpenCloud\Rackspace`` client as follows: - - .. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -2. Obtain an Orchestration service object from the client. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -All Orchestration operations are done via an *orchestration service -object*. To instantiate this object, call the ``orchestrationService`` -method on the ``$client`` object as shown in the following example: - -.. code:: php - - $region = ''; - $orchestrationService = $client->orchestrationService(null, $region); - -Any stacks and resources created with this ``$orchestrationService`` -instance will be stored in the cloud region specified by ``$region``. - -3. Create a stack from a template. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. code:: php - - $stack = $orchestrationService->createStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - -[ `Get the executable PHP script for this -example `__ ] - -Next steps ----------- - -Once you have created a stack, there is more you can do with it. See -`complete user guide for orchestration `__. diff --git a/doc/services/orchestration/USERGUIDE.md.rst b/doc/services/orchestration/USERGUIDE.md.rst deleted file mode 100644 index 98bd51db7..000000000 --- a/doc/services/orchestration/USERGUIDE.md.rst +++ /dev/null @@ -1,672 +0,0 @@ -Complete User Guide for the Orchestration Service -================================================= - -Orchestration is a service that you can use to create and manage cloud -resources such as databases, load balancers, and servers, and the -software installed on servers. - -Table of Contents ------------------ - -- `Concepts <#concepts>`__ -- `Prerequisites <#prerequisites>`__ -- `Client <#client>`__ -- `Orchestration service <#orchestration-service>`__ -- `Templates <#templates>`__ -- `Validate template <#validate-template>`__ - - - `Validate a template from a - file <#validate-a-template-from-a-file>`__ - - `Validate Template from URL <#validate-template-from-url>`__ - -- `Stacks <#stacks>`__ -- `Preview stack <#preview-stack>`__ - - - `Preview a stack from a template - file <#preview-a-stack-from-a-template-file>`__ - - `Preview a stack from a template - URL <#preview-a-stack-from-a-template-url>`__ - -- `Create stack <#create-stack>`__ - - - `Create a stack from a template - file <#create-a-stack-from-a-template-file>`__ - - `Create a stack from a template - URL <#create-a-stack-from-a-template-url>`__ - -- `List stacks <#list-stacks>`__ -- `Get stack <#get-stack>`__ -- `Get stack template <#get-stack-template>`__ -- `Update stack <#update-stack>`__ - - - `Update a stack from a template - file <#update-a-stack-from-a-template-file>`__ - - `Update Stack from Template - URL <#update-stack-from-template-url>`__ - -- `Delete stack <#delete-stack>`__ -- `Abandon Stack <#abandon-stack>`__ -- `Adopt stack <#adopt-stack>`__ -- `Stack resources <#stack-resources>`__ -- `List stack resources <#list-stack-resources>`__ -- `Get stack resource <#get-stack-resource>`__ -- `Get stack resource metadata <#get-stack-resource-metadata>`__ -- `Stack resource events <#stack-resource-events>`__ -- `List stack events <#list-stack-events>`__ -- `List stack resource events <#list-stack-resource-events>`__ -- `Get stack resource event <#get-stack-resource-event>`__ -- `Resource types <#resource-types>`__ -- `List resource types <#list-resource-types>`__ -- `Get resource type <#get-resource-type>`__ -- `Get resource type template <#get-resource-type-template>`__ -- `Build info <#build-info>`__ -- `Get build info <#get-build-info>`__ - -Concepts --------- - -To use the Orchestration service effectively, you should understand the -following key concepts: - -- **Template**: A JSON or YAML document that describes how a set of - resources should be assembled to produce a working deployment. The - template specifies the resources to use, the attributes of these - resources that are parameterized and the information that is sent to - the user when a template is instantiated. - -- **Resource**: Some component of your architecture (a cloud server, a - group of scaled cloud servers, a load balancer, some configuration - management system, and so on) that is defined in a template. - -- **Stack**: A running instance of a template. When a stack is created, - the resources specified in the template are created. - -Prerequisites -------------- - -Client -~~~~~~ - -To use the Orchestration service, you must first instantiate a -``OpenStack`` or ``Rackspace`` client object. - -- If you are working with an OpenStack cloud, instantiate an - ``OpenCloud\OpenStack`` client as follows: - - .. code:: php - - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - -- If you are working with the Rackspace cloud, instantiate a - ``OpenCloud\Rackspace`` client as follows: - - .. code:: php - - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - -Orchestration service -~~~~~~~~~~~~~~~~~~~~~ - -All Orchestration operations are done via an *orchestration service -object*. To instantiate this object, call the ``orchestrationService`` -method on the ``$client`` object. This method takes two arguments: - -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+--------------------------+ -| Position | Description | Data type | Required? | Default value | Example value | -+============+=============================================================+=============+=============+====================================================+==========================+ -| 1 | Name of the service, as it appears in the service catalog | String | No | ``null``; automatically determined when possible | ``cloudOrchestration`` | -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+--------------------------+ -| 2 | Cloud region | String | Yes | - | ``DFW`` | -+------------+-------------------------------------------------------------+-------------+-------------+----------------------------------------------------+--------------------------+ - -.. code:: php - - $region = ''; - $orchestrationService = $client->orchestrationService(null, $region); - -Any stacks and resources created with this ``$orchestrationService`` -instance will be stored in the cloud region specified by ``$region``. - -Templates ---------- - -An Orchestration template is a JSON or YAML document that describes how -a set of resources should be assembled to produce a working deployment -(known as a `stack <#stacks>`__). The template specifies the resources -to use, the attributes of these resources that are parameterized and the -information that is sent to the user when a template is instantiated. - -Validate template -~~~~~~~~~~~~~~~~~ - -Before you use a template to create a stack, you might want to validate -it. - -Validate a template from a file -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored on your local computer as a JSON or YAML -file, you can validate it as shown in the following example: - -.. code:: php - - use OpenCloud\Common\Exceptions\InvalidTemplateError; - - try { - $orchestrationService->validateTemplate(array( - 'template' => file_get_contents(__DIR__ . '/lamp.yaml') - )); - } catch (InvalidTemplateError $e) { - // Use $e->getMessage() for explanation of why template is invalid - } - -[ `Get the executable PHP script for this -example `__ -] - -Validate Template from URL -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored as a JSON or YAML file in a remote location -accessible via HTTP or HTTPS, you can validate it as shown in the -following example: - -.. code:: php - - use OpenCloud\Common\Exceptions\InvalidTemplateError; - - try { - $orchestrationService->validateTemplate(array( - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml' - )); - } catch (InvalidTemplateError $e) { - // Use $e->getMessage() for explanation of why template is invalid - } - -[ `Get the executable PHP script for this -example `__ -] - -Stacks ------- - -A stack is a running instance of a template. When a stack is created, -the `resources <#stack-resources>`__ specified in the template are -created. - -Preview stack -~~~~~~~~~~~~~ - -Before you create a stack from a template, you might want to see what -that stack will look like. This is called *previewing the stack*. - -This operation takes one parameter, an associative array, with the -following keys: - -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+===================+=====================================================================================================================================================================================================================+=========================================================================================================================+=======================================+=================+=================================================================================================+ -| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters | Yes | - | ``simple-lamp-setup`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``templateUrl`` | URL of the template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``parameters`` | Arguments to the template, based on the template's parameters. For example, see the parameters in `this template section `__ | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ - -Preview a stack from a template file -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored on your local computer as a JSON or YAML -file, you can use it to preview a stack as shown in the following -example: - -.. code:: php - - $stack = $orchestrationService->previewStack(array( - 'name' => 'simple-lamp-setup', - 'template' => file_get_contents(__DIR__ . '/lamp.yml'), - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ) - )); - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - -[ `Get the executable PHP script for this -example `__ -] - -Preview a stack from a template URL -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored as a JSON or YAML file in a remote location -accessible via HTTP or HTTPS, you can use it to preview a stack as shown -in the following example: - -.. code:: php - - $stack = $orchestrationService->previewStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ) - )); - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - -[ `Get the executable PHP script for this -example `__ -] - -Create stack -~~~~~~~~~~~~ - -You can create a stack from a template. - -This operation takes one parameter, an associative array, with the -following keys: - -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+===================+====================================================================+==========================================================================================================================+=======================================+=================+=================================================================================================+ -| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters. | Yes | - | ``simple-lamp-setup`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('server_hostname' => 'web01')`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``timeoutMins`` | Duration, in minutes, after which stack creation should time out | Integer | Yes | - | 5 | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ - -Create a stack from a template file -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored on your local computer as a JSON or YAML -file, you can use it to create a stack as shown in the following -example: - -.. code:: php - - $stack = $orchestrationService->createStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - -[ `Get the executable PHP script for this -example `__ -] - -Create a stack from a template URL -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored as a JSON or YAML file in a remote location -accessible via HTTP or HTTPS, you can use it to create a stack as shown -in the following example: - -.. code:: php - - $stack = $orchestrationService->stack(); - $stack->create(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - -[ `Get the executable PHP script for this -example `__ ] - -List stacks -~~~~~~~~~~~ - -You can list all the stacks that you have created as shown in the -following example: - -.. code:: php - - $stacks = $orchestrationService->listStacks(); - foreach ($stacks as $stack) { - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Get stack -~~~~~~~~~ - -You can retrieve a specific stack using its name, as shown in the -following example: - -.. code:: php - - $stack = $orchestrationService->getStack('simple-lamp-setup'); - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - -[ `Get the executable PHP script for this -example `__ ] - -Get stack template -~~~~~~~~~~~~~~~~~~ - -You can retrieve the template used to create a stack. Note that a JSON -string is returned, regardless of whether a JSON or YAML template was -used to create the stack. - -.. code:: php - - $stackTemplate = $stack->getTemplate(); - /** @var $stackTemplate string **/ - -[ `Get the executable PHP script for this -example `__ ] - -Update stack -~~~~~~~~~~~~ - -You can update a running stack. - -This operation takes one parameter, an associative array, with the -following keys: - -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+===================+==================================================================+=============================+=======================================+=================+=========================================================================================================+ -| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml`` | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| ``timeoutMins`` | Duration, in minutes, after which stack update should time out | Integer | Yes | - | 5 | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ - -Update a stack from a template file -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored on your local computer as a JSON or YAML -file, you can use it to update a stack as shown in the following -example: - -.. code:: php - - $stack->update(array( - 'template' => file_get_contents(__DIR__ . '/lamp-updated.yml'), - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - -[ `Get the executable PHP script for this -example `__ -] - -Update Stack from Template URL -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -If your template is stored as a JSON or YAML file in a remote location -accessible via HTTP or HTTPS, you can use it to update a stack as shown -in the following example: - -.. code:: php - - $stack->update(array( - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - -[ `Get the executable PHP script for this -example `__ ] - -Delete stack -~~~~~~~~~~~~ - -If you no longer need a stack and all its resources, you can delete the -stack *and* the resources as shown in the following example: - -.. code:: php - - $stack->delete(); - -[ `Get the executable PHP script for this -example `__ ] - -Abandon Stack -~~~~~~~~~~~~~ - -If you want to delete a stack but preserve all its resources, you can -abandon the stack as shown in the following example: - -.. code:: php - - $abandonStackData = $stack->abandon(); - /** @var $abandonStackData string **/ - - file_put_contents(__DIR__ . '/sample_adopt_stack_data.json', $abandonStackData); - -[ `Get the executable PHP script for this -example `__ ] - -Note that this operation returns data about the abandoned stack as a -string. You can use this data to recreate the stack by using the `adopt -stack <#adopt-stack>`__ operation. - -Adopt stack -~~~~~~~~~~~ - -If you have data from an abandoned stack, you can re-create the stack as -shown in the following example: - -.. code:: php - - $stack = $orchestrationService->adoptStack(array( - 'name' => 'simple-lamp-setup', - 'template' => file_get_contents(__DIR__ . '/lamp.yml'), - 'adoptStackData' => $abandonStackData, - 'timeoutMins' => 5 - )); - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - -[ `Get the executable PHP script for this -example `__ ] - -Stack resources ---------------- - -A stack is made up of zero or more resources such as databases, load -balancers, and servers, and the software installed on servers. - -List stack resources -~~~~~~~~~~~~~~~~~~~~ - -You can list all the resources for a stack as shown in the following -example: - -.. code:: php - - $resources = $stack->listResources(); - foreach ($resources as $resource) { - /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Get stack resource -~~~~~~~~~~~~~~~~~~ - -You can retrieve a specific resource in a stack bt using that resource's -name, as shown in the following example: - -.. code:: php - - $resource = $stack->getResource('load-balancer'); - /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ - -[ `Get the executable PHP script for this -example `__ ] - -Get stack resource metadata -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can retrieve the metadata for a specific resource in a stack as -shown in the following example: - -.. code:: php - - $resourceMetadata = $resource->getMetadata(); - /** @var $resourceMetadata \stdClass **/ - -[ `Get the executable PHP script for this -example `__ ] - -Stack resource events ---------------------- - -Operations on resources within a stack (such as the creation of a -resource) produce events. - -List stack events -~~~~~~~~~~~~~~~~~ - -You can list all of the events for all of the resources in a stack as -shown in the following example: - -.. code:: php - - $stackEvents = $stack->listEvents(); - foreach ($stackEvents as $stackEvent) { - /** @var $stackEvent OpenCloud\Orchestration\Resource\Event **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -List stack resource events -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can list all of the events for a specific resource in a stack as -shown in the following example: - -.. code:: php - - $resourceEvents = $resource->listEvents(); - foreach ($resourceEvents as $resourceEvent) { - /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Get stack resource event -~~~~~~~~~~~~~~~~~~~~~~~~ - -You can retrieve a specific event for a specific resource in a stack, by -using the resource event's ID, as shown in the following example: - -.. code:: php - - $resourceEvent = $resource->getEvent('c1342a0a-59e6-4413-9af5-07c9cae7d729'); - /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ - -[ `Get the executable PHP script for this -example `__ ] - -Resource types --------------- - -When you define a template, you must use resource types supported by -your cloud. - -List resource types -~~~~~~~~~~~~~~~~~~~ - -You can list all supported resource types as shown in the following -example: - -.. code:: php - - $resourceTypes = $orchestrationService->listResourceTypes(); - foreach ($resourceTypes as $resourceType) { - /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ - } - -[ `Get the executable PHP script for this -example `__ ] - -Get resource type -~~~~~~~~~~~~~~~~~ - -You can retrieve a specific resource type's schema as shown in the -following example: - -.. code:: php - - $resourceType = $orchestrationService->getResourceType('OS::Nova::Server'); - /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ - -[ `Get the executable PHP script for this -example `__ ] - -Get resource type template -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can retrieve a specific resource type's representation as it would -appear in a template, as shown in the following example: - -.. code:: php - - $resourceTypeTemplate = $resourceType->getTemplate(); - /** @var $resourceTypeTemplate string **/ - -[ `Get the executable PHP script for this -example `__ ] - -Build info ----------- - -Get build info -~~~~~~~~~~~~~~ - -You can retrieve information about the current Orchestration service -build as shown in the following example: - -.. code:: php - - $buildInfo = $orchestrationService->getBuildInfo(); - /** @var $resourceType OpenCloud\Orchestration\Resource\BuildInfo **/ - -[ `Get the executable PHP script for this -example `__ ] diff --git a/doc/services/orchestration/build-info.rst b/doc/services/orchestration/build-info.rst new file mode 100644 index 000000000..c30ce5cfa --- /dev/null +++ b/doc/services/orchestration/build-info.rst @@ -0,0 +1,15 @@ +Build info +========== + +Get build info +-------------- + +You can retrieve information about the current Orchestration service +build as shown in the following example: + +.. code-block:: php + + /** @var $resourceType OpenCloud\Orchestration\Resource\BuildInfo **/ + $buildInfo = $orchestrationService->getBuildInfo(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/events.rst b/doc/services/orchestration/events.rst new file mode 100644 index 000000000..68dbf611b --- /dev/null +++ b/doc/services/orchestration/events.rst @@ -0,0 +1,53 @@ +Stack resource events +===================== + +Operations on resources within a stack (such as the creation of a +resource) produce events. + + +List stack events +----------------- + +You can list all of the events for all of the resources in a stack as +shown in the following example: + +.. code-block:: php + + $stackEvents = $stack->listEvents(); + + foreach ($stackEvents as $stackEvent) { + /** @var $stackEvent OpenCloud\Orchestration\Resource\Event **/ + } + +`Get the executable PHP script for this example `_ + + +List stack resource events +-------------------------- + +You can list all of the events for a specific resource in a stack as +shown in the following example: + +.. code-block:: php + + $resourceEvents = $resource->listEvents(); + + foreach ($resourceEvents as $resourceEvent) { + /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ + } + +`Get the executable PHP script for this example `_ + + +Get stack resource event +------------------------ + +You can retrieve a specific event for a specific resource in a stack, by +using the resource event's ID, as shown in the following example: + +.. code-block:: php + + /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ + $resourceEvent = $resource->getEvent('c1342a0a-59e6-4413-9af5-07c9cae7d729'); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/index.rst b/doc/services/orchestration/index.rst index e69de29bb..0dce8ac43 100644 --- a/doc/services/orchestration/index.rst +++ b/doc/services/orchestration/index.rst @@ -0,0 +1,50 @@ +Orchestration v1 +================ + +Setup +----- + +.. include:: rs-client.sample.rst + +Now set up the Orchestration service: + +.. code-block:: php + + $service = $client->orchestrationService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + +.. toctree:: + + templates + stacks + resources + resource-types + build-info + + +Glossary +-------- + +.. glossary:: + + template + An Orchestration template is a JSON or YAML document + that describes how a set of resources should be assembled to produce + a working deployment. The template specifies what resources should be + used, what attributes of these resources are parameterized and what + information is output to the user when a template is instantiated. + + resource + A resource is a template artifact that represents some + component of your desired architecture (a Cloud Server, a group of + scaled Cloud Servers, a load balancer, some configuration management + system, and so forth). + + stack + A stack is a running instance of a template. When a stack + is created, the resources specified in the template are created. diff --git a/doc/services/orchestration/resource-types.rst b/doc/services/orchestration/resource-types.rst new file mode 100644 index 000000000..cd229d660 --- /dev/null +++ b/doc/services/orchestration/resource-types.rst @@ -0,0 +1,48 @@ +Resource types +============== + +When you define a template, you must use resource types supported by +your cloud. + +List resource types +------------------- + +You can list all supported resource types as shown in the following +example: + +.. code-block:: php + + $resourceTypes = $orchestrationService->listResourceTypes(); + foreach ($resourceTypes as $resourceType) { + /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ + } + +`Get the executable PHP script for this example `_ + + +Get resource type +----------------- + +You can retrieve a specific resource type's schema as shown in the +following example: + +.. code-block:: php + + /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ + $resourceType = $orchestrationService->getResourceType('OS::Nova::Server'); + +`Get the executable PHP script for this example `_ + + +Get resource type template +-------------------------- + +You can retrieve a specific resource type's representation as it would +appear in a template, as shown in the following example: + +.. code-block:: php + + /** @var $resourceTypeTemplate string **/ + $resourceTypeTemplate = $resourceType->getTemplate(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/resources.rst b/doc/services/orchestration/resources.rst new file mode 100644 index 000000000..049150f58 --- /dev/null +++ b/doc/services/orchestration/resources.rst @@ -0,0 +1,50 @@ +Stack resources +=============== + +A stack is made up of zero or more resources such as databases, load +balancers, and servers, and the software installed on servers. + + +List stack resources +-------------------- + +You can list all the resources for a stack as shown in the following +example: + +.. code-block:: php + + $resources = $stack->listResources(); + + foreach ($resources as $resource) { + /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ + } + +`Get the executable PHP script for this example `_ + + +Get stack resource +------------------ + +You can retrieve a specific resource in a stack bt using that resource's +name, as shown in the following example: + +.. code-block:: php + + /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ + $resource = $stack->getResource('load-balancer'); + +`Get the executable PHP script for this example `_ + + +Get stack resource metadata +--------------------------- + +You can retrieve the metadata for a specific resource in a stack as +shown in the following example: + +.. code-block:: php + + /** @var $resourceMetadata \stdClass **/ + $resourceMetadata = $resource->getMetadata(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/stacks.rst b/doc/services/orchestration/stacks.rst new file mode 100644 index 000000000..75a14cd4c --- /dev/null +++ b/doc/services/orchestration/stacks.rst @@ -0,0 +1,299 @@ +Stacks +====== + +A stack is a running instance of a template. When a stack is created, +the `resources <#stack-resources>`__ specified in the template are +created. + + +Preview stack +------------- + +Before you create a stack from a template, you might want to see what +that stack will look like. This is called *previewing the stack*. + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+=====================================================================================================================================================================================================================+=========================================================================================================================+=======================================+=================+=================================================================================================+ +| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters | Yes | - | ``simple-lamp-setup`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of the template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters. For example, see the parameters in `this template section `__ | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ + +Preview a stack from a template file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to preview a stack as shown in the following +example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->previewStack(array( + 'name' => 'simple-lamp-setup', + 'template' => file_get_contents(__DIR__ . '/lamp.yml'), + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ) + )); + +`Get the executable PHP script for this example `_ + + +Preview a stack from a template URL +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to preview a stack as shown +in the following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->previewStack(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ) + )); + +`Get the executable PHP script for this example `_ + + +Create stack +------------ + +You can create a stack from a template. This operation takes one parameter, an +associative array, with the following keys: + ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+====================================================================+==========================================================================================================================+=======================================+=================+=================================================================================================+ +| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters. | Yes | - | ``simple-lamp-setup`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('server_hostname' => 'web01')`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``timeoutMins`` | Duration, in minutes, after which stack creation should time out | Integer | Yes | - | 5 | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ + +Create a stack from a template file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to create a stack as shown in the following +example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->createStack(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + + +Create a stack from a template URL +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to create a stack as shown +in the following example: + +.. code-block:: php + + $stack = $orchestrationService->stack(); + $stack->create(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + +List stacks +----------- + +You can list all the stacks that you have created as shown in the +following example: + +.. code-block:: php + + $stacks = $orchestrationService->listStacks(); + foreach ($stacks as $stack) { + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + } + +`Get the executable PHP script for this example `_ + + +Get stack +--------- + +You can retrieve a specific stack using its name, as shown in the +following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->getStack('simple-lamp-setup'); + +`Get the executable PHP script for this example `_ + + +Get stack template +------------------ + +You can retrieve the template used to create a stack. Note that a JSON +string is returned, regardless of whether a JSON or YAML template was +used to create the stack. + +.. code-block:: php + + /** @var $stackTemplate string **/ + $stackTemplate = $stack->getTemplate(); + +`Get the executable PHP script for this example `_ + + +Update stack +------------ + +You can update a running stack. + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+==================================================================+=============================+=======================================+=================+=========================================================================================================+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``timeoutMins`` | Duration, in minutes, after which stack update should time out | Integer | Yes | - | 5 | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ + + +Update a stack from a template file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to update a stack as shown in the following +example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack->update(array( + 'template' => file_get_contents(__DIR__ . '/lamp-updated.yml'), + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + + +Update Stack from Template URL +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to update a stack as shown +in the following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack->update(array( + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + + +Delete stack +------------ + +If you no longer need a stack and all its resources, you can delete the +stack *and* the resources as shown in the following example: + +.. code-block:: php + + $stack->delete(); + +`Get the executable PHP script for this example `_ + + +Abandon Stack +------------- + +.. note:: + + This operation returns data about the abandoned stack as a string. You can + use this data to recreate the stack by using the `adopt stack <#adopt-stack>`_ + operation. + +If you want to delete a stack but preserve all its resources, you can +abandon the stack as shown in the following example: + +.. code-block:: php + + /** @var $abandonStackData string **/ + $abandonStackData = $stack->abandon(); + file_put_contents(__DIR__ . '/sample_adopt_stack_data.json', $abandonStackData); + +`Get the executable PHP script for this example `_ + + +Adopt stack +----------- + +If you have data from an abandoned stack, you can re-create the stack as +shown in the following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->adoptStack(array( + 'name' => 'simple-lamp-setup', + 'template' => file_get_contents(__DIR__ . '/lamp.yml'), + 'adoptStackData' => $abandonStackData, + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/templates.rst b/doc/services/orchestration/templates.rst new file mode 100644 index 000000000..5eca2519d --- /dev/null +++ b/doc/services/orchestration/templates.rst @@ -0,0 +1,55 @@ +Templates +========= + +An Orchestration template is a JSON or YAML document that describes how +a set of resources should be assembled to produce a working deployment +(known as a `stack <#stacks>`__). The template specifies the resources +to use, the attributes of these resources that are parameterized and the +information that is sent to the user when a template is instantiated. + +Validating templates +-------------------- + +Before you use a template to create a stack, you might want to validate it. + + +Validate a template from a file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored on your local computer as a JSON or YAML +file, you can validate it as shown in the following example: + +.. code-block:: php + + use OpenCloud\Common\Exceptions\InvalidTemplateError; + + try { + $orchestrationService->validateTemplate(array( + 'template' => file_get_contents(__DIR__ . '/lamp.yaml') + )); + } catch (InvalidTemplateError $e) { + // Use $e->getMessage() for explanation of why template is invalid + } + +`Get the executable PHP script for this example `_ + +Validate Template from URL +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can validate it as shown in the +following example: + +.. code-block:: php + + use OpenCloud\Common\Exceptions\InvalidTemplateError; + + try { + $orchestrationService->validateTemplate(array( + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml' + )); + } catch (InvalidTemplateError $e) { + // Use $e->getMessage() for explanation of why template is invalid + } + +`Get the executable PHP script for this example `_ From 4cd5f9424c4c72571479b7c484715d83acc751e1 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Thu, 5 Mar 2015 19:12:57 +0100 Subject: [PATCH 133/181] Add Queues docs --- doc/services/queues/Queue.md.rst | 197 ------------- .../queues/{Claim.md.rst => claims.rst} | 115 +++----- doc/services/queues/index.rst | 48 +++ .../queues/{Message.md.rst => messages.rst} | 274 +++++++----------- doc/services/queues/queues.rst | 124 ++++++++ 5 files changed, 316 insertions(+), 442 deletions(-) delete mode 100644 doc/services/queues/Queue.md.rst rename doc/services/queues/{Claim.md.rst => claims.rst} (68%) rename doc/services/queues/{Message.md.rst => messages.rst} (52%) create mode 100644 doc/services/queues/queues.rst diff --git a/doc/services/queues/Queue.md.rst b/doc/services/queues/Queue.md.rst deleted file mode 100644 index 1fe9f7036..000000000 --- a/doc/services/queues/Queue.md.rst +++ /dev/null @@ -1,197 +0,0 @@ -1. Introduction ---------------- - -A Queue is an entity that holds messages. Ideally, a queue is created -per work type. For example, if you want to compress files, you would -create a queue dedicated to this job. Any application that reads from -this queue would only compress files. - -2. Setup --------- - -.. code:: php - - $service = $client->queuesService('cloudQueues', 'ORD'); - -3. Client IDs -------------- - -With most of Marconi's operation, you must specify a **Client ID** which -will be used as a unique identifier for the process accessing this -Queue. This is basically a UUID that must be unique to each client -accessing the API - it can be an arbitrary string. - -.. code:: php - - $service->setClientId(); - - echo $service->getClientId(); - -If you call ``setClientId`` without any parameters, a UUID is -automatically generated for you. - -4. List queues --------------- - -4.1 Description -~~~~~~~~~~~~~~~ - -This operation lists queues for the project. The queues are sorted -alphabetically by name. - -4.2 Parameters -~~~~~~~~~~~~~~ - -\|Name\|Style\|Type\|Description\| \|----\|-----\|----\|-----------\| -\|marker\|Query\|​String\|Specifies the name of the last queue received -in a previous request, or none to get the first page of results. -Optional.\| \|limit\|Query\|Integer\|Specifies the number of queues to -return. The default value for the number of queues returned is 10. If -you do not specify this parameter, the default number of queues is -returned. Optional.\| \|detailed\|Query\|​Boolean\|Determines whether -queue metadata is included in the response. The default value for this -parameter is false, which excludes the metadata. Optional.\| -\|----\|-----\|----\|-----------\| - -4.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - $queues = $service->listQueues(); - - while ($queue = $queues->next()) { - echo $queue->getName() . PHP_EOL; - } - -5. Create queue ---------------- - -5.1 Description -~~~~~~~~~~~~~~~ - -This operation creates a new queue. - -5.2 Parameters -~~~~~~~~~~~~~~ - -A string representation of the name for your new Queue. The name must -not exceed 64 bytes in length, and it is limited to US-ASCII letters, -digits, underscores, and hyphens. - -5.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - $queue = $service->createQueue('new_queue'); - -6. Retrieve queue ------------------ - -6.1 Description -~~~~~~~~~~~~~~~ - -Returns a ``Queue`` object for use. - -6.2 Parameters -~~~~~~~~~~~~~~ - -Queue name. - -6.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - $queue = $service->getQueue('new_queue'); - -7. Check queue existence ------------------------- - -7.1 Description -~~~~~~~~~~~~~~~ - -This operation verifies whether the specified queue exists by returning -``TRUE`` or ``FALSE``. - -7.2 Parameters -~~~~~~~~~~~~~~ - -7.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - if ($service->hasQueue('new_queue')) { - // do something - } - -8. Update queue metadata (permanently to the API) -------------------------------------------------- - -4.1 Description -~~~~~~~~~~~~~~~ - -This operation replaces any existing metadata document in its entirety. -Ensure that you do not accidentally overwrite existing metadata that you -want to retain. If you want to *append* metadata, ensure you merge a new -array to the existing values. - -4.2 Parameters -~~~~~~~~~~~~~~ - -Hash of key pairs. - -4.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - $queue->saveMetadata(array( - 'foo' => 'bar' - )); - -9. Retrieve the queue metadata (fresh from the API) ---------------------------------------------------- - -4.1 Description -~~~~~~~~~~~~~~~ - -This operation returns metadata, such as message TTL, for the queue. - -4.2 Parameters -~~~~~~~~~~~~~~ - -None. - -4.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - $metadata = $queue->retrieveMetadata(); - - print_r($metadata->toArray()); - -10. Get queue stats -------------------- - -4.1 Description -~~~~~~~~~~~~~~~ - -This operation returns queue statistics, including how many messages are -in the queue, categorized by status. - -4.2 Parameters -~~~~~~~~~~~~~~ - -None. - -4.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - $queue->getStats(); - diff --git a/doc/services/queues/Claim.md.rst b/doc/services/queues/claims.rst similarity index 68% rename from doc/services/queues/Claim.md.rst rename to doc/services/queues/claims.rst index 42161536d..7e375c8d3 100644 --- a/doc/services/queues/Claim.md.rst +++ b/doc/services/queues/claims.rst @@ -1,28 +1,18 @@ -1. Introduction ---------------- +Claims +====== -A **Claim** is the process of a worker checking out a message to perform -a task. Claiming a message prevents other workers from attempting to -process the same messages. +Setup +----- -2. Setup --------- +In order to work with messages, you must first retrieve a queue by its name: -A Claim is initialized on its parent object, a Queue: +.. code-block:: php -.. code:: php + $queue = $service->getQueue('{queueName}'); - // To initialize an empty object: - $claim = $queue->getClaim(); - // or retrieve a specific claim: - $claim = $queue->getClaim('51db7067821e727dc24df754'); - -3. Claim messages ------------------ - -3.1 Description -~~~~~~~~~~~~~~~ +Claim messages +-------------- This operation claims a set of messages (up to the value of the limit parameter) from oldest to newest and skips any messages that are already @@ -46,8 +36,8 @@ and whether a given message's claim is about to expire. When a claim expires, it is released. If the original worker failed to process the message, another client worker can then claim the message. -3.2 Attributes -~~~~~~~~~~~~~~ +Parameters +~~~~~~~~~~ The ``ttl`` attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and 43200 seconds @@ -67,46 +57,30 @@ The ``limit`` attribute specifies the number of messages to return, up to 20 messages. If limit is not specified, limit defaults to 10. The limit parameter is optional. -3.3 Code -~~~~~~~~ +.. code-block:: php -.. code:: php + use OpenCloud\Common\Constants\Datetime; - use OpenCloud\Common\Constants\Datetime; + $queue->claimMessages(array( + 'limit' => 15, + 'grace' => 5 * Datetime::MINUTE, + 'ttl' => 5 * Datetime::MINUTE + )); - $queue->claimMessages(array( - 'limit' => 15, - 'grace' => 5 * Datetime::MINUTE, - 'ttl' => 5 * Datetime::MINUTE - )); - -4. Query claim --------------- - -4.1 Description -~~~~~~~~~~~~~~~ - -This operation queries the specified claim for the specified queue. -Claims with malformed IDs or claims that are not found by ID are -ignored. -4.2 Attributes -~~~~~~~~~~~~~~ +Query claim +----------- -Claim ID. +This operation queries the specified claim for the specified queue. Claims with +malformed IDs or claims that are not found by ID are ignored. -4.3 Code -~~~~~~~~ +.. code-block:: php -.. code:: php + $claim = $queue->getClaim('{claimId}'); - $claim = $queue->getClaim('51db7067821e727dc24df754'); -5. Update claim ---------------- - -5.1 Description -~~~~~~~~~~~~~~~ +Update claim +------------ This operation updates the specified claim for the specified queue. Claims with malformed IDs or claims that are not found by ID are @@ -118,27 +92,17 @@ renew a claim by executing this method on a specific **Claim** and including a new TTL. The API will then reset the age of the claim and apply the new TTL. -5.2 Attributes -~~~~~~~~~~~~~~ - -See section 4.2. - -5.3 Code -~~~~~~~~ - -.. code:: php +.. code-block:: php - use OpenCloud\Common\Constants\Datetime; + use OpenCloud\Common\Constants\Datetime; - $claim->update(array( - 'ttl' => 10 * Datetime::MINUTE - )); + $claim->update(array( + 'ttl' => 10 * Datetime::MINUTE + )); -6. Release claim ----------------- -6.1 Description -~~~~~~~~~~~~~~~ +Release claim +------------- This operation immediately releases a claim, making any remaining undeleted messages that are associated with the claim available to other @@ -150,15 +114,6 @@ shutdown, fails to process one or more messages, or is taking longer than expected to process messages, and wants to make the remainder of the messages available to other workers. -6.2 Attributes -~~~~~~~~~~~~~~ - -See section 4.2. - -6.3 Code -~~~~~~~~ - -.. code:: php - - $message->delete(); +.. code-block:: php + $message->delete(); diff --git a/doc/services/queues/index.rst b/doc/services/queues/index.rst index e69de29bb..e37845d76 100644 --- a/doc/services/queues/index.rst +++ b/doc/services/queues/index.rst @@ -0,0 +1,48 @@ +Queues v1 +========= + +Setup +----- + +.. include:: ../common/rs-client.sample.rst + +Now to instantiate the Queues service: + +.. code-block:: php + + $service = $client->queuesService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + +.. toctree:: + + queues + messages + claims + + +Glossary +-------- + +.. glossary:: + + claim + A Claim is the process of a worker checking out a message to perform + a task. Claiming a message prevents other workers from attempting to + process the same messages. + + queue + A Queue is an entity that holds messages. Ideally, a queue is created + per work type. For example, if you want to compress files, you would + create a queue dedicated to this job. Any application that reads from + this queue would only compress files. + + message + A Message is a task, a notification, or any meaningful data that a + producer or publisher sends to the queue. A message exists until it is + deleted by a recipient or automatically by the system based on a TTL + (time-to-live) value. diff --git a/doc/services/queues/Message.md.rst b/doc/services/queues/messages.rst similarity index 52% rename from doc/services/queues/Message.md.rst rename to doc/services/queues/messages.rst index ca67e22bb..ea23caea3 100644 --- a/doc/services/queues/Message.md.rst +++ b/doc/services/queues/messages.rst @@ -1,29 +1,18 @@ -1. Introduction ---------------- +Messages +======== -A **Message** is a task, a notification, or any meaningful data that a -producer or publisher sends to the queue. A message exists until it is -deleted by a recipient or automatically by the system based on a TTL -(time-to-live) value. +Setup +----- -2. Setup --------- +In order to work with messages, you must first retrieve a queue by its name: -A message is initialized from its parent object, a Queue: +.. code-block:: php -.. code:: php + $queue = $service->getQueue('{queueName}'); - // Setup an empty object - $message = $queue->getMessage(); - // or retrieve an existing one - $message = $queue->getMessage(''); - -3. Post message ---------------- - -3.1 Description -~~~~~~~~~~~~~~~ +Post new message +---------------- This operation posts the specified message or messages. You can submit up to 10 messages in a single request. @@ -31,73 +20,67 @@ up to 10 messages in a single request. When posting new messages, you specify only the ``body`` and ``ttl`` for the message. The API will insert metadata, such as ID and age. -3.2 Parameters -~~~~~~~~~~~~~~ - How you pass through the array structure depends on whether you are -executing multiple (3.3.2) or single (3.3.3) posts, but the keys are the -same. +executing multiple or single posts, but the keys are the +same: -The ``body`` attribute specifies an arbitrary document that constitutes -the body of the message being sent. The size of this body is limited to -256 KB, excluding whitespace. +* The ``body`` attribute specifies an arbitrary document that constitutes + the body of the message being sent. The size of this body is limited to + 256 KB, excluding whitespace. -The ``ttl`` attribute specifies how long the server waits before marking -the message as expired and removing it from the queue. The value of ttl -must be between 60 and 1209600 seconds (14 days). Note that the server -might not actually delete the message until its age has reached up to -(ttl + 60) seconds, to allow for flexibility in storage implementations. +* The ``ttl`` attribute specifies how long the server waits before marking + the message as expired and removing it from the queue. The value of ttl + must be between 60 and 1209600 seconds (14 days). Note that the server + might not actually delete the message until its age has reached up to + (ttl + 60) seconds, to allow for flexibility in storage implementations. -3.3 Code samples -~~~~~~~~~~~~~~~~ -3.3.1 Posting a single message -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Posting a single message +~~~~~~~~~~~~~~~~~~~~~~~~ -:: +.. code-block:: php - use OpenCloud\Common\Constants\Datetime; + use OpenCloud\Common\Constants\Datetime; - $queue->createMessage(array( - 'body' => (object) array( - 'event' => 'BackupStarted', - 'deadline' => '26.12.2013 - ), - 'ttl' => 2 * Datetime::DAY - )); + $queue->createMessage(array( + 'body' => (object) array( + 'event' => 'BackupStarted', + 'deadline' => '26.12.2013', + ), + 'ttl' => 2 * Datetime::DAY + )); -3.3.2 Post a batch of messages -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Post a batch of messages +~~~~~~~~~~~~~~~~~~~~~~~~ Please note that the list of messages will be truncated at 10. For more, please execute another method call. -.. code:: php +.. code-block:: php - use OpenCloud\Common\Constants\Datetime; + use OpenCloud\Common\Constants\Datetime; - $messages = array( - array( - 'body' => (object) array( - 'play' => 'football' - ), - 'ttl' => 2 * Datetime::DAY - ), - array( - 'body' => (object) array( - 'play' => 'tennis' - ), - 'ttl' => 50 * Datetime::HOUR - ) - ); + $messages = array( + array( + 'body' => (object) array( + 'play' => 'football' + ), + 'ttl' => 2 * Datetime::DAY + ), + array( + 'body' => (object) array( + 'play' => 'tennis' + ), + 'ttl' => 50 * Datetime::HOUR + ) + ); - $queue->createMessages($messages); + $queue->createMessages($messages); -4. Get messages ---------------- -4.1 Description -~~~~~~~~~~~~~~~ +Get messages +------------ This operation gets the message or messages in the specified queue. @@ -109,10 +92,11 @@ variety of storage driver implementations. Results are ordered by age, oldest message first. -4.2 Parameters -~~~~~~~~~~~~~~ -A hash of options. +Parameters +~~~~~~~~~~ + +When retrieving messages, you can filter using these options: +--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Name | Style | Type | Description | @@ -123,135 +107,95 @@ A hash of options. +--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | echo | Query | Boolean | Determines whether the API returns a client's own messages. The echo parameter is a Boolean value (true or false) that determines whether the API returns a client's own messages, as determined by the uuid portion of the User-Agent header. If you do not specify a value, echo uses the default value of false. If you are experimenting with the API, you might want to set echo=true in order to see the messages that you posted. The echo parameter is optional. | +--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -| include\_claimed | Query | ​Boolean | Determines whether the API returns claimed messages and unclaimed messages. The include\_claimed parameter is a Boolean value (true or false) that determines whether the API returns claimed messages and unclaimed messages. If you do not specify a value, include\_claimed uses the default value of false (only unclaimed messages are returned). Optional. | +| include_claimed | Query | ​Boolean | Determines whether the API returns claimed messages and unclaimed messages. The include\_claimed parameter is a Boolean value (true or false) that determines whether the API returns claimed messages and unclaimed messages. If you do not specify a value, include\_claimed uses the default value of false (only unclaimed messages are returned). Optional. | +--------------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ -4.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php +.. code-block:: php - $messages = $queue->listMessages(array( - 'marker' => '51db6f78c508f17ddc924357', - 'limit' => 20, - 'echo' => true - )); + $messages = $queue->listMessages(array( + 'marker' => '51db6f78c508f17ddc924357', + 'limit' => 20, + 'echo' => true + )); - while ($message = $messages->next()) { - echo $message->getId() . PHP_EOL; - } + foreach ($messages as $message) { + echo $message->getId() . PHP_EOL; + } -5. Get a set of messages by ID ------------------------------- -5.1 Description -~~~~~~~~~~~~~~~ +Get a set of messages by ID +--------------------------- This operation provides a more efficient way to query multiple messages compared to using a series of individual GET. Note that the list of IDs cannot exceed 20. If a malformed ID or a nonexistent message ID is provided, it is ignored, and the remaining messages are returned. -5.2 Parameters -~~~~~~~~~~~~~~ - -A hash of options. +Parameters +~~~~~~~~~~ -\|Name\|Style\|Type\|Description\| \|----\|-----\|----\|-----------\| -\|ids\|Query\|String\|Specifies the IDs of the messages to get. Format -multiple message ID values by separating them with commas -(comma-separated). Optional.\| \|claim\_id\|Query\|​String\|Specifies -the claim ID with which the message is associated. Optional.\| -\|----\|-----\|----\|-----------\| ++------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------+ +| Name | Style | Type | Description | ++============+=========+============+========================================================================================================================================+ +| ids | Query | String | Specifies the IDs of the messages to get. Format multiple message ID values by separating them with commas (comma-separated). Optional | ++------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------+ +| claim_id | Query | ​Boolean | Specifies the claim ID with which the message is associated. Optional. | ++------------+---------+------------+----------------------------------------------------------------------------------------------------------------------------------------+ -5.3 Code sample -~~~~~~~~~~~~~~~ -.. code:: php +.. code-block:: php - $ids = array('51db6f78c508f17ddc924357', 'f5b8c8a7c62b0150b68a50d6'); + $ids = array('id_1', 'id_2'); - $messages = $queue->listMessages(array('ids' => $ids)); + $messages = $queue->listMessages(array('ids' => $ids)); - while ($message = $messages->next()) { - echo $message->getId() . PHP_EOL; - } + foreach ($messages as $message) { + echo $message->getId() . PHP_EOL; + } -6. Delete a set of messages by ID ---------------------------------- -6.1 Description -~~~~~~~~~~~~~~~ +Delete a set of messages by ID +------------------------------ This operation immediately deletes the specified messages. If any of the message IDs are malformed or non-existent, they are ignored. The remaining valid messages IDs are deleted. -6.2 Parameters -~~~~~~~~~~~~~~ - -An array of IDs. - -6.3 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php +.. code-block:: php - $ids = array('51db6f78c508f17ddc924357', 'f5b8c8a7c62b0150b68a50d6'); + $ids = array('id_1', 'id_2'); + $response = $queue->deleteMessages($ids); - $response = $queue->deleteMessages($ids); -7. Get a specific message -------------------------- - -7.1 Description -~~~~~~~~~~~~~~~ +Get a specific message +---------------------- This operation gets the specified message from the specified queue. -7.2 Parameters -~~~~~~~~~~~~~~ - -Message ID. - -7.3 Object properties -~~~~~~~~~~~~~~~~~~~~~ - -``href`` is an opaque relative URI that the client can use to uniquely -identify a message resource and interact with it. - -``ttl`` is the TTL that was set on the message when it was posted. The -message expires after (ttl - age) seconds. - -``age`` is the number of seconds relative to the server's clock. - -``body`` is the arbitrary document that was submitted with the original -request to post the message. - -7.4 Code sample -~~~~~~~~~~~~~~~ - -.. code:: php - - $message = $queue->getMessage('51db6f78c508f17ddc924357'); - -8. Delete message ------------------ +.. code-block:: php -8.1 Description -~~~~~~~~~~~~~~~ + /** @var $message OpenCloud\Queues\Message */ + $message = $queue->getMessage('{messageId}'); -This operation immediately deletes the specified message. -8.2 Parameters -~~~~~~~~~~~~~~ +Once you have access to the ``Message`` object, you access its attributes: -None. ++-----------+-------------+--------------------------------------------------------------------------------------------------------------+ +| attribute | method | description | ++===========+=============+==============================================================================================================+ +| href | ``getHref`` | An opaque relative URI that the client can use to uniquely identify a message resource and interact with it. | ++-----------+-------------+--------------------------------------------------------------------------------------------------------------+ +| ttl | ``getTtl`` | The TTL that was set on the message when it was posted. The message expires after (ttl - age) seconds. | ++-----------+-------------+--------------------------------------------------------------------------------------------------------------+ +| age | ``getAge`` | The number of seconds relative to the server's clock. | ++-----------+-------------+--------------------------------------------------------------------------------------------------------------+ +| body | ``getBody`` | The arbitrary document that was submitted with the original request to post the message. | ++-----------+-------------+--------------------------------------------------------------------------------------------------------------+ -8.3 Code sample -~~~~~~~~~~~~~~~ -.. code:: php +Delete message +-------------- - $message->delete(); +.. code-block:: php + $message->delete(); diff --git a/doc/services/queues/queues.rst b/doc/services/queues/queues.rst new file mode 100644 index 000000000..7958adfae --- /dev/null +++ b/doc/services/queues/queues.rst @@ -0,0 +1,124 @@ +Queues +====== + +A note on Client IDs +-------------------- + +For most of the operations in Cloud Queues, you must specify a **Client ID** +which will be used as a unique identifier for the process accessing this +Queue. This is basically a UUID that must be unique to each client +accessing the API - it can be an arbitrary string. + +.. code-block:: php + + $service->setClientId(); + + echo $service->getClientId(); + +If you call ``setClientId`` without any parameters, a UUID is +automatically generated for you. + + +List queues +----------- + +This operation lists queues for the project. The queues are sorted alphabetically by name. + +.. code-block:: php + + $queues = $service->listQueues(); + + foreach ($queues as $queue) { + echo $queue->getName() , PHP_EOL; + } + + +Filtering lists +~~~~~~~~~~~~~~~ + +You can also filter collections using the following query parameters: + ++----------+-------+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Name | Style | Type | Description | ++==========+=======+=========+================================================================================================================================================================================================+ +| marker | Query | ​String | Specifies the name of the last queue received in a previous request, or none to get the first page of results. Optional. | ++----------+-------+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| limit | Query | Integer | Specifies the number of queues to return. The default value for the number of queues returned is 10. If you do not specify this parameter, the default number of queues is returned. Optional. | ++----------+-------+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| detailed | Query | ​Boolean | Determines whether queue metadata is included in the response. The default value for this parameter is false, which excludes the metadata. Optional. | ++----------+-------+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +.. code-block:: php + + $queues = $service->listQueues(array('detailed' => false)); + + +Create queue +------------ + +The only parameter required is the name of the queue you're creating. The name +must not exceed 64 bytes in length, and it is limited to US-ASCII letters, +digits, underscores, and hyphens. + +.. code-block:: php + + $queue = $service->createQueue('new_queue'); + + +Find queue details +------------------ + +.. code-block:: php + + /** @var $queue OpenCloud\Queues\Resource\Queues */ + $queue = $service->getQueue('{name}'); + + +Check queue existence +--------------------- + +This operation verifies whether the specified queue exists by returning +``TRUE`` or ``FALSE``. + +.. code-block:: php + + if ($service->hasQueue('new_queue')) { + // do something + } + + +Update queue metadata +--------------------- + +This operation replaces any existing metadata document in its entirety. +Ensure that you do not accidentally overwrite existing metadata that you +want to retain. If you want to *append* metadata, ensure you merge a new +array to the existing values. + +.. code-block:: php + + $queue->saveMetadata(array( + 'foo' => 'bar' + )); + + +Retrieve the queue metadata +--------------------------- + +This operation returns metadata, such as message TTL, for the queue. + +.. code-block:: php + + $metadata = $queue->retrieveMetadata(); + print_r($metadata->toArray()); + + +Get queue stats +--------------- + +This operation returns queue statistics, including how many messages are +in the queue, categorized by status. + +.. code-block:: php + + $queue->getStats(); From 26f3d6fc5a2c14efdd51b3ba383a30b2ec0f2bc2 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 5 Mar 2015 17:20:43 -0800 Subject: [PATCH 134/181] Fix what properties can be updated. --- lib/OpenCloud/Networking/Resource/Network.php | 4 +--- lib/OpenCloud/Networking/Resource/Port.php | 6 +----- tests/OpenCloud/Smoke/Unit/Networking.php | 8 +------- 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/lib/OpenCloud/Networking/Resource/Network.php b/lib/OpenCloud/Networking/Resource/Network.php index 53716a8f0..19454445e 100644 --- a/lib/OpenCloud/Networking/Resource/Network.php +++ b/lib/OpenCloud/Networking/Resource/Network.php @@ -57,9 +57,7 @@ class Network extends PersistentResource implements NetworkInterface ); protected $updateKeys = array( - 'adminStateUp', - 'name', - 'shared' + 'name' ); /** diff --git a/lib/OpenCloud/Networking/Resource/Port.php b/lib/OpenCloud/Networking/Resource/Port.php index 484de675e..bc7ee4dd0 100644 --- a/lib/OpenCloud/Networking/Resource/Port.php +++ b/lib/OpenCloud/Networking/Resource/Port.php @@ -78,11 +78,7 @@ class Port extends PersistentResource protected $updateKeys = array( 'name', - 'adminStateUp', - 'deviceId', - 'deviceOwner', - 'fixedIps', - 'securityGroups' + 'deviceId' ); /** diff --git a/tests/OpenCloud/Smoke/Unit/Networking.php b/tests/OpenCloud/Smoke/Unit/Networking.php index b6ab4592e..2518119bd 100644 --- a/tests/OpenCloud/Smoke/Unit/Networking.php +++ b/tests/OpenCloud/Smoke/Unit/Networking.php @@ -245,13 +245,7 @@ protected function testPortOperations() $this->step('Update port'); $port->update(array( - 'name' => 'updated_test_port', - 'fixedIps' => array( - array( - 'subnetId' => $subnet1->getId(), - 'ipAddress' => '192.168.62.17' - ) - ) + 'name' => 'updated_test_port' )); } From 1e2850ef30aa19582ab4245a43591bfe0c3e89a9 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 5 Mar 2015 17:21:12 -0800 Subject: [PATCH 135/181] Fix variable names. --- tests/OpenCloud/Smoke/Unit/Networking.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/OpenCloud/Smoke/Unit/Networking.php b/tests/OpenCloud/Smoke/Unit/Networking.php index 2518119bd..7b424c46f 100644 --- a/tests/OpenCloud/Smoke/Unit/Networking.php +++ b/tests/OpenCloud/Smoke/Unit/Networking.php @@ -252,7 +252,7 @@ protected function testPortOperations() protected function testSecurityGroupOperations() { $this->step('Create security group'); - $security group = $this->getService()->createSecurityGroup(array( + $securityGroup = $this->getService()->createSecurityGroup(array( 'name' => 'new-webservers', 'description' => 'security group for webservers' )); @@ -269,7 +269,7 @@ protected function testSecurityGroupOperations() } $this->step('Get security group'); - $security group = $this->getService()->getSecurityGroup($securityGroup->getId()); + $securityGroup = $this->getService()->getSecurityGroup($securityGroup->getId()); $this->stepInfo('Security Group ID: ' . $securityGroup->getId()); $this->stepInfo('Security Group Name: ' . $securityGroup->getName()); } @@ -282,7 +282,7 @@ protected function testSecurityGroupRuleOperations() $this->cleanupSecurityGroupIds[] = $securityGroup1->getId(); $this->step('Create security group rule'); - $security group rule = $this->getService()->createSecurityGroupRule(array( + $securityGroupRule = $this->getService()->createSecurityGroupRule(array( 'securityGroupId' => $securityGroup1->getId(), 'direction' => 'egress', 'ethertype' => 'IPv4', From 073aef3ae0cb7aecaa8ff29f90ff05d1a63799f6 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 5 Mar 2015 17:21:27 -0800 Subject: [PATCH 136/181] Only ingress rules are currently allowed. --- tests/OpenCloud/Smoke/Unit/Networking.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/OpenCloud/Smoke/Unit/Networking.php b/tests/OpenCloud/Smoke/Unit/Networking.php index 7b424c46f..38d903ff0 100644 --- a/tests/OpenCloud/Smoke/Unit/Networking.php +++ b/tests/OpenCloud/Smoke/Unit/Networking.php @@ -284,7 +284,7 @@ protected function testSecurityGroupRuleOperations() $this->step('Create security group rule'); $securityGroupRule = $this->getService()->createSecurityGroupRule(array( 'securityGroupId' => $securityGroup1->getId(), - 'direction' => 'egress', + 'direction' => 'ingress', 'ethertype' => 'IPv4', 'portRangeMin' => 80, 'portRangeMax' => 80, From aed62d9c20931085bc4cc57f11f7d25f8db7074b Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 5 Mar 2015 17:21:41 -0800 Subject: [PATCH 137/181] Remote groups are not currently allowed. --- tests/OpenCloud/Smoke/Unit/Networking.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/OpenCloud/Smoke/Unit/Networking.php b/tests/OpenCloud/Smoke/Unit/Networking.php index 38d903ff0..deaefda33 100644 --- a/tests/OpenCloud/Smoke/Unit/Networking.php +++ b/tests/OpenCloud/Smoke/Unit/Networking.php @@ -288,8 +288,7 @@ protected function testSecurityGroupRuleOperations() 'ethertype' => 'IPv4', 'portRangeMin' => 80, 'portRangeMax' => 80, - 'protocol' => 'tcp', - 'remoteGroupId' => '85cc3048-abc3-43cc-89b3-377341426ac5' + 'protocol' => 'tcp' )); $this->stepInfo('Security Group Rule ID: ' . $securityGroupRule->getId()); $this->stepInfo('Security Group Rule Direction: ' . $securityGroupRule->getDirection()); From 14099cc13887f6066fcf83fc5d175a3da86649dc Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 5 Mar 2015 17:21:55 -0800 Subject: [PATCH 138/181] Security group rules don't have names. s/name/direction/. --- tests/OpenCloud/Smoke/Unit/Networking.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/OpenCloud/Smoke/Unit/Networking.php b/tests/OpenCloud/Smoke/Unit/Networking.php index deaefda33..8ccd30a94 100644 --- a/tests/OpenCloud/Smoke/Unit/Networking.php +++ b/tests/OpenCloud/Smoke/Unit/Networking.php @@ -296,16 +296,16 @@ protected function testSecurityGroupRuleOperations() $this->step('List security group rules'); $securityGroupRules = $this->getService()->listSecurityGroupRules(); - $this->stepInfo('%-40s | %s', 'Security Group Rule ID', 'Security Group Rule name'); + $this->stepInfo('%-40s | %s', 'Security Group Rule ID', 'Security Group Rule direction'); $this->stepInfo('%-40s | %s', str_repeat('-', 40), str_repeat('-', 40)); foreach ($securityGroupRules as $securityGroupRule) { - $this->stepInfo('%-40s | %s', $securityGroupRule->getId(), $securityGroupRule->getName()); + $this->stepInfo('%-40s | %s', $securityGroupRule->getId(), $securityGroupRule->getDirection()); } $this->step('Get security group rule'); - $security group rule = $this->getService()->getSecurityGroupRule($securityGroupRule->getId()); + $securityGroupRule = $this->getService()->getSecurityGroupRule($securityGroupRule->getId()); $this->stepInfo('Security Group Rule ID: ' . $securityGroupRule->getId()); - $this->stepInfo('Security Group Rule Name: ' . $securityGroupRule->getName()); + $this->stepInfo('Security Group Rule Direction: ' . $securityGroupRule->getDirection()); } public function teardown() From 623f5cc9936efa0fa027599b519e2313a07ae674 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Thu, 5 Mar 2015 17:38:43 -0800 Subject: [PATCH 139/181] Appeasing the linter. --- lib/OpenCloud/Networking/Resource/SecurityGroup.php | 2 +- lib/OpenCloud/Networking/Resource/SecurityGroupRule.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/OpenCloud/Networking/Resource/SecurityGroup.php b/lib/OpenCloud/Networking/Resource/SecurityGroup.php index 105fc22a1..2892f5471 100644 --- a/lib/OpenCloud/Networking/Resource/SecurityGroup.php +++ b/lib/OpenCloud/Networking/Resource/SecurityGroup.php @@ -20,7 +20,7 @@ use OpenCloud\Common\Resource\PersistentResource; /** - * + * * @see http://developer.openstack.org/api-ref-networking-v2.html#security_groups * * @package OpenCloud\Networking\Resource diff --git a/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php b/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php index 3659d08ac..5527ce272 100644 --- a/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php +++ b/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php @@ -20,7 +20,7 @@ use OpenCloud\Common\Resource\PersistentResource; /** - * + * * @see http://developer.openstack.org/api-ref-networking-v2.html#security_groups * * @package OpenCloud\Networking\Resource From 1698223117ef8e3f75437472977692a735a20baa Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 6 Mar 2015 11:24:03 +0100 Subject: [PATCH 140/181] Shuffle setup org --- doc/services/autoscale/index.rst | 8 +- doc/services/common/clients.sample.rst | 22 ++++++ doc/services/common/os-client.sample.rst | 13 --- .../{rs-client.sample.rst => rs-client.rst} | 8 +- doc/services/common/rs-only.sample.rst | 8 ++ doc/services/common/service-args.rst | 23 +++--- doc/services/compute/index.rst | 13 +-- doc/services/database/index.rst | 8 +- doc/services/dns/index.rst | 8 +- doc/services/identity/index.rst | 8 +- doc/services/image/index.rst | 8 +- doc/services/load-balancer/index.rst | 12 +-- doc/services/monitoring/index.rst | 8 +- doc/services/networking/index.rst | 8 +- doc/services/object-store/index.rst | 10 +-- doc/services/orchestration/index.rst | 8 +- doc/services/queues/index.rst | 6 +- doc/services/volume/index.rst | 43 ++++++++++ doc/services/volume/snapshots.rst | 48 +++++++++++ doc/services/volume/volume-types.rst | 30 +++++++ doc/services/volume/volumes.rst | 79 +++++++++++++++++++ doc/url-types.rst | 2 + 22 files changed, 293 insertions(+), 88 deletions(-) create mode 100644 doc/services/common/clients.sample.rst delete mode 100644 doc/services/common/os-client.sample.rst rename doc/services/common/{rs-client.sample.rst => rs-client.rst} (58%) create mode 100644 doc/services/common/rs-only.sample.rst create mode 100644 doc/services/volume/snapshots.rst create mode 100644 doc/services/volume/volume-types.rst create mode 100644 doc/services/volume/volumes.rst create mode 100644 doc/url-types.rst diff --git a/doc/services/autoscale/index.rst b/doc/services/autoscale/index.rst index d6ec512ac..1bfd20e68 100644 --- a/doc/services/autoscale/index.rst +++ b/doc/services/autoscale/index.rst @@ -1,12 +1,12 @@ Auto Scale v2 ============= -Setup ------ +.. include:: ../common/rs-only.sample.rst -.. include:: ../common/rs-client.sample.rst +Auto Scale service +~~~~~~~~~~~~~~~~~~ -Now, set up the Auto Scale service: +Now to instantiate the Auto Scale service: .. code-block:: php diff --git a/doc/services/common/clients.sample.rst b/doc/services/common/clients.sample.rst new file mode 100644 index 000000000..a952da730 --- /dev/null +++ b/doc/services/common/clients.sample.rst @@ -0,0 +1,22 @@ +Setup +----- + +Rackspace setup +~~~~~~~~~~~~~~~ + +.. include:: /services/common/rs-client.rst + + +OpenStack setup +~~~~~~~~~~~~~~~ + +If you're an OpenStack user, you will also need to prove a few other +configuration parameters: + +.. code-block:: php + + $client = new OpenCloud\OpenStack('{keystoneUrl}', array( + 'username' => '{username}', + 'password' => '{apiKey}', + 'tenantId' => '{tenantId}', + )); diff --git a/doc/services/common/os-client.sample.rst b/doc/services/common/os-client.sample.rst deleted file mode 100644 index b4614474d..000000000 --- a/doc/services/common/os-client.sample.rst +++ /dev/null @@ -1,13 +0,0 @@ -.. code-block:: php - - '{username}', - 'password' => '{apiKey}', - 'tenantId' => '{tenantId}', - )); diff --git a/doc/services/common/rs-client.sample.rst b/doc/services/common/rs-client.rst similarity index 58% rename from doc/services/common/rs-client.sample.rst rename to doc/services/common/rs-client.rst index e33983270..46f9a5291 100644 --- a/doc/services/common/rs-client.sample.rst +++ b/doc/services/common/rs-client.rst @@ -1,12 +1,8 @@ -The first thing to do is pass in your credentials and instantiate a Rackspace -client: +The first step is to pass in your credentials and set up a client. For +Rackspace users, you will need your username and API key: .. code-block:: php - `_. +* ``{region}`` is the region the service will operate in. For Rackspace + users, you can select one of the following from the `supported regions page + `_. -``{urlType}`` is the type of URL to use, depending on what endpoints your -catalog provides. For Rackspace, you may use either ``internalURL`` or -``publicURL``. The former will execute HTTP transactions over the internal -network configured for your service, possibly reducing latency and the overall -bandwidth cost - the caveat is that all of your resources must be in same region. -``publicURL``, however, which is the default, will operate over the public -Internet and is to be used for multi-region installations. +* ``{urlType}`` is the `type of URL `_ to use, depending on which + endpoints your catalog provides. If omitted, it will default to the public + network. diff --git a/doc/services/compute/index.rst b/doc/services/compute/index.rst index 207151d50..234517661 100644 --- a/doc/services/compute/index.rst +++ b/doc/services/compute/index.rst @@ -1,17 +1,12 @@ Compute v2 ========== -.. note:: +.. include:: ../common/clients.sample.rst - This is a joint service that supports both Rackspace Cloud Servers v2 API, and - OpenStack Nova v2 API. +Compute service +~~~~~~~~~~~~~~~ -Setup ------ - -.. include:: ../common/rs-client.sample.rst - -Now, set up the Compute service: +Now to instantiate the Compute service: .. code-block:: php diff --git a/doc/services/database/index.rst b/doc/services/database/index.rst index 850e56c8a..c330d4ac8 100644 --- a/doc/services/database/index.rst +++ b/doc/services/database/index.rst @@ -1,12 +1,12 @@ Databases v1 ============ -Setup ------ +.. include:: ../common/clients.sample.rst -.. include:: ../common/rs-client.sample.rst +Databases service +~~~~~~~~~~~~~~~~~ -Now, set up the Database service: +Now to instantiate the Databases service: .. code-block:: php diff --git a/doc/services/dns/index.rst b/doc/services/dns/index.rst index 4caca9fe5..99d19c5e8 100644 --- a/doc/services/dns/index.rst +++ b/doc/services/dns/index.rst @@ -1,12 +1,12 @@ DNS v1 ====== -Setup ------ +.. include:: ../common/rs-only.sample.rst -.. include:: ../common/rs-client.sample.rst +DNS service +~~~~~~~~~~~ -Now, set up the DNS service: +Now to instantiate the DNS service: .. code-block:: php diff --git a/doc/services/identity/index.rst b/doc/services/identity/index.rst index 35c27131b..3eaa08de6 100644 --- a/doc/services/identity/index.rst +++ b/doc/services/identity/index.rst @@ -1,10 +1,12 @@ Identity v2 =========== -Setup ------ +.. include:: ../common/clients.sample.rst -.. include:: ../common/rs-client.sample +Identity service +~~~~~~~~~~~~~~~~ + +Now to instantiate the Identity service: .. code-block:: php diff --git a/doc/services/image/index.rst b/doc/services/image/index.rst index d54b09ad0..c6451554b 100644 --- a/doc/services/image/index.rst +++ b/doc/services/image/index.rst @@ -1,10 +1,12 @@ Images v1 ========= -Setup ------ +.. include:: ../common/clients.sample.rst -.. include:: ../common/rs-client.sample.rst +Images service +~~~~~~~~~~~~~~ + +Now to instantiate the Images service: .. code-block:: php diff --git a/doc/services/load-balancer/index.rst b/doc/services/load-balancer/index.rst index bf2b6dd0c..e2e4ca973 100644 --- a/doc/services/load-balancer/index.rst +++ b/doc/services/load-balancer/index.rst @@ -1,17 +1,13 @@ Load Balancer v1 ================ -.. note:: +.. include:: ../common/rs-only.sample.rst - This service is only available for Rackspace users. +Load Balancer service +~~~~~~~~~~~~~~~~~~~~~ -Setup ------ - -.. include:: ../common/rs-client.sample.rst - -Now, set up the Load Balancer service: +Now to instantiate the Load Balancer service: .. code-block:: php diff --git a/doc/services/monitoring/index.rst b/doc/services/monitoring/index.rst index df0597e8c..be38d1067 100644 --- a/doc/services/monitoring/index.rst +++ b/doc/services/monitoring/index.rst @@ -1,12 +1,12 @@ Monitoring v1 ============= -Setup ------ +.. include:: ../common/rs-only.sample.rst -.. include:: ../common/rs-client.sample.rst +Monitoring service +~~~~~~~~~~~~~~~~~~ -Now, set up the Cloud Monitoring service: +Now to instantiate the Monitoring service: .. code-block:: php diff --git a/doc/services/networking/index.rst b/doc/services/networking/index.rst index 92270fe86..89a159d4f 100644 --- a/doc/services/networking/index.rst +++ b/doc/services/networking/index.rst @@ -1,12 +1,12 @@ Networking v2 ============= -Setup ------ +.. include:: ../common/clients.sample.rst -.. include:: rs-client.sample.rst +Networking service +~~~~~~~~~~~~~~~~~~ -Now, set up the Cloud Monitoring service: +Now to instantiate the Networking service: .. code-block:: php diff --git a/doc/services/object-store/index.rst b/doc/services/object-store/index.rst index 6b3a18b6f..8c50d7de0 100644 --- a/doc/services/object-store/index.rst +++ b/doc/services/object-store/index.rst @@ -1,12 +1,12 @@ Object Store v1 =============== -Setup ------ +.. include:: ../common/clients.sample.rst -.. include:: ../common/rs-client.sample.rst +Object Store service +~~~~~~~~~~~~~~~~~~~~ -Now, set up the Object Store service: +Now to instantiate the Object Store service: .. code-block:: php @@ -38,7 +38,7 @@ Glossary account is your portion of it. container - A storage compartment that provides a way for you to organize data. A + A storage compartment that provides a way for you to organize data. A container is similar to a folder in Windows or a directory in UNIX. The primary difference between a container and these other file system concepts is that containers cannot be nested. diff --git a/doc/services/orchestration/index.rst b/doc/services/orchestration/index.rst index 0dce8ac43..fcb5e46b9 100644 --- a/doc/services/orchestration/index.rst +++ b/doc/services/orchestration/index.rst @@ -1,12 +1,12 @@ Orchestration v1 ================ -Setup ------ +.. include:: ../common/clients.sample.rst -.. include:: rs-client.sample.rst +Orchestration service +~~~~~~~~~~~~~~~~~~~~~ -Now set up the Orchestration service: +Now to instantiate the Orchestration service: .. code-block:: php diff --git a/doc/services/queues/index.rst b/doc/services/queues/index.rst index e37845d76..317257d65 100644 --- a/doc/services/queues/index.rst +++ b/doc/services/queues/index.rst @@ -1,10 +1,10 @@ Queues v1 ========= -Setup ------ +.. include:: ../common/clients.sample.rst -.. include:: ../common/rs-client.sample.rst +Queues service +~~~~~~~~~~~~~~ Now to instantiate the Queues service: diff --git a/doc/services/volume/index.rst b/doc/services/volume/index.rst index e69de29bb..7e318a5cc 100644 --- a/doc/services/volume/index.rst +++ b/doc/services/volume/index.rst @@ -0,0 +1,43 @@ +Volumes v1 +========== + +.. include:: ../common/clients.sample.rst + +Volume service +~~~~~~~~~~~~~~ + +Now to instantiate the Volume service: + +.. code-block:: php + + $service = $client->volumeService('{catalogName}', '{region}', '{urlType}'); + +.. include:: ../common/service-args.rst + + +Operations +---------- + +.. toctree:: + + volumes + volume-types + snapshots + + +Glossary +-------- + +.. glossary:: + + volume + A volume is a detachable block storage device. You can think of it as a USB + hard drive. It can only be attached to one instance at a time. + + volume type + Providers may support multiple types of volumes; at Rackspace, a volume + can either be ``SSD`` (solid state disk: expensive, high-performance) or + ``SATA`` (serial attached storage: regular disks, less expensive). + + snapshot + A snapshot is a point-in-time copy of the data contained in a volume. diff --git a/doc/services/volume/snapshots.rst b/doc/services/volume/snapshots.rst new file mode 100644 index 000000000..c2d8ef6cc --- /dev/null +++ b/doc/services/volume/snapshots.rst @@ -0,0 +1,48 @@ +Snapshots +========= + +Create a snapshot +----------------- + +A ``Snapshot`` object is created from the Cloud Block Storage service. +However, it is associated with a volume, and you must specify a volume +to create one: + +.. code-block:: php + + // New instance of OpenCloud\Volume\Resource\Snapshot + $snapshot = $service->snapshot(); + + // Send to API + $snapshot->create(array( + 'display_name' => 'Name that snapshot', + 'volume_id' => $volume->id + )); + + +List snapshots +-------------- + +.. code-block:: php + + $snapshots = $service->snapshotList(); + + foreach ($snapshots as $snapshot) { + /** @param $snapshot OpenCloud\Volume\Resource\Snapshot */ + } + + +To get details on a single snapshot +----------------------------------- + +.. code-block:: php + + $snapshot = $dallas->snapshot('{snapshotId}'); + + +To delete a snapshot +-------------------- + +.. code-block:: php + + $snapshot->delete(); diff --git a/doc/services/volume/volume-types.rst b/doc/services/volume/volume-types.rst new file mode 100644 index 000000000..ba3176df9 --- /dev/null +++ b/doc/services/volume/volume-types.rst @@ -0,0 +1,30 @@ +Volume Types +============ + +List volume types +----------------- + +.. code-block:: php + + $volumeTypes = $service->volumeTypeList(); + + foreach ($volumeTypes as $volumeType) { + /** @param $volumeType OpenCloud\Volume\Resource\VolumeType */ + } + + +Describe a volume type +---------------------- + +If you know the ID of a volume type, use the ``volumeType`` method to +retrieve information on it: + +.. code-block:: php + + $volumeType = $service->volumeType(1); + +A volume type has three attributes: + +- ``id`` the volume type identifier +- ``name`` its name +- ``extra_specs`` additional information for the provider diff --git a/doc/services/volume/volumes.rst b/doc/services/volume/volumes.rst new file mode 100644 index 000000000..6a35bb135 --- /dev/null +++ b/doc/services/volume/volumes.rst @@ -0,0 +1,79 @@ +Volumes +======= + +Create a volume +--------------- + +To create a volume, you must specify its size (in gigabytes). All other +parameters are optional: + +.. code-block:: php + + // Create instance of OpenCloud\Volume\Resource\Volume + $volume = $service->volume(); + + $volume->create(array( + 'size' => 200, + 'volume_type' => $service->volumeType(''), + 'display_name' => 'My Volume', + 'display_description' => 'Used for large object storage' + )); + +List volumes +------------ + +.. code-block:: php + + $volumes = $service->volumeList(); + + foreach ($volumes as $volume) { + /** @param $volumeType OpenCloud\Volume\Resource\Volume */ + } + + +Get details on a single volume +------------------------------ + +If you specify an ID on the ``volume()`` method, it retrieves +information on the specified volume: + +.. code-block:: php + + $volume = $dallas->volume(''); + echo $volume->size; + + +To delete a volume +------------------ + +.. code-block:: php + + $volume->delete(); + + +Attach a volume to a server +--------------------------- + +.. code-block:: php + + // retrieve server + $computeService = $client->computeService('{catalogName}', '{region}'); + $server = $computeService->server('{serverId}'); + + // attach volume + $server->attachVolume($volume, '{mountPoint}') + +The ``{mountPoint}`` is the location on the server on which to mount +the volume (usually ``/dev/xvhdd`` or similar). You can also supply +``'auto'`` as the mount point, in which case the mount point will be +automatically selected for you. ``auto`` is the default value for +``{mountPoint}``, so you do not actually need to supply anything for +that parameter. + + +Detach a volume from a server +----------------------------- + +.. code-block:: php + + $server->detachVolume($volume); diff --git a/doc/url-types.rst b/doc/url-types.rst new file mode 100644 index 000000000..b0e2cc0ea --- /dev/null +++ b/doc/url-types.rst @@ -0,0 +1,2 @@ +URL types +========= From 63a3a2c8a493ff8cab9d5c0555ede76fa9a80e40 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 6 Mar 2015 11:43:03 +0100 Subject: [PATCH 141/181] Refactor root pages and index page --- doc/caching-creds.rst | 36 ++++++++++----------- doc/debugging.rst | 60 +++++++++++++++++++---------------- doc/index.rst | 74 ++++++++++++++++++++++++++++++++++++------- doc/iterators.rst | 18 ++++------- doc/regions.rst | 7 +++- doc/url-types.rst | 13 ++++++++ 6 files changed, 138 insertions(+), 70 deletions(-) diff --git a/doc/caching-creds.rst b/doc/caching-creds.rst index 3c3e8df23..4eb5be5c8 100644 --- a/doc/caching-creds.rst +++ b/doc/caching-creds.rst @@ -16,29 +16,29 @@ Filesystem example In this example, credentials will be saved to a file in the local filesystem. Be sure to exclude it from your VCS. -.. code:: php +.. code-block:: php - use OpenCloud\Rackspace; + use OpenCloud\Rackspace; - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => 'foo', - 'apiKey' => 'bar' - )); + $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( + 'username' => 'foo', + 'apiKey' => 'bar' + )); - $cacheFile = __DIR__ . '/.opencloud_token'; + $cacheFile = __DIR__ . '/.opencloud_token'; - // If the cache file exists, try importing it into the client - if (file_exists($cacheFile)) { - $data = unserialize(file_get_contents($cacheFile)); - $client->importCredentials($data); - } + // If the cache file exists, try importing it into the client + if (file_exists($cacheFile)) { + $data = unserialize(file_get_contents($cacheFile)); + $client->importCredentials($data); + } - $token = $client->getTokenObject(); + $token = $client->getTokenObject(); - // If no token exists, or the current token is expired, re-authenticate and save the new token to disk - if (!$token || ($token && $token->hasExpired())) { - $client->authenticate(); - file_put_contents($cacheFile, serialize($client->exportCredentials())); - } + // If no token exists, or the current token is expired, re-authenticate and save the new token to disk + if (!$token || ($token && $token->hasExpired())) { + $client->authenticate(); + file_put_contents($cacheFile, serialize($client->exportCredentials())); + } In tests, the above code shaved about 1-2s off the execution time. diff --git a/doc/debugging.rst b/doc/debugging.rst index 445915284..5d35d5bc1 100644 --- a/doc/debugging.rst +++ b/doc/debugging.rst @@ -36,38 +36,40 @@ If you're trying to retrieve a Swift resource, such as a Data Object, and you're not completely certain that it exists, it makes sense to wrap your call in a try/catch block: -.. code:: php +.. code-block:: php - use Guzzle\Http\Exception\ClientErrorResponseException; + use Guzzle\Http\Exception\ClientErrorResponseException; - try { - return $service->getObject('foo.jpg'); - } catch (ClientErrorResponseException $e) { - // Okay, the resource probably does not exist + try { + return $service->getObject('foo.jpg'); + } catch (ClientErrorResponseException $e) { + if ($e->getResponse()->getStatusCode() == 404) { + // Okay, the resource does not exist return false; - } catch (\Exception $e) { - // Some other exception was thrown, probably critical - $this->logException($e); - $this->alertDevs(); - } + } + } catch (\Exception $e) { + // Some other exception was thrown... + } + Both ``ClientErrorResponseException`` and ``ServerErrorResponseException`` have two methods that allow you to access the HTTP transaction: -.. code:: php +.. code-block:: php + + // Find out the faulty request + $request = $e->getRequest(); - // Find out the faulty request - $request = $e->getRequest(); + // Display everything by casting as string + echo (string) $request; - // Display everything by casting as string - echo (string) $request; + // Find out the HTTP response + $response = $e->getResponse(); - // Find out the HTTP response - $response = $e->getResponse(); + // Output that too + echo (string) $response; - // Output that too - echo (string) $response; Strategy 2: Wire logging ------------------------ @@ -80,20 +82,22 @@ don't know what's going on. Here's how you enable it: Install the plugin -^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~ -.. code:: bash +.. code-block:: bash + + composer require guzzle/guzzle - php composer.phar require guzzle/plugin-log:~3.8 Add to your client -^^^^^^^^^^^^^^^^^^ +~~~~~~~~~~~~~~~~~~ + +.. code-block:: php -.. code:: php + use Guzzle\Plugin\Log\LogPlugin; - use Guzzle\Plugin\Log\LogPlugin; + $client->addSubscriber(LogPlugin::getDebugPlugin()); - $client->addSubscriber(LogPlugin::getDebugPlugin()); The above will add a generic logging subscriber to your client, which -will be notified every time a relevant HTTP event is fired off. +will output every HTTP transaction to `STDOUT`. diff --git a/doc/index.rst b/doc/index.rst index 9c06b86e8..8a211dab4 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -1,12 +1,37 @@ -.. php-opencloud documentation master file, created by - sphinx-quickstart on Tue Mar 3 12:28:19 2015. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +Welcome to php-opencloud! +========================= -Welcome to php-opencloud's documentation! -========================================= +Installation +------------ -Contents: +You must install this library through Composer: + +.. code-block:: bash + + composer require rackspace/php-opencloud + + +If you do not have Composer installed, please consult the `official docs +`_. + +Once you have installed the library, you will need to load Composer's autoloader +(which registers all the required namespaces). To do this, place the following +line of PHP code at the top of your application's PHP files: + +.. code-block:: php + + require 'vendor/autoload.php'; + +This assumes your application's PHP files are located in the same folder as +``vendor/``. If your files are located elsewhere, please supply the path to +``vendor/autoload.php`` in the require statement above. + +Read the `OpenStack Getting Started guide `_ +or `Rackspace Getting Started guide `_ to help +you get started with basic Compute operations. + +Services +-------- .. toctree:: :glob: @@ -14,10 +39,35 @@ Contents: services/**/index +Usage tips +---------- + +.. toctree:: + :maxdepth: 1 + + debugging + caching-creds + iterators + regions + url-types + +Help and support +---------------- + +If you have specific problems or bugs with this SDK, please file an issue on +our official `Github `_. We also +have a `mailing list `_, +so feel free to join to keep up to date with all the latest changes and +announcements to the library. + +For general feedback and support requests, send an email to +sdk-support@rackspace.com. + +You can also find assistance via IRC on #rackspace at freenode.net. -Indices and tables -================== +Contributing +------------ -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` +If you'd like to contribute to the project, or require help running the +unit/acceptance tests, please view the `contributing guidelines +`_. diff --git a/doc/iterators.rst b/doc/iterators.rst index e5d3c198d..bef59e339 100644 --- a/doc/iterators.rst +++ b/doc/iterators.rst @@ -1,9 +1,6 @@ Iterators ========= -Intro ------ - Iterators allow you to traverse over collections of your resources in an efficient and easy way. Currently there are two Iterators provided by the SDK: @@ -27,27 +24,27 @@ the SDK: Common behaviour ---------------- -.. code:: php +.. code-block:: php $iterator = $computeService->flavorList(); There are two ways to traverse an iterator. The first is the longer, more traditional way: -.. code:: php +.. code-block:: php while ($iterator->valid()) { $flavor = $iterator->current(); - + // do stuff.. echo $flavor->id; - + $iterator->next(); } There is also a shorter and more intuitive version: -.. code:: php +.. code-block:: php foreach ($iterator as $flavor) { // do stuff... @@ -63,7 +60,7 @@ Very important note Until now, users have been expected to do this: -.. code:: php +.. code-block:: php while ($flavor = $iterator->next()) { // ... @@ -119,7 +116,7 @@ precedence. Setting up a PaginatedIterator ------------------------------ -.. code:: php +.. code-block:: php use OpenCloud\Common\Collection\PaginatedIterator; @@ -175,4 +172,3 @@ needs to work. These are: +-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ | request.curlOptions | Additional cURL options to use when making API calls for new pages | array | No | ``array()`` | +-------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+------------------------------+------------+---------------+ - diff --git a/doc/regions.rst b/doc/regions.rst index 82edf28ec..42c14595c 100644 --- a/doc/regions.rst +++ b/doc/regions.rst @@ -3,13 +3,18 @@ Rackspace regions Below are the supported regions on the Rackspace network: -+======+===========+ ++------+-----------+ | code | location | +======+===========+ | IAD | Virginia | ++------+-----------+ | ORD | Chicago | ++------+-----------+ | DFW | Dallas | ++------+-----------+ | LON | London | ++------+-----------+ | SYD | Sydney | ++------+-----------+ | HKG | Hong Kong | +------+-----------+ diff --git a/doc/url-types.rst b/doc/url-types.rst index b0e2cc0ea..26a0410bd 100644 --- a/doc/url-types.rst +++ b/doc/url-types.rst @@ -1,2 +1,15 @@ URL types ========= + +internalURL +----------- + +An internal URL is a URL that is accessible only from within the Rackspace +Cloud network. Access to an internal URL is always free of charge. + + +publicURL +--------- + +A public URL is a URL that is accessible from anywhere. Access to a public URL +usually incurs traffic charges. From 10af5c6ca685a8cc3ddd216fa8fdfca646d4ed60 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 6 Mar 2015 12:29:29 +0100 Subject: [PATCH 142/181] Add final links --- doc/services/compute/index.rst | 8 +++- doc/services/database/index.rst | 8 ++++ doc/services/dns/index.rst | 8 ++++ doc/services/identity/index.rst | 7 +++ doc/services/image/index.rst | 7 +++ doc/services/load-balancer/index.rst | 9 +++- doc/services/monitoring/index.rst | 65 +++++++++++++++++++++++++++- doc/services/networking/index.rst | 8 ++++ doc/services/object-store/index.rst | 8 ++++ doc/services/orchestration/index.rst | 9 ++++ doc/services/queues/index.rst | 8 ++++ doc/services/volume/index.rst | 8 ++++ 12 files changed, 150 insertions(+), 3 deletions(-) diff --git a/doc/services/compute/index.rst b/doc/services/compute/index.rst index 234517661..ee27bce8e 100644 --- a/doc/services/compute/index.rst +++ b/doc/services/compute/index.rst @@ -46,4 +46,10 @@ Glossary server A server is a virtual machine instance in the Cloud Servers environment. - keypair + +Further Links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/database/index.rst b/doc/services/database/index.rst index c330d4ac8..32888e27d 100644 --- a/doc/services/database/index.rst +++ b/doc/services/database/index.rst @@ -67,3 +67,11 @@ Glossary for increased performance, scalability, availability and manageability. Applications with high I/O demands are performance optimized and data is protected through both local and network RAID-10. + + +Further Links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/dns/index.rst b/doc/services/dns/index.rst index 99d19c5e8..39db3d675 100644 --- a/doc/services/dns/index.rst +++ b/doc/services/dns/index.rst @@ -49,3 +49,11 @@ Glossary DNS usually determines an IP address associated with a domain name. Reverse DNS is the opposite process: resolving a domain name from an IP address. This is usually achieved with a domain name pointer. + + +Further Links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/identity/index.rst b/doc/services/identity/index.rst index 3eaa08de6..6cb4dfdf4 100644 --- a/doc/services/identity/index.rst +++ b/doc/services/identity/index.rst @@ -46,3 +46,10 @@ Glossary access the requested resources. Users may be directly assigned to a particular tenant and behave as if they are contained within that tenant. + + +Further Links +------------- + +- `Quickstart for the API `_ +- `API Developer Guide `_ diff --git a/doc/services/image/index.rst b/doc/services/image/index.rst index c6451554b..a7331b430 100644 --- a/doc/services/image/index.rst +++ b/doc/services/image/index.rst @@ -41,3 +41,10 @@ Glossary tag An image tag is a string of characters used to identify a specific image or images. + + +Further Links +------------- + + - `Getting Started Guide for the API `_ + - `API Developer Guide `_ diff --git a/doc/services/load-balancer/index.rst b/doc/services/load-balancer/index.rst index e2e4ca973..9ea7614ad 100644 --- a/doc/services/load-balancer/index.rst +++ b/doc/services/load-balancer/index.rst @@ -21,7 +21,7 @@ Operations .. toctree:: - load-balancers + load-balancer nodes virtual-ips access @@ -87,3 +87,10 @@ Glossary (``PUBLIC``), routable on the public Internet, or a ServiceNet VIP address (``SERVICENET``), routable only within the region in which the load balancer resides. + + +Further Links +------------- + +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/monitoring/index.rst b/doc/services/monitoring/index.rst index be38d1067..0a7225e36 100644 --- a/doc/services/monitoring/index.rst +++ b/doc/services/monitoring/index.rst @@ -29,6 +29,69 @@ Operations views zones - Glossary -------- + +.. glossary:: + + agent + A monitoring daemon that resides on the server being monitored. The agent + gathers metrics based on agent checks and pushes them to Cloud Monitoring. + The agent provides insight into your servers with checks for information + such as load average and network usage. The agent acts as a single small + service that runs scheduled checks and pushes metrics to the rest of Cloud + Monitoring so the metrics can be analyzed, trigger alerts, and be archived. + These metrics are gathered via checks using agent check types, and can be + used with the other Cloud Monitoring primitives such as alarms. + + agent token + An authentication token used to identify the agent when it communicates + with Cloud Monitoring. + + alarm + An alarm contains a set of rules that determine when the monitoring system + sends a notification. You can create multiple alarms for the different + checks types associated with an entity. For example, if your entity is a + web server that hosts your company's website, you can create one alarm to + monitor the server itself, and another alarm to monitor the website. + + check + Checks explicitly specify how you want to monitor an entity. Once you've + created an entity, you can configure one or more checks for it. A check is + the foundational building block of the monitoring system, and is always + associated with an entity. The check specifies the parts or pieces of the + entity that you want to monitor, the monitoring frequency, how many + monitoring zones are launching the check, and so on. It contains the + specific details of how you are monitoring the entity. + + entity + The object or resource that you want to monitor. It can be any object or + device that you want to monitor. It's commonly a web server, but it might + also be a website, a web page or a web service. + + monitoring zone + A monitoring zone is the "launch point" of a check. When you create a + check, you specify which monitoring zone(s) you want to launch the check + from. This concept of a monitoring zone is similar to that of a datacenter, + however in the monitoring system, you can think of it more as a geographical + region. + + notification + A notification is an informational message sent to one or more addresses + by the monitoring system when an alarm is triggered. You can set up + notifications to alert a single individual or an entire team. Rackspace + Cloud Monitoring currently supports webhooks and email for sending + notifications. + + notification plan + A notification plan contains a set of notification rules to execute when an + alarm is triggered. A notification plan can contain multiple notifications + for each of the following states: + + +Further links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/networking/index.rst b/doc/services/networking/index.rst index 89a159d4f..515f9ddce 100644 --- a/doc/services/networking/index.rst +++ b/doc/services/networking/index.rst @@ -48,3 +48,11 @@ Glossary When IP addresses are associated to a port, this also implies the port is associated with a subet, as the IP address is taken from the allocation pool for a specific subnet. + + +Further links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/object-store/index.rst b/doc/services/object-store/index.rst index 8c50d7de0..fcdc5aff2 100644 --- a/doc/services/object-store/index.rst +++ b/doc/services/object-store/index.rst @@ -55,3 +55,11 @@ Glossary object An object (sometimes referred to as a file) is the unit of storage in an Object Store. An object is a combination of content (data) and metadata. + + +Further links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/orchestration/index.rst b/doc/services/orchestration/index.rst index fcb5e46b9..bae5ec6aa 100644 --- a/doc/services/orchestration/index.rst +++ b/doc/services/orchestration/index.rst @@ -25,6 +25,7 @@ Operations resources resource-types build-info + events Glossary @@ -48,3 +49,11 @@ Glossary stack A stack is a running instance of a template. When a stack is created, the resources specified in the template are created. + + +Further links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/queues/index.rst b/doc/services/queues/index.rst index 317257d65..4175df760 100644 --- a/doc/services/queues/index.rst +++ b/doc/services/queues/index.rst @@ -46,3 +46,11 @@ Glossary producer or publisher sends to the queue. A message exists until it is deleted by a recipient or automatically by the system based on a TTL (time-to-live) value. + + +Further links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ diff --git a/doc/services/volume/index.rst b/doc/services/volume/index.rst index 7e318a5cc..bee589086 100644 --- a/doc/services/volume/index.rst +++ b/doc/services/volume/index.rst @@ -41,3 +41,11 @@ Glossary snapshot A snapshot is a point-in-time copy of the data contained in a volume. + + +Further links +------------- + +- `Getting Started Guide for the API `_ +- `API Developer Guide `_ +- `API release history `_ From 21dccc349cb4cedee7d248fa8b7aa259786a5107 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 6 Mar 2015 13:05:09 +0100 Subject: [PATCH 143/181] Add GS guides --- doc/index.rst | 4 ++-- doc/services/load-balancer/lb-setup.sample.rst | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/index.rst b/doc/index.rst index 8a211dab4..297a64c6c 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -26,8 +26,8 @@ This assumes your application's PHP files are located in the same folder as ``vendor/``. If your files are located elsewhere, please supply the path to ``vendor/autoload.php`` in the require statement above. -Read the `OpenStack Getting Started guide `_ -or `Rackspace Getting Started guide `_ to help +Read the `OpenStack Getting Started guide `_ +or `Rackspace Getting Started guide `_ to help you get started with basic Compute operations. Services diff --git a/doc/services/load-balancer/lb-setup.sample.rst b/doc/services/load-balancer/lb-setup.sample.rst index 96e228b8d..d82c80a1f 100644 --- a/doc/services/load-balancer/lb-setup.sample.rst +++ b/doc/services/load-balancer/lb-setup.sample.rst @@ -6,4 +6,4 @@ load balancer, like so: .. code-block:: php - $loadBalancer = $service->loadBalancer('{id}'); + $loadBalancer = $service->loadBalancer('{id}'); From 2c9a7fb2753023ad26600c86fd814341571984aa Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 6 Mar 2015 13:22:42 +0100 Subject: [PATCH 144/181] Tweak GS guides --- doc/getting-started-with-openstack.rst | 233 +++++++++++++++++++++++++ doc/getting-started-with-rackspace.rst | 185 ++++++++++++++++++++ 2 files changed, 418 insertions(+) create mode 100644 doc/getting-started-with-openstack.rst create mode 100644 doc/getting-started-with-rackspace.rst diff --git a/doc/getting-started-with-openstack.rst b/doc/getting-started-with-openstack.rst new file mode 100644 index 000000000..da6c6ee24 --- /dev/null +++ b/doc/getting-started-with-openstack.rst @@ -0,0 +1,233 @@ +Getting Started with OpenStack +============================== + +Installing the SDK +------------------ + +You must install through Composer, because this library has a few +dependencies: + +.. code-block:: bash + + composer require rackspace/php-opencloud + +Once you have installed the library, you will need to load Composer's +autoloader (which registers all the required namespaces): + +.. code-block:: php + + require 'vendor/autoload.php'; + +And you're good to go! + + +Quick deep-dive: building some Nova instances +--------------------------------------------- + +In this example, you will write code that will create a Nova instance +running Ubuntu. + + +1. Setup the client and pass in your credentials +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To authenticate against Keystone: + +.. code-block:: php + + use OpenCloud\OpenStack; + + $client = new OpenStack('http://my-openstack.com:35357/v2.0/', array( + 'username' => 'foo', + 'password' => 'bar', + 'tenantName' => 'baz' + )); + +You will need to substitute in the public URL endpoint for your Keystone +service, as well as your ``username``, ``password`` and ``tenantName``. +You can also specify your ``tenantId`` instead of ``tenantName`` if you +prefer. + + +2. Pick what service you want to use +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In this case, we want to use the Nova service: + +.. code-block:: php + + $compute = $client->computeService('nova', 'regionOne'); + + +The first argument is the **name** of the service as it appears in the +OpenStack service catalog. For OpenStack users, this must be retrieved +and entered in your code. If you are unsure how to retrieve the service +name, follow these steps: + +1. Setup the ``$client`` object, as above +2. Copy and run this code: + +.. code-block:: php + + $client->authenticate(); + print_r($client->getCatalog()->getItems()); + + +3. This will output all the items in your service catalog. Go through + the outputted list and find your service, making note of the "name" + field. This is the name you will need to enter as the first argument. + You will also be able to see the available regions. + +The second argument is the region. The third and last argument is the +type of URL; you may use either ``publicURL`` or ``internalURL``. + + +3. Select your server image +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Instances are based on "images", which are effectively just the type of +operating system you want. Let's go through the list and find an Ubuntu +one: + +.. code-block:: php + + $images = $compute->imageList(); + + foreach ($images as $image) { + if (strpos($image->name, 'Ubuntu') !== false) { + $ubuntu = $image; + break; + } + } + +Alternatively, if you already know the image ID, you can do this much +easier: + +.. code-block:: php + + $ubuntu = $compute->image('868a0966-0553-42fe-b8b3-5cadc0e0b3c5'); + + +4. Select your flavor +--------------------- + +There are different server specs - some which offer 1GB RAM, others +which offer a much higher spec. The 'flavor' of an instance is its +hardware configuration. So if you want a 2GB instance but don't know the +ID, you have to traverse the list: + +.. code-block:: php + + $flavors = $compute->flavorList(); + + foreach ($flavors as $flavor) { + if (strpos($flavor->name, '2GB') !== false) { + $twoGbFlavor = $flavor; + break; + } + } + +Again, it's much easier if you know the ID: + +.. code-block:: php + + $twoGbFlavor = $compute->flavor('4'); + + +5. Thunderbirds are go! +----------------------- + +Okay, you're ready to spin up a server: + +.. code-block:: php + + use Guzzle\Http\Exception\BadResponseException; + + $server = $compute->server(); + + try { + $response = $server->create(array( + 'name' => 'My lovely server', + 'image' => $ubuntu, + 'flavor' => $twoGbFlavor + )); + } catch (BadResponseException $e) { + // No! Something failed. Let's find out: + printf("Request: %s\n\nResponse: %s", $e->getRequest(), $e->getResponse()); + } + +As you can see, you're creating a server called "My lovely server" - +this will take a few minutes for the build to complete. You can always +check the progress by logging into your Controller node and running: + +.. code-block:: bash + + nova list + +You can also execute a polling function immediately after the ``create`` +method that checks the build process: + +.. code-block:: php + + use OpenCloud\Compute\Constants\ServerState; + + $callback = function($server) { + if (!empty($server->error)) { + var_dump($server->error); + exit; + } else { + echo sprintf( + "Waiting on %s/%-12s %4s%%", + $server->name(), + $server->status(), + isset($server->progress) ? $server->progress : 0 + ); + } + }; + + $server->waitFor(ServerState::ACTIVE, 600, $callback); + +So, the server will be polled until it is in an ``ACTIVE`` state, with a +timeout of 600 seconds. When the poll happens, the callback function is +executed - which in this case just logs some output. + +More fun with Nova +------------------ + +Once you've booted up your instance, you can use other API operations to +monitor your Compute nodes. To list every node on record, you can +execute: + +.. code-block:: php + + $servers = $compute->serverList(); + + foreach ($servers as $server) { + // do something with each server... + echo $server->name, PHP_EOL; + } + +or, if you know a particular instance ID you can retrieve its details: + +.. code-block:: php + + $server = $compute->server('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'); + +allowing you to update its properties: + +.. code-block:: php + + $server->update(array( + 'name' => 'New server name' + )); + +or delete it entirely: + +.. code-block:: php + + $server->delete(); + +Next steps +---------- + +Read our docs for the `Compute v2 `_ service. diff --git a/doc/getting-started-with-rackspace.rst b/doc/getting-started-with-rackspace.rst new file mode 100644 index 000000000..35317a3e6 --- /dev/null +++ b/doc/getting-started-with-rackspace.rst @@ -0,0 +1,185 @@ +Getting Started with Rackspace +============================== + +Installing the SDK +------------------ + +You must install through Composer, because this library has a few +dependencies: + +.. code-block:: bash + + composer require rackspace/php-opencloud + +Once you have installed the library, you will need to load Composer's +autoloader (which registers all the required namespaces): + +.. code-block:: php + + require 'vendor/autoload.php'; + +And you're good to go! + + +Quick deep-dive: building some Nova instances +--------------------------------------------- + +In this example, you will write code that will create a Cloud Servers instance +running Ubuntu. + + +1. Setup the client and pass in your credentials +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To authenticate against the Rackspace API and use its services: + +.. code-block:: php + + 'foo', + 'apiKey' => 'bar' + )); + +You can see in the first example that the constant +``Rackspace::US_IDENTITY_ENDPOINT`` is just a string representation of +Rackspace's identity endpoint +(``https://identity.api.rackspacecloud.com/v2.0/``). Another difference +is that Rackspace uses API key for authentication, whereas OpenStack +uses a generic password. + + +2. Pick what service you want to use +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In this case, we want to use the Compute (Nova) service: + +.. code-block:: php + + $compute = $client->computeService(null, 'ORD'); + +The first argument is the **name** of the service as it appears in the +OpenStack service catalog. If in doubt, you can leave blank and it will +revert to the default name for the service. The second argument is the +region; you may use: + +- **DFW** (Dallas) +- **ORD** (Chicago) +- **IAD** (Virginia) +- **LON** (London) +- **HKG** (Hong Kong) +- **SYD** (Sydney) + +The third and last argument is the type of URL; you may use either +``publicURL`` or ``internalURL``. If you select ``internalUrl`` all API +traffic will use ServiceNet (internal IPs) and will receive a +performance boost. + +3. Select your server image +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Servers are based on "images", which are effectively just the type of +operating system you want. Let's go through the list and find an Ubuntu +one: + +.. code-block:: php + + $images = $compute->imageList(); + + foreach ($images as $image) { + if (strpos($image->name, 'Ubuntu') !== false) { + $ubuntu = $image; + break; + } + } + +Alternatively, if you already know the image ID, you can do this much +easier: + +.. code-block:: php + + $ubuntu = $compute->image('868a0966-0553-42fe-b8b3-5cadc0e0b3c5'); + + +4. Select your flavor +--------------------- + +There are different server specs - some which offer 1GB RAM, others +which offer a much higher spec. The 'flavor' of a server is its hardware +configuration. So if you want a 2GB instance but don't know the ID, you +have to traverse the list: + +.. code-block:: php + + $flavors = $compute->flavorList(); + + foreach ($flavors as $flavor) { + if (strpos($flavor->name, '2GB') !== false) { + $twoGbFlavor = $flavor; + break; + } + } + +Again, it's much easier if you know the ID: + +.. code-block:: php + + $twoGbFlavor = $compute->flavor('4'); + +5. Thunderbirds are go! +----------------------- + +Okay, you're ready to spin up a server: + +.. code-block:: php + +use Guzzle\Http\Exception\BadResponseException; + + $server = $compute->server(); + + try { + $response = $server->create(array( + 'name' => 'My lovely server', + 'image' => $ubuntu, + 'flavor' => $twoGbFlavor + )); + } catch (BadResponseException $e) { + // No! Something failed. Let's find out: + printf("Request: %s\n\nResponse: %s", $e->getRequest(), $e->getResponse()); + } + +You can also call a polling function that checks on the build process: + +.. code-block:: php + + use OpenCloud\Compute\Constants\ServerState; + + $callback = function($server) { + if (!empty($server->error)) { + var_dump($server->error); + exit; + } else { + echo sprintf( + "Waiting on %s/%-12s %4s%%", + $server->name(), + $server->status(), + isset($server->progress) ? $server->progress : 0 + ); + } + }; + + $server->waitFor(ServerState::ACTIVE, 600, $callback); + +So, the server will be polled until it is in an ``ACTIVE`` state, with a +timeout of 600 seconds. When the poll happens, the callback function is +executed - which in this case just logs some output. + +Next steps +---------- + +Read our docs for the `Compute v2 `_ service. From 6493280bc77bb2ace53a1bf956bc3cff79b4597f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 6 Mar 2015 07:15:29 -0800 Subject: [PATCH 145/181] Adding descriptions to docblocks. --- lib/OpenCloud/Networking/Resource/SecurityGroup.php | 2 ++ lib/OpenCloud/Networking/Resource/SecurityGroupRule.php | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/lib/OpenCloud/Networking/Resource/SecurityGroup.php b/lib/OpenCloud/Networking/Resource/SecurityGroup.php index 2892f5471..b4a8e08d2 100644 --- a/lib/OpenCloud/Networking/Resource/SecurityGroup.php +++ b/lib/OpenCloud/Networking/Resource/SecurityGroup.php @@ -20,6 +20,8 @@ use OpenCloud\Common\Resource\PersistentResource; /** + * A security group is a named container for security group rules, each of which is + * represented by {@see \OpenCloud\Networking\Resource\SecurityGroupRule}. * * @see http://developer.openstack.org/api-ref-networking-v2.html#security_groups * diff --git a/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php b/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php index 5527ce272..06ad028b2 100644 --- a/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php +++ b/lib/OpenCloud/Networking/Resource/SecurityGroupRule.php @@ -20,6 +20,10 @@ use OpenCloud\Common\Resource\PersistentResource; /** + * + * Security group rules provide users the ability to specify the types of traffic that are allowed + * to pass through to and from ports (represented by {@see \OpenCloud\Networking\Resource\Port}) + * on a virtual server instance. * * @see http://developer.openstack.org/api-ref-networking-v2.html#security_groups * From 3409c425da7f8d3955c346b585efcdb22adaee89 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 6 Mar 2015 07:32:30 -0800 Subject: [PATCH 146/181] Fixing typo. --- docs/userguide/Networking/USERGUIDE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/userguide/Networking/USERGUIDE.md b/docs/userguide/Networking/USERGUIDE.md index bfa1a217c..13342977f 100644 --- a/docs/userguide/Networking/USERGUIDE.md +++ b/docs/userguide/Networking/USERGUIDE.md @@ -65,9 +65,9 @@ be assigned to the interfaces plugged into them. When IP addresses are associated with a port, this also implies the port is associated with a subnet because the IP address is taken from the allocation pool for a specific subnet. -* **Security Group**: TODO +* **Security Group**: A named container for security group rules. -* **Security Group Rule**: TODO +* **Security Group Rule**: Provide users the ability to specify the types of traffic that are allowed to pass through to and from ports on a virtual server instance. ## Prerequisites From 78c3dc004e90e295fbdf8e3aa0049438e675560c Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 6 Mar 2015 07:32:38 -0800 Subject: [PATCH 147/181] Adding descriptions for Security Groups and Security Group Rules sections. --- docs/userguide/Networking/USERGUIDE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/userguide/Networking/USERGUIDE.md b/docs/userguide/Networking/USERGUIDE.md index 13342977f..5a7beb07f 100644 --- a/docs/userguide/Networking/USERGUIDE.md +++ b/docs/userguide/Networking/USERGUIDE.md @@ -485,7 +485,7 @@ $port->delete(); ## Security Groups -TODO: Add description +A security group is a named container for [security group rules](#security-group-rules). ### Create a security group @@ -546,7 +546,7 @@ $securityGroup->delete(); ## Security Group Rules -TODO: Add description +A security group rule provides users the ability to specify the types of traffic that are allowed to pass through to and from ports on a virtual server instance. ### Create a security group rule From 79f0c78dba4b01a7835e98c2960e60f0d5005c26 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 6 Mar 2015 07:51:36 -0800 Subject: [PATCH 148/181] Moving @see annotations to their own lines. --- lib/OpenCloud/Networking/Service.php | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/OpenCloud/Networking/Service.php b/lib/OpenCloud/Networking/Service.php index 12bb7477f..e3fcc879e 100644 --- a/lib/OpenCloud/Networking/Service.php +++ b/lib/OpenCloud/Networking/Service.php @@ -51,8 +51,10 @@ public function network($id = null) /** * Creates a new Network and returns it. * - * @param array $params Network creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-network + * @param array $params Network creation parameters. * @return \OpenCloud\Networking\Resource\Network Object representing created network + * + * @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-network */ public function createNetwork(array $params = array()) { @@ -136,8 +138,10 @@ public function subnet($id = null) /** * Creates a new Subnet and returns it. * - * @param array $params Subnet creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-subnet + * @param array $params Subnet creation parameters. * @return \OpenCloud\Networking\Resource\Subnet Object representing created subnet + * + * @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-subnet */ public function createSubnet(array $params = array()) { @@ -221,8 +225,10 @@ public function port($id = null) /** * Creates a new Port and returns it. * - * @param array $params Port creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-port + * @param array $params Port creation parameters. * @return \OpenCloud\Networking\Resource\Port Object representing created port + * + * @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-port */ public function createPort(array $params = array()) { @@ -306,8 +312,10 @@ public function securityGroup($id = null) /** * Creates a new SecurityGroup and returns it. * - * @param array $params SecurityGroup creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-security-group + * @param array $params SecurityGroup creation parameters. * @return \OpenCloud\Networking\Resource\SecurityGroup Object representing created security group + * + * @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-security-group */ public function createSecurityGroup(array $params = array()) { @@ -355,8 +363,10 @@ public function securityGroupRule($id = null) /** * Creates a new SecurityGroupRule and returns it. * - * @param array $params SecurityGroupRule creation parameters. @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-security-group-rule + * @param array $params SecurityGroupRule creation parameters. * @return \OpenCloud\Networking\Resource\SecurityGroupRule Object representing created security group rule + * + * @see https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Networking/USERGUIDE.md#create-a-security-group-rule */ public function createSecurityGroupRule(array $params = array()) { From 1b2f0490604bae0a3bbfe25537c8f323c49ef280 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Fri, 6 Mar 2015 07:53:56 -0800 Subject: [PATCH 149/181] Appeasing the PSR-2 linter. --- lib/OpenCloud/Networking/Resource/SecurityGroup.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/OpenCloud/Networking/Resource/SecurityGroup.php b/lib/OpenCloud/Networking/Resource/SecurityGroup.php index b4a8e08d2..4b2f85efd 100644 --- a/lib/OpenCloud/Networking/Resource/SecurityGroup.php +++ b/lib/OpenCloud/Networking/Resource/SecurityGroup.php @@ -20,7 +20,7 @@ use OpenCloud\Common\Resource\PersistentResource; /** - * A security group is a named container for security group rules, each of which is + * A security group is a named container for security group rules, each of which is * represented by {@see \OpenCloud\Networking\Resource\SecurityGroupRule}. * * @see http://developer.openstack.org/api-ref-networking-v2.html#security_groups From 48f3bebd229810b540b1b0c517bf47017500a9be Mon Sep 17 00:00:00 2001 From: Everett Toews Date: Fri, 6 Mar 2015 17:29:07 -0600 Subject: [PATCH 150/181] Swap support email address for support URL --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 42948e8c3..6031cf4ac 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ Your feedback is appreciated! If you have specific problems or bugs with this SD also have a [mailing list](https://groups.google.com/forum/#!forum/php-opencloud), so feel free to join to keep up to date with all the latest changes and announcements to the library. -For general feedback and support requests, send an email to sdk-support@rackspace.com. +For general feedback and support requests, contact us at https://developer.rackspace.com/support/ You can also find assistance via IRC on #rackspace at freenode.net. From 43ee5426661b61ab784e244794f6649287e13fc8 Mon Sep 17 00:00:00 2001 From: Everett Toews Date: Fri, 6 Mar 2015 17:30:33 -0600 Subject: [PATCH 151/181] Swap support email address for support URL --- docs/getting-started-openstack.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/getting-started-openstack.md b/docs/getting-started-openstack.md index b00e58693..6bb1ae260 100644 --- a/docs/getting-started-openstack.md +++ b/docs/getting-started-openstack.md @@ -198,4 +198,4 @@ $server->delete(); Consult our [documentation](https://github.com/rackspace/php-opencloud/tree/master/docs/userguide) about other services you can use, like [Keystone](https://github.com/rackspace/php-opencloud/tree/master/docs/userguide/Identity) or [Swift](https://github.com/rackspace/php-opencloud/tree/master/docs/userguide/ObjectStore). If you have any questions or -troubles, feel free to e-mail sdk-support@rackspace.com or open a Github issue with details. +troubles, feel free to contact us at https://developer.rackspace.com/support/ or open a Github issue with details. From 67cf54ef207e5811e9f578f0644f9c7f39215f63 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 9 Mar 2015 11:34:55 +0100 Subject: [PATCH 152/181] Use full paths for downloadable samples --- doc/services/database/configurations.rst | 14 +- doc/services/database/datastores.rst | 8 +- doc/services/database/instances.rst | 4 +- doc/services/networking/networks.rst | 12 +- doc/services/networking/ports.rst | 12 +- doc/services/networking/subnets.rst | 12 +- doc/services/orchestration/build-info.rst | 2 +- doc/services/orchestration/events.rst | 6 +- doc/services/orchestration/resource-types.rst | 6 +- doc/services/orchestration/resources.rst | 6 +- doc/services/orchestration/stacks.rst | 24 +- doc/services/orchestration/stacks.rst-e | 299 ++++++++++++++++++ doc/services/orchestration/templates.rst | 4 +- 13 files changed, 354 insertions(+), 55 deletions(-) create mode 100644 doc/services/orchestration/stacks.rst-e diff --git a/doc/services/database/configurations.rst b/doc/services/database/configurations.rst index edfb9dc89..f50619914 100644 --- a/doc/services/database/configurations.rst +++ b/doc/services/database/configurations.rst @@ -22,7 +22,7 @@ Creating a configuration ) )); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Listing configurations @@ -37,7 +37,7 @@ You can list out all the configurations you have created as shown below: /** @var $configuration OpenCloud\Database\Resource\Configuration **/ } -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Retrieving a configuration @@ -50,7 +50,7 @@ You can retrieve a specific configuration, using its ID, as shown below: $configuration = $service->configuration('{configId}'); /** @var OpenCloud\Database\Resource\Configuration **/ -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Updating a configuration @@ -77,7 +77,7 @@ You can patch a configuration as shown below: ) )); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Replacing a configuration @@ -94,7 +94,7 @@ You can replace a configuration as shown below: ) )); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Deleting a configuration @@ -104,7 +104,7 @@ Deleting a configuration $configuration->delete(); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ .. note:: @@ -124,4 +124,4 @@ as shown below: /** @var $instance OpenCloud\Database\Resource\Instance **/ } -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ diff --git a/doc/services/database/datastores.rst b/doc/services/database/datastores.rst index 6ca45daed..ad6d90e85 100644 --- a/doc/services/database/datastores.rst +++ b/doc/services/database/datastores.rst @@ -13,7 +13,7 @@ You can list out all the datastores available as shown below: /** @var $datastore OpenCloud\Database\Resource\Datastore **/ } -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Retrieving a datastore @@ -27,7 +27,7 @@ shown below: /** @var OpenCloud\Database\Resource\Datastore **/ $datastore = $service->datastore('{datastoreId}'); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Listing datastore versions @@ -43,7 +43,7 @@ shown below: /** @var $version OpenCloud\Database\Resource\DatastoreVersion **/ } -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Retrieving a datastore version @@ -56,4 +56,4 @@ below: $datastoreVersion = $datastore->version('{versionId}'); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ diff --git a/doc/services/database/instances.rst b/doc/services/database/instances.rst index 082e56c05..6f3afc1e0 100644 --- a/doc/services/database/instances.rst +++ b/doc/services/database/instances.rst @@ -16,7 +16,7 @@ Create a new instance 'volume' => array('size' => 4) // 4GB of volume disk )); -`Get the executable PHP script for this sample `__ +`Get the executable PHP script for this sample `__ Waiting for the instance to build @@ -96,7 +96,7 @@ Retrieving an instance $instance = $service->instance('{instanceId}'); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Updating an instance diff --git a/doc/services/networking/networks.rst b/doc/services/networking/networks.rst index a290a34e7..b95d44eba 100644 --- a/doc/services/networking/networks.rst +++ b/doc/services/networking/networks.rst @@ -28,7 +28,7 @@ You can create a network as shown in the following example: 'name' => 'My private backend network' )); -`Get the executable PHP script for this example `__ +`Get the executable PHP script for this example `__ Create multiple networks @@ -55,7 +55,7 @@ You can create multiple networks as shown in the following example: /** @var $network OpenCloud\Networking\Resource\Network **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ List networks ------------- @@ -72,7 +72,7 @@ following example: } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get a network @@ -86,7 +86,7 @@ in the following example: /** @var $network OpenCloud\Networking\Resource\Network **/ $network = $networkingService->getNetwork('{networkId}'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Update a network @@ -113,7 +113,7 @@ You can update a network as shown in the following example: 'name' => 'My updated private backend network' )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Delete a network @@ -125,4 +125,4 @@ You can delete a network as shown in the following example: $network->delete(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/networking/ports.rst b/doc/services/networking/ports.rst index 06d2ec2cf..8eeb07bf0 100644 --- a/doc/services/networking/ports.rst +++ b/doc/services/networking/ports.rst @@ -39,7 +39,7 @@ You can create a port as shown in the following example: )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Create multiple ports @@ -68,7 +68,7 @@ You can create multiple ports as shown in the following example: /** @var $port OpenCloud\Networking\Resource\Port **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ List ports @@ -84,7 +84,7 @@ You can list all the ports to which you have access as shown in the following ex /** @var $port OpenCloud\Networking\Resource\Port **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get a port @@ -98,7 +98,7 @@ the following example: /** @var $port OpenCloud\Networking\Resource\Port **/ $port = $networkingService->getPort('{portId}'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Update a port @@ -135,7 +135,7 @@ You can update a port as shown in the following example: ) )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Delete a port @@ -147,4 +147,4 @@ You can delete a port as shown in the following example: $port->delete(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/networking/subnets.rst b/doc/services/networking/subnets.rst index e8d6951a0..9a6c2a7b4 100644 --- a/doc/services/networking/subnets.rst +++ b/doc/services/networking/subnets.rst @@ -42,7 +42,7 @@ You can create a subnet as shown in the following example: 'cidr' => '192.168.199.0/25' )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Create multiple subnets @@ -69,7 +69,7 @@ You can create multiple subnets as shown in the following example: /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ List subnets @@ -85,7 +85,7 @@ following example: /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get a subnet @@ -99,7 +99,7 @@ in the following example: /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ $subnet = $networkingService->getSubnet('{subnetId}'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Update a subnet @@ -137,7 +137,7 @@ You can update a subnet as shown in the following example: 'gatewayIp' => '192.168.62.155' )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Delete a subnet @@ -149,4 +149,4 @@ You can delete a subnet as shown in the following example: $subnet->delete(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/build-info.rst b/doc/services/orchestration/build-info.rst index c30ce5cfa..b4016bab2 100644 --- a/doc/services/orchestration/build-info.rst +++ b/doc/services/orchestration/build-info.rst @@ -12,4 +12,4 @@ build as shown in the following example: /** @var $resourceType OpenCloud\Orchestration\Resource\BuildInfo **/ $buildInfo = $orchestrationService->getBuildInfo(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/events.rst b/doc/services/orchestration/events.rst index 68dbf611b..bceec0f5a 100644 --- a/doc/services/orchestration/events.rst +++ b/doc/services/orchestration/events.rst @@ -19,7 +19,7 @@ shown in the following example: /** @var $stackEvent OpenCloud\Orchestration\Resource\Event **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ List stack resource events @@ -36,7 +36,7 @@ shown in the following example: /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get stack resource event @@ -50,4 +50,4 @@ using the resource event's ID, as shown in the following example: /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ $resourceEvent = $resource->getEvent('c1342a0a-59e6-4413-9af5-07c9cae7d729'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/resource-types.rst b/doc/services/orchestration/resource-types.rst index cd229d660..caa58b013 100644 --- a/doc/services/orchestration/resource-types.rst +++ b/doc/services/orchestration/resource-types.rst @@ -17,7 +17,7 @@ example: /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get resource type @@ -31,7 +31,7 @@ following example: /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ $resourceType = $orchestrationService->getResourceType('OS::Nova::Server'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get resource type template @@ -45,4 +45,4 @@ appear in a template, as shown in the following example: /** @var $resourceTypeTemplate string **/ $resourceTypeTemplate = $resourceType->getTemplate(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/resources.rst b/doc/services/orchestration/resources.rst index 049150f58..b04115122 100644 --- a/doc/services/orchestration/resources.rst +++ b/doc/services/orchestration/resources.rst @@ -19,7 +19,7 @@ example: /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get stack resource @@ -33,7 +33,7 @@ name, as shown in the following example: /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ $resource = $stack->getResource('load-balancer'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get stack resource metadata @@ -47,4 +47,4 @@ shown in the following example: /** @var $resourceMetadata \stdClass **/ $resourceMetadata = $resource->getMetadata(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/stacks.rst b/doc/services/orchestration/stacks.rst index 75a14cd4c..29b6c4f7f 100644 --- a/doc/services/orchestration/stacks.rst +++ b/doc/services/orchestration/stacks.rst @@ -46,7 +46,7 @@ example: ) )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Preview a stack from a template URL @@ -68,7 +68,7 @@ in the following example: ) )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Create stack @@ -111,7 +111,7 @@ example: 'timeoutMins' => 5 )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Create a stack from a template URL @@ -134,7 +134,7 @@ in the following example: 'timeoutMins' => 5 )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ List stacks ----------- @@ -149,7 +149,7 @@ following example: /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get stack @@ -163,7 +163,7 @@ following example: /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ $stack = $orchestrationService->getStack('simple-lamp-setup'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get stack template @@ -178,7 +178,7 @@ used to create the stack. /** @var $stackTemplate string **/ $stackTemplate = $stack->getTemplate(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Update stack @@ -221,7 +221,7 @@ example: 'timeoutMins' => 5 )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Update Stack from Template URL @@ -243,7 +243,7 @@ in the following example: 'timeoutMins' => 5 )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Delete stack @@ -256,7 +256,7 @@ stack *and* the resources as shown in the following example: $stack->delete(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Abandon Stack @@ -277,7 +277,7 @@ abandon the stack as shown in the following example: $abandonStackData = $stack->abandon(); file_put_contents(__DIR__ . '/sample_adopt_stack_data.json', $abandonStackData); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Adopt stack @@ -296,4 +296,4 @@ shown in the following example: 'timeoutMins' => 5 )); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/stacks.rst-e b/doc/services/orchestration/stacks.rst-e new file mode 100644 index 000000000..29b6c4f7f --- /dev/null +++ b/doc/services/orchestration/stacks.rst-e @@ -0,0 +1,299 @@ +Stacks +====== + +A stack is a running instance of a template. When a stack is created, +the `resources <#stack-resources>`__ specified in the template are +created. + + +Preview stack +------------- + +Before you create a stack from a template, you might want to see what +that stack will look like. This is called *previewing the stack*. + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+=====================================================================================================================================================================================================================+=========================================================================================================================+=======================================+=================+=================================================================================================+ +| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters | Yes | - | ``simple-lamp-setup`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of the template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters. For example, see the parameters in `this template section `__ | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | ++-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ + +Preview a stack from a template file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to preview a stack as shown in the following +example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->previewStack(array( + 'name' => 'simple-lamp-setup', + 'template' => file_get_contents(__DIR__ . '/lamp.yml'), + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ) + )); + +`Get the executable PHP script for this example `_ + + +Preview a stack from a template URL +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to preview a stack as shown +in the following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->previewStack(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ) + )); + +`Get the executable PHP script for this example `_ + + +Create stack +------------ + +You can create a stack from a template. This operation takes one parameter, an +associative array, with the following keys: + ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+====================================================================+==========================================================================================================================+=======================================+=================+=================================================================================================+ +| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters. | Yes | - | ``simple-lamp-setup`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('server_hostname' => 'web01')`` | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ +| ``timeoutMins`` | Duration, in minutes, after which stack creation should time out | Integer | Yes | - | 5 | ++-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ + +Create a stack from a template file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to create a stack as shown in the following +example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->createStack(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + + +Create a stack from a template URL +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to create a stack as shown +in the following example: + +.. code-block:: php + + $stack = $orchestrationService->stack(); + $stack->create(array( + 'name' => 'simple-lamp-setup', + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + +List stacks +----------- + +You can list all the stacks that you have created as shown in the +following example: + +.. code-block:: php + + $stacks = $orchestrationService->listStacks(); + foreach ($stacks as $stack) { + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + } + +`Get the executable PHP script for this example `_ + + +Get stack +--------- + +You can retrieve a specific stack using its name, as shown in the +following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->getStack('simple-lamp-setup'); + +`Get the executable PHP script for this example `_ + + +Get stack template +------------------ + +You can retrieve the template used to create a stack. Note that a JSON +string is returned, regardless of whether a JSON or YAML template was +used to create the stack. + +.. code-block:: php + + /** @var $stackTemplate string **/ + $stackTemplate = $stack->getTemplate(); + +`Get the executable PHP script for this example `_ + + +Update stack +------------ + +You can update a running stack. + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+==================================================================+=============================+=======================================+=================+=========================================================================================================+ +| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ +| ``timeoutMins`` | Duration, in minutes, after which stack update should time out | Integer | Yes | - | 5 | ++-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ + + +Update a stack from a template file +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored on your local computer as a JSON or YAML +file, you can use it to update a stack as shown in the following +example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack->update(array( + 'template' => file_get_contents(__DIR__ . '/lamp-updated.yml'), + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + + +Update Stack from Template URL +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your template is stored as a JSON or YAML file in a remote location +accessible via HTTP or HTTPS, you can use it to update a stack as shown +in the following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack->update(array( + 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml', + 'parameters' => array( + 'server_hostname' => 'web01', + 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' + ), + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ + + +Delete stack +------------ + +If you no longer need a stack and all its resources, you can delete the +stack *and* the resources as shown in the following example: + +.. code-block:: php + + $stack->delete(); + +`Get the executable PHP script for this example `_ + + +Abandon Stack +------------- + +.. note:: + + This operation returns data about the abandoned stack as a string. You can + use this data to recreate the stack by using the `adopt stack <#adopt-stack>`_ + operation. + +If you want to delete a stack but preserve all its resources, you can +abandon the stack as shown in the following example: + +.. code-block:: php + + /** @var $abandonStackData string **/ + $abandonStackData = $stack->abandon(); + file_put_contents(__DIR__ . '/sample_adopt_stack_data.json', $abandonStackData); + +`Get the executable PHP script for this example `_ + + +Adopt stack +----------- + +If you have data from an abandoned stack, you can re-create the stack as +shown in the following example: + +.. code-block:: php + + /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ + $stack = $orchestrationService->adoptStack(array( + 'name' => 'simple-lamp-setup', + 'template' => file_get_contents(__DIR__ . '/lamp.yml'), + 'adoptStackData' => $abandonStackData, + 'timeoutMins' => 5 + )); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/templates.rst b/doc/services/orchestration/templates.rst index 5eca2519d..24bc896bc 100644 --- a/doc/services/orchestration/templates.rst +++ b/doc/services/orchestration/templates.rst @@ -31,7 +31,7 @@ file, you can validate it as shown in the following example: // Use $e->getMessage() for explanation of why template is invalid } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Validate Template from URL ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -52,4 +52,4 @@ following example: // Use $e->getMessage() for explanation of why template is invalid } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ From 0df0c84d8b9d73610fb002bc94fb10ce5b1dc037 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 9 Mar 2015 11:37:13 +0100 Subject: [PATCH 153/181] Remove MD links --- doc/services/identity/roles.rst | 57 ++++++++++++--------------------- 1 file changed, 21 insertions(+), 36 deletions(-) diff --git a/doc/services/identity/roles.rst b/doc/services/identity/roles.rst index 96a56488f..09f0600fa 100644 --- a/doc/services/identity/roles.rst +++ b/doc/services/identity/roles.rst @@ -1,9 +1,6 @@ Roles ===== -Intro ------ - A role is a personality that a user assumes when performing a specific set of operations. A role includes a set of rights and privileges. A user assuming a role inherits the rights and privileges associated with @@ -13,12 +10,6 @@ determines how to interpret a user's roles. A role that grants access to a list of operations or resources within one service may grant access to a completely different list when interpreted by a different service. -Setup ------ - -Role objects are instantiated from the Identity service. For more -details, see the `Service `__ docs. - Useful object properties/methods -------------------------------- @@ -37,16 +28,13 @@ List roles This call lists the global roles available within a specified service. -.. code:: php - - $roles = $service->getRoles(); +.. code-block:: php - foreach ($roles as $role) { - // ... - } + $roles = $service->getRoles(); -For more information about how to use iterators, see the -`documentation <../Iterators.md>`__. + foreach ($roles as $role) { + // ... + } Get role -------- @@ -54,39 +42,36 @@ Get role This call lists detailed information (id, name, description) for a specified role. -.. code:: php +.. code-block:: php + + $role = $service->getRole('{roleId}'); - $roleId = '123abc'; - $role = $service->getRole($roleId); Add/delete user roles --------------------- -To add/remove user roles, you must first instantiate a -`user `__ object: +.. code-block:: php + + $user = $service->getUser('{userId}'); -.. code:: php + $roleId = '{roleId}'; - $roleId = '123abc'; + // add role to user + $user->addRole($roleId); - // add role to user - $user->addRole($roleId); + // remove role from user + $user->removeRole($roleId); - // remove role from user - $user->removeRole($roleId); List user global roles ---------------------- This call returns a list of global roles associated with a user: -.. code:: php - - $roles = $user->getRoles(); +.. code-block:: php - foreach ($roles as $role) { - // ... - } + $roles = $user->getRoles(); -For more information about how to use iterators, see the -`documentation <../Iterators.md>`__. + foreach ($roles as $role) { + // ... + } From 59eefc237cc9c19fed69a3582dbb6c7cce02d2e3 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 9 Mar 2015 11:43:57 +0100 Subject: [PATCH 154/181] Add Security Groups docs --- doc/services/networking/index.rst | 10 +++ .../networking/security-group-rules.rst | 61 +++++++++++++++++ doc/services/networking/security-groups.rst | 67 +++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 doc/services/networking/security-group-rules.rst create mode 100644 doc/services/networking/security-groups.rst diff --git a/doc/services/networking/index.rst b/doc/services/networking/index.rst index 515f9ddce..335f6a10c 100644 --- a/doc/services/networking/index.rst +++ b/doc/services/networking/index.rst @@ -23,6 +23,8 @@ Operations networks subnets ports + security-groups + security-group-rules Glossary -------- @@ -49,6 +51,14 @@ Glossary associated with a subet, as the IP address is taken from the allocation pool for a specific subnet. + security group + A security group is a named container for security group rules. + + security group rule + A security group rule provides users the ability to specify the types of + traffic that are allowed to pass through to and from ports on a virtual + server instance. + Further links ------------- diff --git a/doc/services/networking/security-group-rules.rst b/doc/services/networking/security-group-rules.rst new file mode 100644 index 000000000..1ca6041d1 --- /dev/null +++ b/doc/services/networking/security-group-rules.rst @@ -0,0 +1,61 @@ +Security Group Rules +==================== + +Create a security group rule +---------------------------- + +This operation takes one parameter, an associative array, with the +following keys: + ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++=======================+===================================================================================================================================================================================================================================================================+=======================================+=============+=================+============================================+ +| ``securityGroupId`` | The security group ID to associate with this security group rule. | String | Yes | - | ``2076db17-a522-4506-91de-c6dd8e837028`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| ``direction`` | The direction in which the security group rule is applied. For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. | String (``ingress`` or ``egress``) | Yes | - | ``ingress`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| ``ethertype`` | Must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. | String (``IPv4`` or ``IPv6``) | No | ``IPv4`` | ``IPv6`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| ``portRangeMin`` | The minimum port number in the range that is matched by the security group rule. If the protocol is TCP or UDP, this value must be less than or equal to the value of the ``portRangeMax`` attribute. If the protocol is ICMP, this value must be an ICMP type. | Integer | No | ``null`` | ``80`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| ``portRangeMax`` | The maximum port number in the range that is matched by the security group rule. The port\_range\_min attribute constrains the attribute. If the protocol is ICMP, this value must be an ICMP type. | Integer | No | ``null`` | ``80`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| ``protocol`` | The protocol that is matched by the security group rule. | String (``tcp``, ``udp``, ``icmp``) | No | ``null`` | ``tcp`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| ``remoteGroupId`` | The remote group ID to be associated with this security group rule. You can specify either ``remoteGroupId`` or ``remoteGroupPrefix``. | String | Optional | ``null`` | ``85cc3048-abc3-43cc-89b3-377341426ac5`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ +| ``remoteIpPrefix`` | The remote IP prefix to be associated with this security group rule. You can specify either ``remoteGroupId`` or ``remoteGroupPrefix``. | String | Optional | ``null`` | ``192.168.5.0`` | ++-----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-------------+-----------------+--------------------------------------------+ + +You can create a security group rule as shown in the following example: + +.. code:: php + + /** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ + $securityGroupRule = $networkingService->createSecurityGroupRule(array( + 'securityGroupId' => '2076db17-a522-4506-91de-c6dd8e837028', + 'direction' => 'egress', + 'ethertype' => 'IPv4', + 'portRangeMin' => 80, + 'portRangeMax' => 80, + 'protocol' => 'tcp', + 'remoteGroupId' => '85cc3048-abc3-43cc-89b3-377341426ac5' + )); + +`Get the executable PHP script for this example `_ + + +List security group rules +------------------------- + +You can list all the security group rules to which you have access as +shown in the following example: + +.. code:: php + + $securityGroupRules = $networkingService->listSecurityGroupRules(); + foreach ($securityGroupRules as $securityGroupRule) { + /** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ + } + +`Get the executable PHP script for this example `_ diff --git a/doc/services/networking/security-groups.rst b/doc/services/networking/security-groups.rst new file mode 100644 index 000000000..2ec8b384d --- /dev/null +++ b/doc/services/networking/security-groups.rst @@ -0,0 +1,67 @@ +Security Groups +=============== + +Create a security group +~~~~~~~~~~~~~~~~~~~~~~~ + +This operation takes one parameter, an associative array, with the +following keys: + ++-------------------+--------------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------------------+ +| Name | Description | Data type | Required? | Default value | Example value | ++===================+================================================================================+=============+=============+=================+=====================================+ +| ``name`` | A human-readable name for the security group. This name might not be unique. | String | Yes | - | ``new-webservers`` | ++-------------------+--------------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------------------+ +| ``description`` | Description of the security group. | String | No | ``null`` | ``security group for webservers`` | ++-------------------+--------------------------------------------------------------------------------+-------------+-------------+-----------------+-------------------------------------+ + +You can create a security group as shown in the following example: + +.. code-block:: php + + /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ + $securityGroup = $networkingService->createSecurityGroup(array( + 'name' => 'new-webservers', + 'description' => 'security group for webservers' + )); + +`Get the executable PHP script for this example `_ + +List security groups +~~~~~~~~~~~~~~~~~~~~ + +You can list all the security groups to which you have access as shown +in the following example: + +.. code-block:: php + + $securityGroups = $networkingService->listSecurityGroups(); + foreach ($securityGroups as $securityGroup) { + /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ + } + +`Get the executable PHP script for this example `_ + +Get a security group +~~~~~~~~~~~~~~~~~~~~ + +You can retrieve a specific security group by using that security +group’s ID, as shown in the following example: + +.. code-block:: php + + /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ + $securityGroup = $networkingService->getSecurityGroup('{secGroupId}'); + +`Get the executable PHP script for this example `_ + +Delete a security group +~~~~~~~~~~~~~~~~~~~~~~~ + +You can delete a security group as shown in the following example: + +.. code-block:: php + + $securityGroup->delete(); + +`Get the executable PHP script for this example `_ From 9ef5e6856a31c012fd0e7a4ab21e0ad35308217e Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 9 Mar 2015 16:54:07 +0100 Subject: [PATCH 155/181] Fixing relative links --- doc/services/networking/security-groups.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/services/networking/security-groups.rst b/doc/services/networking/security-groups.rst index 2ec8b384d..cde5c9a2d 100644 --- a/doc/services/networking/security-groups.rst +++ b/doc/services/networking/security-groups.rst @@ -40,7 +40,7 @@ in the following example: /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ } -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Get a security group ~~~~~~~~~~~~~~~~~~~~ @@ -53,7 +53,7 @@ group’s ID, as shown in the following example: /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ $securityGroup = $networkingService->getSecurityGroup('{secGroupId}'); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ Delete a security group ~~~~~~~~~~~~~~~~~~~~~~~ @@ -64,4 +64,4 @@ You can delete a security group as shown in the following example: $securityGroup->delete(); -`Get the executable PHP script for this example `_ +`Get the executable PHP script for this example `_ From 916911cfbff0b3e3ccfab2105d238ed100fe405f Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 9 Mar 2015 17:05:37 +0100 Subject: [PATCH 156/181] Use :doc: to link to inline documents --- doc/index.rst | 6 +++--- doc/services/identity/roles.rst | 1 + doc/services/identity/tokens.rst | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/doc/index.rst b/doc/index.rst index 297a64c6c..fc7c280c3 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -26,9 +26,9 @@ This assumes your application's PHP files are located in the same folder as ``vendor/``. If your files are located elsewhere, please supply the path to ``vendor/autoload.php`` in the require statement above. -Read the `OpenStack Getting Started guide `_ -or `Rackspace Getting Started guide `_ to help -you get started with basic Compute operations. +Read the :doc:`getting-started-with-openstack` or +:doc:`getting-started-with-rackspace` to help you get started with basic +Compute operations. Services -------- diff --git a/doc/services/identity/roles.rst b/doc/services/identity/roles.rst index 09f0600fa..614518b9b 100644 --- a/doc/services/identity/roles.rst +++ b/doc/services/identity/roles.rst @@ -36,6 +36,7 @@ This call lists the global roles available within a specified service. // ... } + Get role -------- diff --git a/doc/services/identity/tokens.rst b/doc/services/identity/tokens.rst index f49484105..e4601c7c4 100644 --- a/doc/services/identity/tokens.rst +++ b/doc/services/identity/tokens.rst @@ -76,7 +76,7 @@ Interacting with users $user = $service->resource('User', $data); To see which methods you can call on ``$user`` (which implements -``OpenCloud\Identity\Resource\User``), see our `user documentation `_ +``OpenCloud\Identity\Resource\User``), see our :doc:`user documentation ` which accompanies this guide. @@ -89,7 +89,7 @@ Interacting with tenants $tenant = $service->resource('Tenant', $data); To see which methods you can call on ``$tenant`` (which implements -``OpenCloud\Identity\Resource\Tenant``), see our `user documentation `_ +``OpenCloud\Identity\Resource\Tenant``), see our :doc:`user documentation ` which accompanies this guide. From 25de01ed8d4b5b65719251bb54430ae5f824aba2 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 9 Mar 2015 18:23:21 +0100 Subject: [PATCH 157/181] Adding sphinx extension --- doc/requirements.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 doc/requirements.txt diff --git a/doc/requirements.txt b/doc/requirements.txt new file mode 100644 index 000000000..9873100ea --- /dev/null +++ b/doc/requirements.txt @@ -0,0 +1 @@ +sphinxcontrib.phpdomain From ba89da5f301607c0c01fd6897a7bb0d3ee2c4637 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 9 Mar 2015 18:31:28 +0100 Subject: [PATCH 158/181] Use correct ext name --- doc/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/requirements.txt b/doc/requirements.txt index 9873100ea..3f092f372 100644 --- a/doc/requirements.txt +++ b/doc/requirements.txt @@ -1 +1 @@ -sphinxcontrib.phpdomain +sphinxcontrib-phpdomain From 840c1407d2b1d5fbba5d2d5989c95d56716006ee Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 10 Mar 2015 11:44:00 +0100 Subject: [PATCH 159/181] Adding sample links --- doc/services/compute/flavors.rst | 2 + doc/services/compute/images.rst | 3 + doc/services/compute/keypairs.rst | 5 + doc/services/compute/servers.rst | 29 +- doc/services/identity/users.rst | 14 + doc/services/load-balancer/access.rst | 7 +- doc/services/load-balancer/load-balancer.rst | 14 +- doc/services/load-balancer/ssl.rst | 2 + doc/services/object-store/access.rst | 11 +- doc/services/object-store/account.rst | 6 + doc/services/object-store/cdn.rst | 6 + doc/services/object-store/containers.rst | 22 ++ doc/services/object-store/objects.rst | 22 ++ doc/services/orchestration/stacks.rst-e | 299 ------------------- doc/services/queues/claims.rst | 2 + doc/services/queues/messages.rst | 2 + doc/services/queues/queues.rst | 11 + doc/services/volume/snapshots.rst | 8 + doc/services/volume/volumes.rst | 9 + 19 files changed, 162 insertions(+), 312 deletions(-) delete mode 100644 doc/services/orchestration/stacks.rst-e diff --git a/doc/services/compute/flavors.rst b/doc/services/compute/flavors.rst index eeb447d3c..470ce8368 100644 --- a/doc/services/compute/flavors.rst +++ b/doc/services/compute/flavors.rst @@ -20,6 +20,8 @@ List flavors /** @param $flavor OpenCloud\Common\Resource\FlavorInterface */ } +`Get the executable PHP script for this example `_ + Detailed results ~~~~~~~~~~~~~~~~ diff --git a/doc/services/compute/images.rst b/doc/services/compute/images.rst index fb68af7f7..570790c04 100644 --- a/doc/services/compute/images.rst +++ b/doc/services/compute/images.rst @@ -23,6 +23,9 @@ Below is the simplest usage for retrieving a list of images: } +`Get the executable PHP script for this example `_ + + Detailed results ~~~~~~~~~~~~~~~~ diff --git a/doc/services/compute/keypairs.rst b/doc/services/compute/keypairs.rst index f7e67b113..823fcf5a2 100644 --- a/doc/services/compute/keypairs.rst +++ b/doc/services/compute/keypairs.rst @@ -21,6 +21,8 @@ value is automatically generated for you. $pubKey = $keypair->getPublicKey(); $priKey = $keypair->getPrivateKey(); +`Get the executable PHP script for this example `_ + Upload existing keypair ----------------------- @@ -41,6 +43,9 @@ filesystem. 'publicKey' => $content )); +`Get the executable PHP script for this example `_ + + List keypairs ------------- diff --git a/doc/services/compute/servers.rst b/doc/services/compute/servers.rst index 229e8e4ff..8a55ce57f 100644 --- a/doc/services/compute/servers.rst +++ b/doc/services/compute/servers.rst @@ -49,6 +49,9 @@ URL parameters for filtering servers | RAX-SI:image_schedule | If scheduled images enabled or not. If the value is TRUE, the list contains all servers that have an image schedule resource set on them. If the value is set to FALSE, the list contains all servers that do not have an image schedule. | bool | +--------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------+ +`Get the executable PHP script for this example `_ + + Create server ------------- @@ -59,19 +62,22 @@ Now we're ready to create our instance: .. code-block:: php - $server = $compute->server(); + $server = $compute->server(); - $server->create(array( - 'name' => 'My lovely server', - 'imageId' => '{imageId}', - 'flavorId' => '{flavorId}', - )); + $server->create(array( + 'name' => 'My lovely server', + 'imageId' => '{imageId}', + 'flavorId' => '{flavorId}', + )); It's always best to be defensive when executing functionality over HTTP; you can achieve this best by wrapping calls in a try/catch block. It allows you to debug your failed operations in a graceful and efficient manner. +`Get the executable PHP script for this example `_ + + Using a bootable volume ~~~~~~~~~~~~~~~~~~~~~~~ @@ -98,6 +104,9 @@ you can achieve this best by wrapping calls in a try/catch block. It allows you to debug your failed operations in a graceful and efficient manner. +`Get the executable PHP script for this example `_ + + Create parameters ~~~~~~~~~~~~~~~~~ @@ -146,6 +155,8 @@ as usual, with one extra parameter: So, as you can see, you specify the **name** of an existing keypair that you previously created on the API. +`Get the executable PHP script for this example `_ + Creating a server with personality files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -176,6 +187,10 @@ attributes are detailed in the next section. 'name' => 'NEW SERVER NAME' )); + +`Get the executable PHP script for this example `_ + + Updatable attributes ~~~~~~~~~~~~~~~~~~~~ @@ -195,3 +210,5 @@ Delete server .. code-block:: php $server->delete(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/identity/users.rst b/doc/services/identity/users.rst index b55236a74..944888902 100644 --- a/doc/services/identity/users.rst +++ b/doc/services/identity/users.rst @@ -34,6 +34,8 @@ List users // ... } +`Get the executable PHP script for this example `_ + Retrieve a user by username --------------------------- @@ -42,6 +44,8 @@ Retrieve a user by username $user = $service->getUser('jamie'); +`Get the executable PHP script for this example `_ + Retrieve a user by user ID -------------------------- @@ -52,6 +56,8 @@ Retrieve a user by user ID $user = $service->getUser('{userId}', UserConst::MODE_ID); +`Get the executable PHP script for this example `_ + Retrieve a user by email address -------------------------------- @@ -62,6 +68,8 @@ Retrieve a user by email address $user = $service->getUser('{emailAddress}', UserConst::MODE_EMAIL); +`Get the executable PHP script for this example `_ + Create user ----------- @@ -98,6 +106,8 @@ automatically generated and provided in the response. // show generated password echo $user->getPassword(); +`Get the executable PHP script for this example `_ + Update user ----------- @@ -129,6 +139,8 @@ Delete user $user->delete(); +`Get the executable PHP script for this example `_ + List credentials ---------------- @@ -159,3 +171,5 @@ you: $user->resetApiKey(); echo $user->getApiKey(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/load-balancer/access.rst b/doc/services/load-balancer/access.rst index 4387dd8de..42cd68315 100644 --- a/doc/services/load-balancer/access.rst +++ b/doc/services/load-balancer/access.rst @@ -68,6 +68,11 @@ You can add network items to a load balancer's access list very easily: In the above example, we allowed access for 1 IP address, and used the "0.0.0.0" wildcard to blacklist all other traffic. +Get the executable PHP scripts for this example: + +* `Blacklist IP range `_ +* `Limit access to 1 IP `_ + Remove Network Item From Access List ------------------------------------ @@ -76,4 +81,4 @@ You an remove a network item from a load balancer's access list: .. code-block:: php - $networkItem->delete(); + $networkItem->delete(); diff --git a/doc/services/load-balancer/load-balancer.rst b/doc/services/load-balancer/load-balancer.rst index 7071794df..d7867755d 100644 --- a/doc/services/load-balancer/load-balancer.rst +++ b/doc/services/load-balancer/load-balancer.rst @@ -51,9 +51,11 @@ port number, before submitting to the API: For a full list of available `protocols <#protocols>`_ and `algorithms <#algorithms>`_ please see the sections below. +`Get the executable PHP script for this example `_ -List Load Balancer Details --------------------------- + +Get Load Balancer Details +------------------------- You can retrieve a single load balancer's details by using its ID: @@ -64,7 +66,7 @@ You can retrieve a single load balancer's details by using its ID: List Load Balancers -~~~~~~~~~~~~~~~~~~~ +------------------- You can retrieve a list of all your load balancers: @@ -76,6 +78,8 @@ You can retrieve a list of all your load balancers: /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ } +`Get the executable PHP script for this example `_ + Update a Load Balancer ---------------------- @@ -121,6 +125,8 @@ When you no longer have a need for the load balancer, you can remove it: $loadBalancer->delete(); +`Get the executable PHP script for this example `_ + Protocols --------- @@ -159,7 +165,7 @@ You can programmatically list all supported load balancing algorithms: .. code-block:: php $algorithms = $service->algorithmList(); - + foreach ($algorithms as $algorithm) { /** @var $algorithm OpenCloud\LoadBalancer\Resource\Algorithm **/ } diff --git a/doc/services/load-balancer/ssl.rst b/doc/services/load-balancer/ssl.rst index 12b28a6af..413bdc612 100644 --- a/doc/services/load-balancer/ssl.rst +++ b/doc/services/load-balancer/ssl.rst @@ -43,6 +43,8 @@ For a full list, with explanations, of required and optional attributes, please consult the `official documentation `__ +`Get the executable PHP script for this example `_ + Delete configuration -------------------- diff --git a/doc/services/object-store/access.rst b/doc/services/object-store/access.rst index 62cb541ca..40fe61670 100644 --- a/doc/services/object-store/access.rst +++ b/doc/services/object-store/access.rst @@ -23,6 +23,11 @@ in a global state: The string argument of ``setTempUrlSecret()`` is optional - if left out, the SDK will generate a random hashed secret for you. +Get the executable PHP script for this example: + +* `Specify a URL secret `_ +* `Generate random URL secret `_ + Create a temporary URL ---------------------- @@ -32,14 +37,16 @@ your object. To allow GET access to your object for 1 minute: .. code-block:: php - $object->getTemporaryUrl(60, 'GET'); + $object->getTemporaryUrl(60, 'GET'); To allow PUT access for 1 hour: .. code-block:: php - $object->getTemporaryUrl(360, 'PUT'); + $object->getTemporaryUrl(360, 'PUT'); + +`Get the executable PHP script for this example `_ Hosting HTML sites on CDN diff --git a/doc/services/object-store/account.rst b/doc/services/object-store/account.rst index fb51c8855..50c17f1a8 100644 --- a/doc/services/object-store/account.rst +++ b/doc/services/object-store/account.rst @@ -29,6 +29,8 @@ Retrieve total container count $account->getContainerCount(); +`Get the executable PHP script for this example `_ + Retrieve total object count --------------------- @@ -37,6 +39,8 @@ Retrieve total object count $account->getObjectCount(); +`Get the executable PHP script for this example `_ + Retrieve total bytes used ------------------------- @@ -44,3 +48,5 @@ Retrieve total bytes used .. code-block:: php $account->getBytesUsed(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/object-store/cdn.rst b/doc/services/object-store/cdn.rst index 5ad72b6cd..eb29bb27f 100644 --- a/doc/services/object-store/cdn.rst +++ b/doc/services/object-store/cdn.rst @@ -29,6 +29,8 @@ execute the method on: /** @var $cdnContainer OpenCloud\ObjectStore\Resource\CDNContainer */ } +`Get the executable PHP script for this example `_ + CDN-enable a container ---------------------- @@ -47,6 +49,8 @@ refetches and caches the object for the TTL period. $container->enableCdn(); +`Get the executable PHP script for this example `_ + CDN-disable a container ----------------------- @@ -55,6 +59,8 @@ CDN-disable a container $container->disableCdn(); +`Get the executable PHP script for this example `_ + Operations on CDN-enabled containers ------------------------------------ diff --git a/doc/services/object-store/containers.rst b/doc/services/object-store/containers.rst index 4b9c66ac3..a2f0485e8 100644 --- a/doc/services/object-store/containers.rst +++ b/doc/services/object-store/containers.rst @@ -22,6 +22,9 @@ Forward slashes are not currently permitted. (such as spaces or non-English characters), you must ensure they are encoded with `urlencode `_ before passing them in +`Get the executable PHP script for this example `_ + + List containers --------------- @@ -42,6 +45,8 @@ memcmp() function, regardless of text encoding. The list is limited to 10,000 containers at a time. To work with larger collections, please read the next section. +`Get the executable PHP script for this example `_ + Filtering large collections ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -82,6 +87,8 @@ To retrieve a certain container: /** @param $container OpenCloud\ObjectStore\Resource\Container */ $container = $service->getContainer('{containerName}'); +`Get the executable PHP script for this example `_ + Retrieve a container's name ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -98,6 +105,8 @@ Retrieve a container's object count $count = $container->getObjectCount(); +`Get the executable PHP script for this example `_ + Retrieve a container's total bytes used ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -106,6 +115,8 @@ Retrieve a container's total bytes used $bytes = $container->getBytesUsed(); +`Get the executable PHP script for this example `_ + Delete container ---------------- @@ -129,6 +140,8 @@ before deleting it. This is done for you if you set the You can also `delete all objects <#deleting-all-objects-inside-a-container>`_ first, and then call ``delete``. +`Get the executable PHP script for this example `_ + Deleting all objects inside a container --------------------------------------- @@ -137,6 +150,8 @@ Deleting all objects inside a container $container->deleteAllObjects(); +`Get the executable PHP script for this example `_ + Create or update container metadata ----------------------------------- @@ -158,6 +173,8 @@ to the current metadata: 'Publisher' => 'Hogarth' )); +`Get the executable PHP script for this example `_ + Container quotas ---------------- @@ -184,6 +201,11 @@ And to retrieve them: echo $container->getCountQuota(); echo $container->getBytesQuota(); +Get the executable PHP scripts for this example: + +* `Set bytes quota `_ +* `Set count quota `_ + Access log delivery ------------------- diff --git a/doc/services/object-store/objects.rst b/doc/services/object-store/objects.rst index e38e0eb8b..0eb0ea836 100644 --- a/doc/services/object-store/objects.rst +++ b/doc/services/object-store/objects.rst @@ -43,6 +43,8 @@ its path: The resource handle will be automatically closed by Guzzle in its destructor, so there is no need to execute ``fclose``. +`Get the executable PHP script for this example `_ + Upload a single file (under 5GB) with metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -80,6 +82,8 @@ file handle resource, or a string representation of object content (a temporary resource will be created in memory), and the third is an array of additional headers. +`Get the executable PHP script for this example `_ + Batch upload multiple files (each under 5GB) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -108,6 +112,8 @@ also specify *either* a path key (to an existing file), or a ``body``. The ``body`` can either be a PHP resource or a string representation of the content you want to upload. +`Get the executable PHP script for this example `_ + Upload large files (over 5GB) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -142,6 +148,8 @@ In Swift terminology, the name for this process is *Dynamic Large Object (DLO)*. To find out more details, please consult the `official documentation `_. +`Get the executable PHP script for this example `_ + List objects in a container --------------------------- @@ -166,6 +174,8 @@ docs objectList(array('prefix' => 'logFile_')); +`Get the executable PHP script for this example `_ + Get object ---------- @@ -313,6 +323,8 @@ destination path: Where ``container_2`` is the name of the container, and ``new_object_name`` is the name of the object inside the container that does not exist yet. +`Get the executable PHP script for this example `_ + Get object metadata ------------------- @@ -346,6 +358,8 @@ You can also update to get the latest metadata: $object->retrieveMetadata(); +`Get the executable PHP script for this example `_ + Update object metadata ---------------------- @@ -386,6 +400,8 @@ you want to append values to your metadata, use the correct method: $object->saveMetadata($metadata); +`Get the executable PHP script for this example `_ + Extract archive --------------- @@ -406,6 +422,8 @@ the first argument). If you do this, the API will create the containers necessary to house the extracted files - this is done based on the filenames inside the archive. +`Get the executable PHP script for this example `_ + Delete object ------------- @@ -414,6 +432,8 @@ Delete object $object->delete(); +`Get the executable PHP script for this example `_ + Delete multiple objects ----------------------- @@ -425,3 +445,5 @@ Bulk delete a set of paths: $pathsToBeDeleted = array('/container_1/old_file', '/container_2/notes.txt', '/container_1/older_file.log'); $service->bulkDelete($pathsToBeDeleted); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/orchestration/stacks.rst-e b/doc/services/orchestration/stacks.rst-e deleted file mode 100644 index 29b6c4f7f..000000000 --- a/doc/services/orchestration/stacks.rst-e +++ /dev/null @@ -1,299 +0,0 @@ -Stacks -====== - -A stack is a running instance of a template. When a stack is created, -the `resources <#stack-resources>`__ specified in the template are -created. - - -Preview stack -------------- - -Before you create a stack from a template, you might want to see what -that stack will look like. This is called *previewing the stack*. - -This operation takes one parameter, an associative array, with the -following keys: - -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+===================+=====================================================================================================================================================================================================================+=========================================================================================================================+=======================================+=================+=================================================================================================+ -| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters | Yes | - | ``simple-lamp-setup`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``templateUrl`` | URL of the template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``parameters`` | Arguments to the template, based on the template's parameters. For example, see the parameters in `this template section `__ | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | -+-------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ - -Preview a stack from a template file -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your template is stored on your local computer as a JSON or YAML -file, you can use it to preview a stack as shown in the following -example: - -.. code-block:: php - - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - $stack = $orchestrationService->previewStack(array( - 'name' => 'simple-lamp-setup', - 'template' => file_get_contents(__DIR__ . '/lamp.yml'), - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ) - )); - -`Get the executable PHP script for this example `_ - - -Preview a stack from a template URL -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your template is stored as a JSON or YAML file in a remote location -accessible via HTTP or HTTPS, you can use it to preview a stack as shown -in the following example: - -.. code-block:: php - - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - $stack = $orchestrationService->previewStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ) - )); - -`Get the executable PHP script for this example `_ - - -Create stack ------------- - -You can create a stack from a template. This operation takes one parameter, an -associative array, with the following keys: - -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+===================+====================================================================+==========================================================================================================================+=======================================+=================+=================================================================================================+ -| ``name`` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, ``_``, ``-`` or ``.`` characters. | Yes | - | ``simple-lamp-setup`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('server_hostname' => 'web01')`` | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ -| ``timeoutMins`` | Duration, in minutes, after which stack creation should time out | Integer | Yes | - | 5 | -+-------------------+--------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------+---------------------------------------+-----------------+-------------------------------------------------------------------------------------------------+ - -Create a stack from a template file -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your template is stored on your local computer as a JSON or YAML -file, you can use it to create a stack as shown in the following -example: - -.. code-block:: php - - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - $stack = $orchestrationService->createStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - -`Get the executable PHP script for this example `_ - - -Create a stack from a template URL -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your template is stored as a JSON or YAML file in a remote location -accessible via HTTP or HTTPS, you can use it to create a stack as shown -in the following example: - -.. code-block:: php - - $stack = $orchestrationService->stack(); - $stack->create(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - -`Get the executable PHP script for this example `_ - -List stacks ------------ - -You can list all the stacks that you have created as shown in the -following example: - -.. code-block:: php - - $stacks = $orchestrationService->listStacks(); - foreach ($stacks as $stack) { - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - } - -`Get the executable PHP script for this example `_ - - -Get stack ---------- - -You can retrieve a specific stack using its name, as shown in the -following example: - -.. code-block:: php - - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - $stack = $orchestrationService->getStack('simple-lamp-setup'); - -`Get the executable PHP script for this example `_ - - -Get stack template ------------------- - -You can retrieve the template used to create a stack. Note that a JSON -string is returned, regardless of whether a JSON or YAML template was -used to create the stack. - -.. code-block:: php - - /** @var $stackTemplate string **/ - $stackTemplate = $stack->getTemplate(); - -`Get the executable PHP script for this example `_ - - -Update stack ------------- - -You can update a running stack. - -This operation takes one parameter, an associative array, with the -following keys: - -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| Name | Description | Data type | Required? | Default value | Example value | -+===================+==================================================================+=============================+=======================================+=================+=========================================================================================================+ -| ``template`` | Template contents | String. JSON or YAML | No, if ``templateUrl`` is specified | ``null`` | ``heat_template_version: 2013-05-23\ndescription: LAMP server\n`` | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| ``templateUrl`` | URL of template file | String. HTTP or HTTPS URL | No, if ``template`` is specified | ``null`` | ``https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml`` | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| ``parameters`` | Arguments to the template, based on the template's parameters | Associative array | No | ``null`` | ``array('flavor_id' => 'general1-1')`` | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ -| ``timeoutMins`` | Duration, in minutes, after which stack update should time out | Integer | Yes | - | 5 | -+-------------------+------------------------------------------------------------------+-----------------------------+---------------------------------------+-----------------+---------------------------------------------------------------------------------------------------------+ - - -Update a stack from a template file -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your template is stored on your local computer as a JSON or YAML -file, you can use it to update a stack as shown in the following -example: - -.. code-block:: php - - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - $stack->update(array( - 'template' => file_get_contents(__DIR__ . '/lamp-updated.yml'), - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - -`Get the executable PHP script for this example `_ - - -Update Stack from Template URL -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If your template is stored as a JSON or YAML file in a remote location -accessible via HTTP or HTTPS, you can use it to update a stack as shown -in the following example: - -.. code-block:: php - - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - $stack->update(array( - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 - )); - -`Get the executable PHP script for this example `_ - - -Delete stack ------------- - -If you no longer need a stack and all its resources, you can delete the -stack *and* the resources as shown in the following example: - -.. code-block:: php - - $stack->delete(); - -`Get the executable PHP script for this example `_ - - -Abandon Stack -------------- - -.. note:: - - This operation returns data about the abandoned stack as a string. You can - use this data to recreate the stack by using the `adopt stack <#adopt-stack>`_ - operation. - -If you want to delete a stack but preserve all its resources, you can -abandon the stack as shown in the following example: - -.. code-block:: php - - /** @var $abandonStackData string **/ - $abandonStackData = $stack->abandon(); - file_put_contents(__DIR__ . '/sample_adopt_stack_data.json', $abandonStackData); - -`Get the executable PHP script for this example `_ - - -Adopt stack ------------ - -If you have data from an abandoned stack, you can re-create the stack as -shown in the following example: - -.. code-block:: php - - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ - $stack = $orchestrationService->adoptStack(array( - 'name' => 'simple-lamp-setup', - 'template' => file_get_contents(__DIR__ . '/lamp.yml'), - 'adoptStackData' => $abandonStackData, - 'timeoutMins' => 5 - )); - -`Get the executable PHP script for this example `_ diff --git a/doc/services/queues/claims.rst b/doc/services/queues/claims.rst index 7e375c8d3..1111cb9eb 100644 --- a/doc/services/queues/claims.rst +++ b/doc/services/queues/claims.rst @@ -67,6 +67,8 @@ limit parameter is optional. 'ttl' => 5 * Datetime::MINUTE )); +`Get the executable PHP script for this example `_ + Query claim ----------- diff --git a/doc/services/queues/messages.rst b/doc/services/queues/messages.rst index ea23caea3..3a5dee89d 100644 --- a/doc/services/queues/messages.rst +++ b/doc/services/queues/messages.rst @@ -50,6 +50,8 @@ Posting a single message 'ttl' => 2 * Datetime::DAY )); +`Get the executable PHP script for this example `_ + Post a batch of messages ~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/services/queues/queues.rst b/doc/services/queues/queues.rst index 7958adfae..f324e3f3b 100644 --- a/doc/services/queues/queues.rst +++ b/doc/services/queues/queues.rst @@ -64,6 +64,8 @@ digits, underscores, and hyphens. $queue = $service->createQueue('new_queue'); +`Get the executable PHP script for this example `_ + Find queue details ------------------ @@ -122,3 +124,12 @@ in the queue, categorized by status. .. code-block:: php $queue->getStats(); + +Delete queue +------------ + +.. code-block:: php + + $queue->delete(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/volume/snapshots.rst b/doc/services/volume/snapshots.rst index c2d8ef6cc..555824a9d 100644 --- a/doc/services/volume/snapshots.rst +++ b/doc/services/volume/snapshots.rst @@ -19,6 +19,8 @@ to create one: 'volume_id' => $volume->id )); +`Get the executable PHP script for this example `_ + List snapshots -------------- @@ -31,6 +33,8 @@ List snapshots /** @param $snapshot OpenCloud\Volume\Resource\Snapshot */ } +`Get the executable PHP script for this example `_ + To get details on a single snapshot ----------------------------------- @@ -39,6 +43,8 @@ To get details on a single snapshot $snapshot = $dallas->snapshot('{snapshotId}'); +`Get the executable PHP script for this example `_ + To delete a snapshot -------------------- @@ -46,3 +52,5 @@ To delete a snapshot .. code-block:: php $snapshot->delete(); + +`Get the executable PHP script for this example `_ diff --git a/doc/services/volume/volumes.rst b/doc/services/volume/volumes.rst index 6a35bb135..a84ed0421 100644 --- a/doc/services/volume/volumes.rst +++ b/doc/services/volume/volumes.rst @@ -19,6 +19,9 @@ parameters are optional: 'display_description' => 'Used for large object storage' )); +`Get the executable PHP script for this example `_ + + List volumes ------------ @@ -30,6 +33,8 @@ List volumes /** @param $volumeType OpenCloud\Volume\Resource\Volume */ } +`Get the executable PHP script for this example `_ + Get details on a single volume ------------------------------ @@ -42,6 +47,8 @@ information on the specified volume: $volume = $dallas->volume(''); echo $volume->size; +`Get the executable PHP script for this example `_ + To delete a volume ------------------ @@ -50,6 +57,8 @@ To delete a volume $volume->delete(); +`Get the executable PHP script for this example `_ + Attach a volume to a server --------------------------- From 02eb989508a33b7fa060bb116ba1ca295b22beac Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 10 Mar 2015 11:45:55 +0100 Subject: [PATCH 160/181] Add list CDN containers sample file --- samples/ObjectStore/list-cdn-containers.php | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 samples/ObjectStore/list-cdn-containers.php diff --git a/samples/ObjectStore/list-cdn-containers.php b/samples/ObjectStore/list-cdn-containers.php new file mode 100644 index 000000000..a71a8bed9 --- /dev/null +++ b/samples/ObjectStore/list-cdn-containers.php @@ -0,0 +1,40 @@ + '{username}', + 'apiKey' => '{apiKey}', +)); + +// 2. Obtain an Object Store service object from the client. +$objectStoreService = $client->objectStoreService(null, '{region}'); + +// 3. Object a CDN service object +$cdnService = $objectStoreService->getCdnService(); + +// 4. Get container list. +$containers = $cdnService->listContainers(); + +foreach ($containers as $container) { + /** @var $container OpenCloud\ObjectStore\Resource\CDNContainer **/ +} From 4839afc144e66ba298213373d9c6a169a2ca420f Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 11 Mar 2015 10:09:13 -0700 Subject: [PATCH 161/181] Adding smoke test to apply security group to port. --- tests/OpenCloud/Smoke/Unit/Networking.php | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/OpenCloud/Smoke/Unit/Networking.php b/tests/OpenCloud/Smoke/Unit/Networking.php index 8ccd30a94..02ed838bb 100644 --- a/tests/OpenCloud/Smoke/Unit/Networking.php +++ b/tests/OpenCloud/Smoke/Unit/Networking.php @@ -272,6 +272,30 @@ protected function testSecurityGroupOperations() $securityGroup = $this->getService()->getSecurityGroup($securityGroup->getId()); $this->stepInfo('Security Group ID: ' . $securityGroup->getId()); $this->stepInfo('Security Group Name: ' . $securityGroup->getName()); + + $network1 = $this->getService()->createNetwork(array( + 'name' => 'test_network_for_test_port_sg' + )); + $this->cleanupNetworkIds[] = $network1->getId(); + + $subnet1 = $this->getService()->createSubnet(array( + 'cidr' => '192.165.66.0/25', + 'networkId' => $network1->getId(), + 'ipVersion' => 4, + 'name' => 'test_subnet_for_test_port_sg' + )); + $this->cleanupSubnetIds[] = $subnet1->getId(); + + $port1 = $this->getService()->createPort(array( + 'networkId' => $network1->getId(), + 'name' => 'test_port_for_test_port_sg' + )); + $this->cleanupPortIds[] = $port1->getId(); + + $this->step('Apply security group to port'); + $port1->update(array( + 'securityGroups' => array($securityGroup->getId()) + )); } protected function testSecurityGroupRuleOperations() From 5c8e38e234568b4dca8479cff265435a9d5d506e Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Wed, 11 Mar 2015 10:21:52 -0700 Subject: [PATCH 162/181] Minor formatting fix so code block renders correctly. --- doc/getting-started-with-rackspace.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/getting-started-with-rackspace.rst b/doc/getting-started-with-rackspace.rst index 35317a3e6..73aa3a8d4 100644 --- a/doc/getting-started-with-rackspace.rst +++ b/doc/getting-started-with-rackspace.rst @@ -138,7 +138,7 @@ Okay, you're ready to spin up a server: .. code-block:: php -use Guzzle\Http\Exception\BadResponseException; + use Guzzle\Http\Exception\BadResponseException; $server = $compute->server(); From f017f31110f647490c846d1c1ac2b10c7345f8a2 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Tue, 10 Mar 2015 13:10:35 +0100 Subject: [PATCH 163/181] Add deprecation and redirect links to existing docs --- doc/services/compute/servers.rst | 36 + docs/getting-started-openstack.md | 200 +----- docs/getting-started.md | 182 +---- docs/userguide/Autoscale/Config.md | 46 +- docs/userguide/Autoscale/Groups.md | 95 +-- docs/userguide/Autoscale/Policies.md | 67 +- docs/userguide/Autoscale/Webhooks.md | 51 +- docs/userguide/Clients.md | 148 +---- docs/userguide/CloudMonitoring/Agents.md | 148 +---- docs/userguide/CloudMonitoring/Alarms.md | 55 +- docs/userguide/CloudMonitoring/Changelogs.md | 13 +- docs/userguide/CloudMonitoring/Checks.md | 140 +--- docs/userguide/CloudMonitoring/Entities.md | 54 +- docs/userguide/CloudMonitoring/Metrics.md | 78 +-- .../CloudMonitoring/Notifications.md | 202 +----- docs/userguide/CloudMonitoring/Service.md | 15 +- docs/userguide/CloudMonitoring/Views.md | 18 +- docs/userguide/CloudMonitoring/Zones.md | 45 +- docs/userguide/Compute/Images.md | 64 +- docs/userguide/Compute/Keypair.md | 90 +-- docs/userguide/Compute/Server.md | 179 +---- docs/userguide/Compute/Service.md | 17 +- docs/userguide/DNS/Domains.md | 229 +------ docs/userguide/DNS/Limits.md | 57 +- docs/userguide/DNS/Records.md | 86 +-- docs/userguide/DNS/Reverse-DNS.md | 70 +- docs/userguide/DNS/Service.md | 10 +- docs/userguide/Database/README.md | 115 +--- docs/userguide/Debugging.md | 88 +-- docs/userguide/Identity/Roles.md | 67 +- docs/userguide/Identity/Service.md | 23 +- docs/userguide/Identity/Tenants.md | 20 +- docs/userguide/Identity/Tokens.md | 83 +-- docs/userguide/Identity/Users.md | 127 +--- docs/userguide/Image/Images.md | 96 +-- docs/userguide/Image/Schemas.md | 158 +---- docs/userguide/Image/Sharing.md | 109 +-- docs/userguide/Image/Tags.md | 22 +- docs/userguide/Iterators.md | 117 +--- docs/userguide/LoadBalancer/README.md | 79 +-- docs/userguide/LoadBalancer/USERGUIDE.md | 625 +----------------- docs/userguide/Networking/README.md | 75 +-- docs/userguide/Networking/USERGUIDE.md | 616 +---------------- docs/userguide/ObjectStore/Access.md | 65 +- docs/userguide/ObjectStore/Account.md | 27 +- docs/userguide/ObjectStore/CDN/Container.md | 77 +-- docs/userguide/ObjectStore/CDN/Object.md | 19 +- docs/userguide/ObjectStore/README.md | 64 +- .../ObjectStore/Storage/Container.md | 181 +---- .../ObjectStore/Storage/Migrating.md | 82 +-- docs/userguide/ObjectStore/Storage/Object.md | 274 +------- docs/userguide/ObjectStore/USERGUIDE.md | 624 +---------------- docs/userguide/Orchestration/README.md | 80 +-- docs/userguide/Orchestration/USERGUIDE.md | 505 +------------- docs/userguide/Queues/Claim.md | 122 +--- docs/userguide/Queues/Message.md | 206 +----- docs/userguide/Queues/Queue.md | 155 +---- docs/userguide/README.md | 73 +- docs/userguide/Services.md | 46 +- docs/userguide/accessip.md | 49 +- docs/userguide/caching-credentials.md | 38 +- docs/userguide/dbaas.md | 317 +-------- docs/userguide/flavors.md | 58 +- docs/userguide/networks.md | 101 +-- docs/userguide/servers.md | 186 +----- docs/userguide/volumes.md | 171 +---- 66 files changed, 166 insertions(+), 8169 deletions(-) diff --git a/doc/services/compute/servers.rst b/doc/services/compute/servers.rst index 8a55ce57f..0709bda9a 100644 --- a/doc/services/compute/servers.rst +++ b/doc/services/compute/servers.rst @@ -204,6 +204,42 @@ Updatable attributes | accessIPv6 | The IP version 6 address. | +--------------+--------------------------------------------------------------------------------------------------------------------------------------------------+ + +Updating the access IP address(es) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For example, you may have a private cloud with internal addresses in the +10.1.x range. However, you can access a server via a firewall device at +address 50.57.94.244. In this case, you can change the ``accessIPv4`` +attribute to point to the firewall: + +.. code-block:: php + + $server->update(array('accessIPv4' => '50.57.94.244')); + +When a client application retrieves the server’s information, it will +know that it needs to use the ``accessIPv4`` address to connect to the +server, and *not* the IP address assigned to one of the network +interfaces. + + +Retrieving the server’s IP address +---------------------------------- + +The ``Server::ip()`` method is used to retrieve the server’s IP address. +It has one optional parameter: the format (either IPv4 or IPv6) of the +address to return (by default, it returns the IPv4 address): + +.. code-block:: php + + // IPv4 + echo $server->ip(); + echo $server->ip(4); + + // IPv6 + echo $server->ip(6); + + Delete server ------------- diff --git a/docs/getting-started-openstack.md b/docs/getting-started-openstack.md index 6bb1ae260..24eda2779 100644 --- a/docs/getting-started-openstack.md +++ b/docs/getting-started-openstack.md @@ -1,201 +1,5 @@ # Installing the SDK -You must install through Composer, because this library has a few dependencies: +Our docs have moved! Please visit the below link: -```bash -# Install Composer -curl -sS https://getcomposer.org/installer | php - -# Require php-opencloud as a dependency -php composer.phar require rackspace/php-opencloud:dev-master -``` - -Once you have installed the library, you will need to load Composer's autoloader (which registers all the required -namespaces): - -```php -require 'vendor/autoload.php'; -``` - -And you're good to go! - -# Quick deep-dive: building some Nova instances - -In this example, you will write code that will create a Nova instance running Ubuntu. - -### 1. Setup the client and pass in your credentials - -To authenticate against Keystone: - -```php -use OpenCloud\OpenStack; - -$client = new OpenStack('http://my-openstack.com:35357/v2.0/', array( - 'username' => 'foo', - 'password' => 'bar', - 'tenantName' => 'baz' -)); -``` - -You will need to substitute in the public URL endpoint for your Keystone service, as well as your `username`, `password` -and `tenantName`. You can also specify your `tenantId` instead of `tenantName` if you prefer. - -### 2. Pick what service you want to use - -In this case, we want to use the Nova service: - -```php -$compute = $client->computeService('nova', 'regionOne'); -``` - -The first argument is the __name__ of the service as it appears in the OpenStack service catalog. For OpenStack users, this must be retrieved and entered in your code. If you are unsure how to retrieve the service name, follow these steps: - -1. Setup the `$client` object, as above -2. Copy and run this code: - - ```php - $client->authenticate(); - - print_r($client->getCatalog()->getItems()); - ``` - -3. This will output all the items in your service catalog. Go through the outputted list and find your service, making note of the "name" field. This is the name you will need to enter as the first argument. You will also be able to see the available regions. - -The second argument is the region. The third and last argument is the type of URL; you may use either `publicURL` or `internalURL`. - -### 3. Select your server image - -Instances are based on "images", which are effectively just the type of operating system you want. Let's go through the -list and find an Ubuntu one: - -```php -$images = $compute->imageList(); -foreach ($images as $image) { - if (strpos($image->name, 'Ubuntu') !== false) { - $ubuntu = $image; - break; - } -} -``` - -Alternatively, if you already know the image ID, you can do this much easier: - -```php -$ubuntu = $compute->image('868a0966-0553-42fe-b8b3-5cadc0e0b3c5'); -``` - -## 4. Select your flavor - -There are different server specs - some which offer 1GB RAM, others which offer a much higher spec. The 'flavor' of an -instance is its hardware configuration. So if you want a 2GB instance but don't know the ID, you have to traverse the list: - -```php -$flavors = $compute->flavorList(); -foreach ($flavors as $flavor) { - if (strpos($flavor->name, '2GB') !== false) { - $twoGbFlavor = $flavor; - break; - } -} -``` - -Again, it's much easier if you know the ID: - -```php -$twoGbFlavor = $compute->flavor('4'); -``` - -## 5. Thunderbirds are go! - -Okay, you're ready to spin up a server: - -```php -$server = $compute->server(); - -try { - $response = $server->create(array( - 'name' => 'My lovely server', - 'image' => $ubuntu, - 'flavor' => $twoGbFlavor - )); -} catch (\Guzzle\Http\Exception\BadResponseException $e) { - - // No! Something failed. Let's find out: - - $responseBody = (string) $e->getResponse()->getBody(); - $statusCode = $e->getResponse()->getStatusCode(); - $headers = $e->getResponse()->getHeaderLines(); - - echo sprintf("Status: %s\nBody: %s\nHeaders: %s", $statusCode, $responseBody, implode(', ', $headers)); -} -``` - -As you can see, you're creating a server called "My lovely server" - this will take a few minutes for the build to -complete. You can always check the progress by logging into your Controller node and running: - -`nova list` - -You can also execute a polling function immediately after the `create` method that checks the build process: - -```php -use OpenCloud\Compute\Constants\ServerState; - -$callback = function($server) { - if (!empty($server->error)) { - var_dump($server->error); - exit; - } else { - echo sprintf( - "Waiting on %s/%-12s %4s%%", - $server->name(), - $server->status(), - isset($server->progress) ? $server->progress : 0 - ); - } -}; - -$server->waitFor(ServerState::ACTIVE, 600, $callback); -``` -So, the server will be polled until it is in an `ACTIVE` state, with a timeout of 600 seconds. When the poll happens, the -callback function is executed - which in this case just logs some output. - -# More fun with Nova - -Once you've booted up your instance, you can use other API operations to monitor your Compute nodes. To list every -node on record, you can execute: - -```php -$servers = $compute->serverList(); - -foreach ($servers as $server) { - // do something with each server... - echo $server->name, PHP_EOL; -} -``` - -or, if you know a particular instance ID you can retrieve its details: - -```php -$server = $compute->server('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'); -``` - -allowing you to update its properties: - -```php -$server->update(array( - 'name' => 'New server name' -)); -``` - -or delete it entirely: - -```php -$server->delete(); -``` - -# Next steps - -Consult our [documentation](https://github.com/rackspace/php-opencloud/tree/master/docs/userguide) about other services -you can use, like [Keystone](https://github.com/rackspace/php-opencloud/tree/master/docs/userguide/Identity) or -[Swift](https://github.com/rackspace/php-opencloud/tree/master/docs/userguide/ObjectStore). If you have any questions or -troubles, feel free to contact us at https://developer.rackspace.com/support/ or open a Github issue with details. +https://doc.php-opencloud.com/en/latest/getting-started-with-openstack.html diff --git a/docs/getting-started.md b/docs/getting-started.md index e661e0ce8..af65271fe 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,183 +1,5 @@ # Installing the SDK -You must install through Composer, because this library has a few dependencies: +Our docs have moved! Please visit the below link: -```bash -# Install Composer -curl -sS https://getcomposer.org/installer | php - -# Require php-opencloud as a dependency -php composer.phar require rackspace/php-opencloud:dev-master -``` - -Once you have installed the library, you will need to load Composer's autoloader (which registers all the required -namespaces): - -```php -require 'vendor/autoload.php'; -``` - -And you're good to go! - -# Quick deep-dive: building some cloud servers - -In this example, you will write code that will create a Cloud Server running Ubuntu. - -### 1. Setup the client and pass in your credentials - -To authenticate against the Rackspace API and use its services: - -```php - 'foo', - 'apiKey' => 'bar' -)); -``` - -Alternatively, if you would like to validate against your own API, or just want to access OpenStack services: - -```php -use OpenCloud\OpenStack; - -$client = new OpenStack('http://identity.my-openstack.com/v2.0/', array( - 'username' => 'foo', - 'password' => 'bar' -)); -``` - -You can see in the first example that the constant `Rackspace::US_IDENTITY_ENDPOINT` is just a string representation of -Rackspace's identity endpoint (`https://identity.api.rackspacecloud.com/v2.0/`). Another difference is that Rackspace -uses API key for authentication, whereas OpenStack uses a generic password. - -#### 1.2 Logger injection -As the `Rackspace` client extends the `OpenStack` client, they both support passing `$options` as an array via the constructor's third parameter. The options are passed as a config to the `Guzzle` client, but also allow to inject your own `Logger`. - -Prerequisities and usage example can be found in [the Clients userguide](/docs/userguide/Clients.md#12-logger-injection) - -### 2. Pick what service you want to use - -In this case, we want to use the Compute (Nova) service: - -```php -$compute = $client->computeService('cloudServersOpenStack', 'ORD'); -``` - -The first argument is the __name__ of the service as it appears in the OpenStack service catalog. If in doubt, you can -leave blank and it will revert to the default name for the service. The second argument is the region; you may use: - -- __DFW__ (Dallas) -- __ORD__ (Chicago) -- __IAD__ (Virginia) -- __LON__ (London) -- __HKG__ (Hong Kong) -- __SYD__ (Sydney) - -The third and last argument is the type of URL; you may use either `publicURL` or `internalURL`. If you select `internalUrl` -all API traffic will use ServiceNet (internal IPs) and will receive a performance boost. - -### 3. Select your server image - -Servers are based on "images", which are effectively just the type of operating system you want. Let's go through the list -and find an Ubuntu one: - -```php -$images = $compute->imageList(); -while ($image = $images->next()) { - if (strpos($image->name, 'Ubuntu') !== false) { - $ubuntu = $image; - break; - } -} -``` - -Alternatively, if you already know the image ID, you can do this much easier: - -```php -$ubuntu = $compute->image('868a0966-0553-42fe-b8b3-5cadc0e0b3c5'); -``` - -## 4. Select your flavor - -There are different server specs - some which offer 1GB RAM, others which offer a much higher spec. The 'flavor' of a -server is its hardware configuration. So if you want a 2GB instance but don't know the ID, you have to traverse the list: - -```php -$flavors = $compute->flavorList(); -while ($flavor = $flavors->next()) { - if (strpos($flavor->name, '2GB') !== false) { - $twoGbFlavor = $flavor; - break; - } -} -``` - -Again, it's much easier if you know the ID: - -```php -$twoGbFlavor = $compute->flavor('4'); -``` - -## 5. Thunderbirds are go! - -Okay, you're ready to spin up a server: - -```php -use OpenCloud\Compute\Constants\Network; - -$server = $compute->server(); - -try { - $response = $server->create(array( - 'name' => 'My lovely server', - 'image' => $ubuntu, - 'flavor' => $twoGbFlavor, - 'networks' => array( - $compute->network(Network::RAX_PUBLIC), - $compute->network(Network::RAX_PRIVATE) - ) - )); -} catch (\Guzzle\Http\Exception\BadResponseException $e) { - - // No! Something failed. Let's find out: - - $responseBody = (string) $e->getResponse()->getBody(); - $statusCode = $e->getResponse()->getStatusCode(); - $headers = $e->getResponse()->getHeaderLines(); - - echo sprintf("Status: %s\nBody: %s\nHeaders: %s", $statusCode, $responseBody, implode(', ', $headers)); -} -``` - -As you can see, you're creating a server called "My lovely server", and you've inserted it in two networks: the Rackspace -private network (ServiceNet), and the Rackspace public network (for Internet connectivity). This will take a few -minutes for the build to complete. - -You can also call a polling function that checks on the build process: - -```php -use OpenCloud\Compute\Constants\ServerState; - -$callback = function($server) { - if (!empty($server->error)) { - var_dump($server->error); - exit; - } else { - echo sprintf( - "Waiting on %s/%-12s %4s%%", - $server->name(), - $server->status(), - isset($server->progress) ? $server->progress : 0 - ); - } -}; - -$server->waitFor(ServerState::ACTIVE, 600, $callback); -``` -So, the server will be polled until it is in an `ACTIVE` state, with a timeout of 600 seconds. When the poll happens, the -callback function is executed - which in this case just logs some output. +https://doc.php-opencloud.com/en/latest/getting-started-with-rackspace.html diff --git a/docs/userguide/Autoscale/Config.md b/docs/userguide/Autoscale/Config.md index a619bf277..02f2e891d 100644 --- a/docs/userguide/Autoscale/Config.md +++ b/docs/userguide/Autoscale/Config.md @@ -1,47 +1,5 @@ # Group configurations -##Intro +Our docs have moved! Please visit the below link: -There are two types of configuration associated with an Auto Scale group: - -- **Group configuration**. Outlines the basic elements of the Auto Scale configuration. The group configuration manages how many servers can participate in the scaling group. It sets a minimum and maximum limit for the number of entities that can be used in the scaling process. It also specifies information related to load balancers. - -- **Launch configuration**. Creates a blueprint for how new servers will be created. The launch configuration specifies what type of server image will be started on launch, what flavor the new server is, and which load balancer the new server connects to. - -## Setup - -To interact with the configuration of a scaling group, you will need to setup the group object beforehand: - -```php -$groupId = 'e41380ae-173c-4b40-848a-25c16d7fa83d'; -$group = $service->getGroup($groupId); -``` - -For more information about setting up the `$service` object, please see the userguide tutorial for [groups](). - -## Get group/launch configuration - -```php -$groupConfig = $group->getGroupConfig(); -$launchConfig = $group->getLaunchConfig(); -``` - -## Edit group/launch configuration - -```php -$groupConfig->update(array( - 'name' => 'New name!' -)); - -$launchConfig = $group->getLaunchConfig(); - -$server = $launchConfig->args->server; -$server->name = "BRAND NEW SERVER NAME"; - -$launchConfig->update(array - 'args' => array( - 'server' => $server, - 'loadBalancers' => $launchConfig->args->loadBalancers - ) -)); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/autoscale/group-config.html diff --git a/docs/userguide/Autoscale/Groups.md b/docs/userguide/Autoscale/Groups.md index 98dfb43dc..7ec7aa269 100644 --- a/docs/userguide/Autoscale/Groups.md +++ b/docs/userguide/Autoscale/Groups.md @@ -1,96 +1,5 @@ #Auto Scale groups -## Intro +Our docs have moved! Please visit the below link: -The scaling group is at the heart of an Auto Scale deployment. The scaling group specifies the basic elements of the Auto Scale configuration. It manages how many servers can participate in the scaling group. It also specifies information related to load balancers if your configuration uses a load balancer. - -## Service setup - -Nothing special here; you setup your client and service objects in the same way as every other resource: - -```php -$service = $client->autoscaleService(); -``` - -Please consult the [client doc](docs/userguide/Client.md) for more information about creating clients. - -## List all groups - -```php -$groups = $service->groupList(); -``` - -Please consult the [iterator documentation](docs/userguide/Iterators.md) for more information about iterators. - -## Retrieve one group by ID - -```php -$group = $service->group('605e13f6-1452-4588-b5da-ac6bb468c5bf'); -``` - -## Create a new group - -You can create a new scaling group in two ways: either pass in a JSON string (easier option); or instantiate a new object and manually set its properties (a lot more verbose) - -```php - -// Easy way: - -$jsonString = <<create($jsonString); - -// More granular (and verbose) way: - -$object = new \stdClass; - -// Set the config object for this autoscale group; contains all of properties -// which determine its behaviour -$object->groupConfiguration = new \stdClass; -$object->groupConfiguration->name = 'New autoscale group'; -$object->groupConfiguration->minEntities = 5; -$object->groupConfiguration->maxEntities = 25; -$object->groupConfiguration->cooldown = 60; - -// We need specify what is going to be launched. For now, we'll launch a new server -$object->launchConfiguration = new \stdClass; -$object->launchConfiguration->type = 'launch_server'; - -// To launch a new server, we need two `args` properties: `server` and `loadBalancer` -$server = new \stdClass; -$server->flavorRef = 3; -$server->name = 'webhead'; -$server->imageRef = "0d589460-f177-4b0f-81c1-8ab8903ac7d8"; - -$loadBalancer = new \stdClass; -$loadBalancer->loadBalancerId = 2200; -$loadBalancer->port = 8081; - -$object->launchConfiguration->args = new \stdClass; -$object->launchConfiguration->args->server = $server; -$object->launchConfiguration->args->loadBalancers = array($loadBalancer); - -// Do we want particular scaling policies? -$policy = new \stdClass; -$policy->name = "scale up by 10"; -$policy->change = 10; -$policy->cooldown = 5; -$policy->type = "webhook"; - -$object->scalingPolicies = array($policy); - -$group->create($object); -``` - -## Delete an autoscale group -```php -$group->delete(); -``` - -## Get the current state of the scaling group - -```php -$group->getState(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/autoscale/groups.html diff --git a/docs/userguide/Autoscale/Policies.md b/docs/userguide/Autoscale/Policies.md index 6f3d1b282..7a312af50 100644 --- a/docs/userguide/Autoscale/Policies.md +++ b/docs/userguide/Autoscale/Policies.md @@ -1,68 +1,5 @@ #Policies -## Setup +Our docs have moved! Please visit the below link: -To interact with the policies of a scaling group, you will need to setup the group object beforehand. - -```php -$groupId = 'foobar'; -$group = $service->getGroup($groupId); -``` - -For more information about setting up the `$service` object, please see the userguide tutorial for [Autoscale groups](). - -## Get all policies - -```php -$policies = $group->getPolicies(); - -while ($policy = $policies->next()) { - // do something - echo "{$policy->name} {($policy->type)}" . PHP_EOL; -} -``` - -## Create a new scaling policy - -Creating policies is achieved through passing an array to the `create` method. - -```php -$policy = new \stdClass; -$policy->name = "NEW NAME"; -$policy->change = 1; -$policy->cooldown = 150; -$policy->type = "webhook"; - -$group->getPolicy()->create(array($policy)); - -// or even: - -$group->getPolicy()->create(array( - (object) array( - 'name' => 'NEW NAME', - 'change' => 1, - 'cooldown' => 150, - 'type' => 'webhook' - ), - // etc. -)); -``` - -## Get, update and delete a scaling policy - -```php -$policyId = 'foobar'; -$policy = $group->getPolicy($policyId); - -$policy->update(array( - 'name' => 'More relevant name' -)); - -$policy->delete(); -``` - -## Execute a scaling policy - -```php -$policy->execute(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/autoscale/policies.html diff --git a/docs/userguide/Autoscale/Webhooks.md b/docs/userguide/Autoscale/Webhooks.md index e634cc073..c5e6453ed 100644 --- a/docs/userguide/Autoscale/Webhooks.md +++ b/docs/userguide/Autoscale/Webhooks.md @@ -1,52 +1,5 @@ # Webhooks -## Setup +Our docs have moved! Please visit the below link: -To interact with the webhooks of a group's scaling policy, you will need to setup the group and policy objects beforehand. - -```php -$groupId = 'foo'; -$policyId = 'bar'; - -$group = $service->getGroup($groupId); -$policy = $group->getPolicy($policyId); -``` - -For more information about setting up the `$service` object, please see the userguide tutorial for [Autoscale groups](). - -## Get all webhooks - -```php -$webhooks = $policy->getWebookList(); -``` - -## Create a new webhook - -```php -$policy->getWebhook()->create(array( - (object) array( - 'name' => 'Alice', - 'metadata' => array( - 'firstKey' => 'foo', - 'secondKey' => 'bar' - ) - ) -)); -``` - -## Get, update and delete an individual webhook - -```php -$webhookId = 'baz'; -$webhook = $policy->getWebhook($webhookId); - -// Update the metadata -$metadata = $webhook->metadata; -$metadata->thirdKey = 'blah'; -$webhook->update(array( - 'metadata' => $metadata -)); - -// Delete it -$webhook->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/autoscale/webhooks.html diff --git a/docs/userguide/Clients.md b/docs/userguide/Clients.md index c7270d69e..184b601f4 100644 --- a/docs/userguide/Clients.md +++ b/docs/userguide/Clients.md @@ -1,149 +1,5 @@ # Clients -## Overview +Our docs have moved! Please visit the below link: -A Client is the object responsible for issuing HTTP requests and receiving responses from the API. In short, it forms the core of the SDK because it controls how functionality is executed. All services depend on the client to work. - -Users have access to two types of client: `OpenCloud\OpenStack` and `OpenCloud\Rackspace`. The latter extends the former, meaning that much of the functionality is shared between them. The OpenStack client extends functionality from other base classes, that trace all the way back to Guzzle's root class: - -1. `Guzzle\Http\Client` -2. `OpenCloud\Common\Http\Client` -3. `OpenCloud\OpenStack` -4. `OpenCloud\Rackspace` - -## 1. Initializing a client - -### Rackspace - -First, you need to select the Identity endpoint you want to authenticate against. If you're using Rackspace, you can either use the UK or US endpoints. There are class constants defined for your convenience: - -- `OpenCloud\Rackspace::US_IDENTITY_ENDPOINT` (https://identity.api.rackspacecloud.com/v2.0) -- `OpenCloud\Rackspace::UK_IDENTITY_ENDPOINT` (https://lon.identity.api.rackspacecloud.com/v2.0) - -Then you need to find your username and apiKey. Your username will be visible at the top right of the Rackspace Control panel; and your API key can be retrieved by going to Account Settings. Once this is done: - -```php -use OpenCloud\OpenStack; - -$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => 'foo', - 'apiKey' => 'bar' -)); -``` - -### OpenStack - -To initialize an OpenStack client, the process is the same: - -```php -use OpenCloud\OpenStack; - -$client = new OpenStack('http://identity.my-openstack.com/v2.0', array( - 'username' => 'foo', - 'password' => 'bar' -)); -``` - -#### 1.2 Logger injection -As the `Rackspace` client extends the `OpenStack` client, they both support passing `$options` as an array via the constructor's third parameter. The options are passed as a config to the `Guzzle` client, but also allow to inject your own `Logger`. - -Your logger should implement the `Psr\Log\LoggerInterface` [as defined in PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md). Example of a compatible logger is [`Monolog`](https://github.com/Seldaek/monolog). When the client does create a service, it will inject the logger if one is available. - -To inject a `LoggerInterface` compatible logger into a new `Client`: - -```php -use Monolog\Logger; -use OpenCloud\OpenStack; - -// create a log channel -$log = new Logger('name'); - -$client = new OpenStack('http://identity.my-openstack.com/v2.0', array( - 'username' => 'foo', - 'password' => 'bar' -), array( - 'logger' => $log, -)); -``` - -## 2. Authentication - -The Client does not automatically authenticate against the API on object creation - it waits for an API call. When this happens, it checks whether the current "token" has expired, and (re-)authenticates if necessary. - -You can force authentication, by calling: - -```php -$client->authenticate(); -``` - -If the credentials are incorrect, a `401` error will be returned. If credentials are correct, a `200` status is returned with your Service Catalog. - -## 3. Service Catalog - -The Service Catalog is returned on successful authentication, and is composed of all the different API services available to the current tenant. All of this functionality is encapsulated in the `Catalog` object, which allows you greater control and interactivity. - -```php -/** @var OpenCloud\Common\Service\Catalog */ -$catalog = $client->getCatalog(); - -// Return a list of OpenCloud\Common\Service\CatalogItem objects -foreach ($catalog->getItems() as $catalogItem) { - - $name = $catalogItem->getName(); - $type = $catalogItem->getType(); - - if ($name == 'cloudServersOpenStack' && $type == 'compute') { - break; - } - - // Array of OpenCloud\Common\Service\Endpoint objects - $endpoints = $catalogItem->getEndpoints(); - foreach ($endpoints as $endpoint) { - if ($endpoint->getRegion() == 'DFW') { - echo $endpoint->getPublicUrl(); - } - } -} -``` - -As you can see, you have access to each Service's name, type and list of endpoints. Each endpoint provides access to the specific region, along with its public and private endpoint URLs. - -## 4. Default HTTP headers - -To set default HTTP headers: - -```php -$client->setDefaultOption('headers/X-Custom-Header', 'FooBar'); -``` - -## User agents - -php-opencloud will send a default `User-Agent` header for every HTTP request, unless a custom value is provided by the end-user. The default header will be in this format: - -> User-Agent: OpenCloud/xxx cURL/yyy PHP/zzz - -where `xxx` is the current version of the SDK, `yyy` is the current version of cURL, and `zzz` is the current PHP version. To override this default, you must run: - -```php -$client->setUserAgent('MyCustomUserAgent'); -``` - -which will result in: - -> User-Agent: MyCustomUserAgent - -If you want to set a _prefix_ for the user agent, but retain the default `User-Agent` as a suffix, you must run: - -```php -$client->setUserAgent('MyPrefix', true); -``` - -which will result in: - -> User-Agent: MyPrefix OpenCloud/xxx cURL/yyy PHP/zzz - -where `$client` is an instance of `OpenCloud\OpenStack` or `OpenCloud\Rackspace`. - -## 5. Other functionality - -For a full list of functionality provided by Guzzle, please consult the [official documentation](http://docs.guzzlephp.org/en/latest/http-client/client.html). +https://doc.php-opencloud.com/en/latest/index.html diff --git a/docs/userguide/CloudMonitoring/Agents.md b/docs/userguide/CloudMonitoring/Agents.md index 7e67e7d0b..b316d004c 100644 --- a/docs/userguide/CloudMonitoring/Agents.md +++ b/docs/userguide/CloudMonitoring/Agents.md @@ -1,149 +1,5 @@ # Agents -## Intro +Our docs have moved! Please visit the below link: -The Monitoring Agent resides on the host server being monitored. The agent allows you to gather on-host metrics based on agent checks and push them to Cloud Monitoring where you can analyze them, use them with the Cloud Monitoring infrastructure (such as alarms), and archive them. - -For more information about this feature, including a brief overview of its core design principles and security layers, see the [official API documentation](http://docs.rackspace.com/cm/api/v1.0/cm-devguide/content/service-agent.html). - -## Setup - -```php -$agentId = '00-agent.example.com'; -$agent = $service->getAgent($agentId); -``` - -You can view the [service page](Service.md) for more information about setting up the Cloud Monitoring service. - -## List agents - -```php -$agents = $service->getAgents(); - -foreach ($agents as $agent) { - echo $agent->getLastConnected(); -} -``` - -Please consult the [iterator doc](docs/userguide/Iterators.md) for more information about iterators. - -## List connections - -```php -$connections = $agent->getConnections(); -``` - -Please consult the [iterator doc](docs/userguide/Iterators.md) for more information about iterators. - -## Get connection -```php -/** @var \OpenCloud\CloudMonitoring\Resource\AgentConnection */ -$connection = $agent->getConnection('cntl4qsIbA'); -``` - -### Agent Connection properties - -Name|Description|Type|Method -----|-----------|----|------ -id|-|-|`getId()` -guid|-|-|`getGuid()` -agent_id|-|-|`getAgentId()` -endpoint|-|-|`getEndpoint()` -process_version|-|-|`getProcessVersion()` -bundle_version|-|-|`getBundleVersion()` -agent_ip|-|-|`getAgentIp()` - - -# Agent tokens - -## Intro - -Agent tokens are used to authenticate Monitoring agents to the Monitoring Service. Multiple agents can share a single token. - -## Setup -```php -$tokenId = '4c5e28f0-0b3f-11e1-860d-c55c4705a286:1234'; -$agentToken = $service->getAgentToken($tokenId); -``` - -## Create agent token -```php -$newToken = $service->getAgentToken(); -$newToken->create(array('label' => 'Foobar')); -``` - -## List agent tokens -```php -$agentTokens = $service->getAgentTokens(); - -foreach ($agentTokens as $token) { - echo $token->getLabel(); -} -``` - -Please consult the [iterator doc](docs/userguide/Iterators.md) for more information about iterators. - -## Update and delete Agent Token -```php -// Update -$token->update(array( - 'label' => 'New label' -)); - -// Delete -$token->delete(); -``` - -# Agent Host Information - -## Info - -An agent can gather host information, such as process lists, network configuration, and memory usage, on demand. You can use the host-information API requests to gather this information for use in dashboards or other utilities. - -## Setup -```php -$host = $monitoringService->getAgentHost(); -``` - -## Get some metrics -```php -$cpuInfo = $host->info('cpus'); -$diskInfo = $host->info('disks'); -$filesystemInfo = $host->info('filesystems'); -$memoryInfo = $host->info('memory'); -$networkIntInfo = $host->info('network_interfaces'); -$processesInfo = $host->info('processes'); -$systemInfo = $host->info('system'); -$userInfo = $host->info('who'); - -// What CPU models do we have? -foreach ($cpuInfo as $cpuMetric) { - echo $cpuMetric->model, PHP_EOL; -} - -// How many disks do we have? -echo $diskInfo->count(); - -// What's the available space on our ext4 filesystem? -foreach ($filesystemInfo as $filesystemMetric) { - if ($filesystemMetric->sys_type_name == 'ext4') { - echo $filesystemMetric->avail; - } -} -``` - -# Agent targets - -## Info - -Each agent check type gathers data for a related set of target devices on the server where the agent is installed. For example, `agent.network` gathers data for network devices. The actual list of target devices is specific to the configuration of the host server. By focusing on specific targets, you can efficiently narrow the metric data that the agent gathers. - -### List agent targets -```php -$targets = $service->getAgentTargets(); - -foreach ($targets as $target) { - echo $target->getType(); -} - -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/agents.html diff --git a/docs/userguide/CloudMonitoring/Alarms.md b/docs/userguide/CloudMonitoring/Alarms.md index bf4a75652..b08caf4cd 100644 --- a/docs/userguide/CloudMonitoring/Alarms.md +++ b/docs/userguide/CloudMonitoring/Alarms.md @@ -1,56 +1,5 @@ # Alarms -## Info +Our docs have moved! Please visit the below link: -Alarms bind alerting rules, entities, and notification plans into a logical unit. Alarms are responsible for determining a state (```OK```, ```WARNING``` or ```CRITICAL```) based on the result of a Check, and executing a notification plan whenever that state changes. You create alerting rules by using the alarm DSL. For information about using the alarm language, refer to the [reference documentation](http://docs.rackspace.com/cm/api/v1.0/cm-devguide/content/alerts-language.html). - -## Setup - -Alarms are sub-resources of Entities: - -```php -$alarmId = 'alAAAA'; -$alarm = $check->getAlarm(); -``` - -For more information about working with Checks, please see the [appropriate documentation](Checks.md). - -## Attributes - -Name|Description|Required?|Method ----|---|---|--- -check_id|The ID of the check to alert on.|Required|`getCheckId()` -notification_plan_id|The ID of the notification plan to execute when the state changes.|Optional|`getNotificationPlanId()` -criteria|The alarm DSL for describing alerting conditions and their output states.|Optional|`getCriteria()` -disabled|Disable processing and alerts on this alarm|Optional|`isDisabled()` <`bool`> -label|A friendly label for an alarm.|Optional|`getLabel()` -metadata|Arbitrary key/value pairs.|Optional|`getMetadata()` - -## Create Alarm -```php -$alarm->create(array( - 'check_id' => 'chAAAA', - 'criteria' => 'if (metric["duration"] >= 2) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);', - 'notification_plan_id' => 'npAAAAA' -)); -``` - -## List Alarms -```php -$alarms = $entity->getAlarms(); - -foreach ($alarms as $alarm) { - echo $alarm->getId(); -} -``` - -## Update and delete Alarm -```php -// Update -$alarm->update(array( - 'criteria' => 'if (metric["duration"] >= 5) { return new AlarmStatus(OK); } return new AlarmStatus(CRITICAL);' -)); - -// Delete -$alarm->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/alarms.html diff --git a/docs/userguide/CloudMonitoring/Changelogs.md b/docs/userguide/CloudMonitoring/Changelogs.md index 0f8fe48d0..ff943e592 100644 --- a/docs/userguide/CloudMonitoring/Changelogs.md +++ b/docs/userguide/CloudMonitoring/Changelogs.md @@ -1,14 +1,5 @@ # Changelogs -## Info +Our docs have moved! Please visit the below link: -The monitoring service records changelogs for alarm statuses. Changelogs are accessible as a Time Series Collection. By default the API queries the last 7 days of changelog information. - -## Working with Changelogs -```php -$changelog = $service->getChangelog(); - -foreach ($changelog as $item) { - $entity = $item->getEntityId(); -} -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/changelogs.html diff --git a/docs/userguide/CloudMonitoring/Checks.md b/docs/userguide/CloudMonitoring/Checks.md index 265c0675d..5710aa465 100644 --- a/docs/userguide/CloudMonitoring/Checks.md +++ b/docs/userguide/CloudMonitoring/Checks.md @@ -1,141 +1,5 @@ # Checks -## Info +Our docs have moved! Please visit the below link: -A check is one of the foundational building blocks of the monitoring system. The check determines the parts or pieces of the entity that you want to monitor, the monitoring frequency, how many monitoring zones are originating the check, and so on. When you create a new check in the monitoring system, you specify the following information: - -- A name for the check -- The check's parent entity -- The type of check you're creating -- Details of the check -- The monitoring zones that will launch the check - -The check, as created, will not trigger alert messages until you create an alarm to generate notifications, to enable the creation of a single alarm that acts upon multiple checks (e.g. alert if any of ten different servers stops responding) or multiple alarms off of a single check. (e.g. ensure both that a HTTPS server is responding and that it has a valid certificate). - -## Setup - -Checks are sub-resources of Entities: -```php -$checkId = 'chAAAA'; -$check = $entity->getCheck($checkId); -``` - -## Attributes - -Name|Description|Required?|Data type ----|---|---|--- -type|The type of check.|Required|Valid check type. String (1..25 chars) -details|Details specific to the check type.|Optional|Array -disabled|Disables the check.|Optional|Boolean -label|A friendly label for a check.|Optional|String (1..255 chars) -metadata|Arbitrary key/value pairs.|Optional|Array -period|The period in seconds for a check. The value must be greater than the minimum period set on your account.|Optional|Integer (30..1800) -timeout|The timeout in seconds for a check. This has to be less than the period.|Optional|Integer (2..1800) - -###Attributes used for remote Checks - -Name|Description|Required?|Data type ----|---|---|--- -monitoring_zones_poll|List of monitoring zones to poll from. Note: This argument is only required for remote (non-agent) checks|Optional|Array -target_alias|A key in the entity's `ip_addresses` hash used to resolve this check to an IP address. This parameter is mutually exclusive with target_hostname.|Optional|String (1..64 chars) -target_hostname|The hostname this check should target. This parameter is mutually exclusive with `target_alias`.|Optional|Valid FQDN, IPv4 or IPv6 address. String (1..256 chars). -target_resolver|Determines how to resolve the check target.|Optional|`IPv4` or `IPv6` - -## Test parameters (before create) -```php -$params = array( - 'type' => 'remote.http', - 'details' => array( - 'url' => 'http://example.com', - 'method' => 'GET' - ), - 'monitoring_zones_poll' => array('mzlon'), - 'period' => '100', - 'timeout' => '30', - 'target_alias' => 'default', - 'label' => 'Website check 1' -); - -// You can do a test to see what would happen -// if a Check is launched with these params -$response = $entity->testNewCheckParams($params); - -echo $response->timestamp; // When was it executed? -echo $response->available; // Was it available? -echo $response->status; // Status code -``` -## Create a Check -```php -$entity->createCheck($params); -``` - -## Test existing Check -```php -// Set arg to TRUE for debug information -$response = $check->test(true); - -echo $response->debug_info; -``` - -## List Checks -```php -$checks = $entity->getChecks(); - -foreach ($checks as $check) { - echo $check->getId(); -} -``` - -### Update and delete Check -```php -// Update -$check->update(array('period' => 500)); - -// Delete -$check->delete(); -``` - -# Check types - -## Info - -Each check within the Rackspace Cloud Monitoring has a designated check type. The check type instructs the monitoring system how to check the monitored resource. **Note:** Users cannot create, update or delete check types. - -Check types for commonly encountered web protocols, such as HTTP (```remote.http```), IMAP (```remote.imap-banner```) , SMTP (```remote.stmp```), and DNS (```remote.dns```) are provided. Monitoring commonly encountered infrastructure servers like MySQL (```remote.mysql-banner```) and PostgreSQL (```remote.postgresql-banner```) are also available. Monitoring custom server uptime can be accomplished with the remote.tcp banner check to check for a protocol-defined banner at the beginning of a connection. Gathering metrics from server software to create alerts against can be accomplished using the remote.http check type and the 'extract' attribute to define the format. - -In addition to the standard Cloud Monitoring check types, you can also use agent check types if the Monitoring Agent is installed on the server you are monitoring. For a list of available check types, see the [official API documentation](http://docs.rackspace.com/cm/api/v1.0/cm-devguide/content/appendix-check-types.html). - -Checks generate metrics that alarms will alert based upon. The metrics generated often times depend on the check's parameters. For example, using the 'extract' attribute on the remote.http check, however the default metrics will always be present. To determine the exact metrics available, the Test Check API is provided. - -## Setup - -If you want to see the type for an existing Check: - -```php -/** @var \OpenCloud\CloudMonitoring\Resource\CheckType */ -$checkType = $check->getCheckType(); -``` - -Alternatively, you can retrieve a specific type based on its ID: - -```php -$checkTypeId = 'remote.dns'; -$checkType = $service->getCheckType($checkTypeId); -``` - -## Attributes - -Name|Description|Data type|Method ----|---|---|--- -type|The name of the supported check type.|String|`getType()` -fields|Check type fields.|Array|`getFields()` -supported_platforms|Platforms on which an agent check type is supported. This is advisory information only - the check may still work on other platforms, or report that check execution failed at runtime|Array|`getSupportedPlatforms()` - -## List all possible check types -```php -$checkTypes = $service->getCheckTypes(); - -foreach ($checkTypes as $checkType) { - echo $checkType->getId(); -} -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/checks.html diff --git a/docs/userguide/CloudMonitoring/Entities.md b/docs/userguide/CloudMonitoring/Entities.md index c9885604b..beed807a2 100644 --- a/docs/userguide/CloudMonitoring/Entities.md +++ b/docs/userguide/CloudMonitoring/Entities.md @@ -1,55 +1,5 @@ # Entities -## Info +Our docs have moved! Please visit the below link: -An entity is the target of what you are monitoring. For example, you can create an entity to monitor your website, a particular web service, or your Rackspace server. Note that an entity represents only one item in the monitoring system -- if you wanted to monitor each server in a cluster, you would create an entity for each of the servers. You would not create a single entity to represent the entire cluster. - -An entity can have multiple checks associated with it. This allows you to check multiple services on the same host by creating multiple checks on the same entity, instead of multiple entities each with a single check. - -## Setup - -```php -$entity = $service->getEntity(); -``` - -For more information about setting up the `$service` object, please see the userguide tutorial for [services](Service.md). - -## Attributes - -Name|Description|Required?|Data type|Method ----|---|---|---|--- -label|Defines a name for the entity.|Required|String (1..255 chars)|`getLabel()` -agent_id|Agent to which this entity is bound to.|Optional|String matching the regex: `/^[-\.\w]{1,255}$/`|`getAgentId()` -ip_addresses|Hash of IP addresses that can be referenced by checks on this entity.|Optional|Array|`getIpAddresses()` -metadata|Arbitrary key/value pairs that are passed during the alerting phase.|Optional|`OpenCloud\Common\Metadata`|`getMetadata()` - -## Create Entity -```php -$service->createEntity(array( - 'label' => 'Brand New Entity', - 'ip_addresses' => array( - 'default' => '127.0.0.4', - 'b' => '127.0.0.5', - 'c' => '127.0.0.6', - 'test' => '127.0.0.7' - ), - 'metadata' => array( - 'all' => 'kinds', - 'of' => 'stuff', - 'can' => 'go', - 'here' => 'null is not a valid value' - ) -)); -``` - - -## Update and delete Entity -```php -// Update -$entity->update(array( - 'label' => 'New label for my entity' -)); - -// Delete -$entity->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/entities.html diff --git a/docs/userguide/CloudMonitoring/Metrics.md b/docs/userguide/CloudMonitoring/Metrics.md index 6799f8881..0b275c97e 100644 --- a/docs/userguide/CloudMonitoring/Metrics.md +++ b/docs/userguide/CloudMonitoring/Metrics.md @@ -1,79 +1,5 @@ # Metrics -## Info +Our docs have moved! Please visit the below link: -When Monitoring checks run, they generate metrics. These metrics are stored as full resolution data points in the Cloud Monitoring system. Full resolution data points are periodically rolled up (condensed) into coarser data points. - -Depending on your needs, you can use the metrics API to fetch individual data points (fine-grained) or rolled up data points (coarse-grained) over a period of time. - -## Data Granularity - -Cloud Monitoring supports several granularities of data: full resolution data and rollups computed at 5, 20, 60, 240 and 1440 minute intervals. - -When you fetch metrics data points, you specify several parameters to control the granularity of data returned: - -- A time range for the points -- Either the number of points you want returned OR the resolution of the data you want returned - -When you query by points, the API selects the resolution that will return you the number of points you requested. The API makes the assumption of a 30 second frequency, performs the calculation, and selects the appropriate resolution. - -**Note:** Because the API performs calculations to determine the points returned for a particular resolution, the number of points returned may differ from the specific number of points you request. - -Consider that you want to query data for a 48-hour time range between the timestamps `from=1354647221000` and `to=1358794421000` ( **specified in Unix time, based on the number of milliseconds that have elapsed since January 1, 1970** ). The following table shows the number of points that the API returns for a given resolution. - -#### Specifying resolution to retrieve data in 48 hour period - -You specify resolution...|API returns points... ----|--- -FULL|5760 -MIN5|576 -MIN20|144 -MIN60|48 -MIN240|12 -MIN1440|2 - -#### Specifying number of points to retrieve data in 48 hour period - -You specify points in the range...|API calculates resolution ----|--- -3168-∞|FULL -360-3167|MIN5 -96-359|MIN20 -30-95|MIN60 -7-29|MIN240 -0-6|MIN1440 - -#### Data Point Expiration - -Cloud Monitoring expires data points according to the following schedule: - -Resolution|Expiration ----|--- -FULL|2 days -MIN5|7 days -MIN20|15 days -MIN60|30 days -MIN240|60 days -MIN1440|365 days - -## Setup - -Metrics are sub-resources of Checks. For more information about working with Checks, please see the [relevant documentation](Checks.md). - -## List all metrics -```php -$metrics = $check->getMetrics(); - -foreach ($metrics as $metric) { - echo $metric->getName(); -} -``` - -## Fetch data points -```php -$data = $check->fetchDataPoints('mzdfw.available', array( - 'resolution' => 'FULL', - 'from' => 1369756378450, - 'to' => 1369760279018 -)); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/metrics.html diff --git a/docs/userguide/CloudMonitoring/Notifications.md b/docs/userguide/CloudMonitoring/Notifications.md index 81a890f56..129881fae 100644 --- a/docs/userguide/CloudMonitoring/Notifications.md +++ b/docs/userguide/CloudMonitoring/Notifications.md @@ -1,203 +1,5 @@ # Notifications -## Info +Our docs have moved! Please visit the below link: -A notification is a destination to send an alarm; it can be a variety of different types, and will evolve over time. - -For instance, with a webhook type notification, Cloud Monitoring posts JSON formatted data to a user-specified URL on an alert condition (Check goes from `OK` -> `CRITICAL` and so on). - -## Setup - -```php -$id = 'ntAAAA'; -$notification = $service->getNotification($id); -``` - -## Attributes - -Name|Description|Data type|Method ----|---|---|---|--- -details|A hash of notification specific details based on the notification type.|Array|`getDetails()` -label|Friendly name for the notification.|String (1..255 chars)|`getLabel()` -type|The notification type to send.|String. Either `webhook`, `email`, or `pagerduty`|`getType()` - -## Test parameters -```php -$params = array( - 'label' => 'My webhook #1', - 'type' => 'webhook', - 'details' => array( - 'url' => 'http://example.com' - ) -); - -// Test it -$response = $notification->testParams($params); - -if ($response->status == 'Success') { - echo $response->message; -} -``` - -## Create Notification - -```php -$notification->create($params); -``` - -## Test existing notification -```php -$response = $notification->testExisting(true); -echo $response->debug_info; -``` - -## List Notifications -```php -$notifications = $service->getNotifications(); - -foreach ($notifications as $notification) { - echo $notification->getId(); -} -``` - -## Update and delete Notifications -```php -// Update -$notification->update(array( - 'label' => 'New notification label' -)); - -// Delete -$notification->delete(); -``` - -# Notification types - -## Info - -Pretty self-explanatory. Rackspace Cloud Monitoring currently supports the following notification types: - -#### Webhook - -Industry-standard web hooks, where JSON is posted to a configurable URL. It has these attributes: - -Name|Description|Data type ----|---|--- -address|Email address to send notifications to|Valid email - -#### Email - -Email alerts where the message is delivered to a specified address. It has these attributes: - -Name|Description|Data type ----|---|--- -url|An HTTP or HTTPS URL to POST to|Valid URL - -## Setup - -If you've already set up a main Notification object, and want to access functionality for this Notification's particular Notification Type, you can access its property: - -```php -$type = $notification->getNotificationType(); -``` - -Alternatively, you can retrieve an independent resource using the ID: - -```php -$typeId = 'pagerduty'; -$type = $service->getNotificationType($typeId); -``` - -## List all possible notification types -```php -$types = $service->getNotificationTypes(); - -foreach ($types as $type) { - echo sprintf('%s %s', $type->getName(), $type->getDescription()); -} -``` - -# Notification plans - -## Info - -A notification plan contains a set of notification actions that Rackspace Cloud Monitoring executes when triggered by an alarm. Rackspace Cloud Monitoring currently supports webhook and email notifications. - -Each notification state can contain multiple notification actions. For example, you can create a notification plan that hits a webhook/email to notify your operations team if a warning occurs. However, if the warning escalates to an Error, the notification plan could be configured to hit a different webhook/email that triggers both email and SMS messages to the operations team. The notification plan supports the following states: - -- Critical -- Warning -- OK - -A notification plan, `npTechnicalContactsEmail`, is provided by default which will email all of the technical contacts on file for an account whenever there is a state change. - -## Setup - -```php -$planId = 'npAAAA'; -$plan = $service->getNotificationPlan(); -``` - -## Attributes - -Name|Description|Required?|Data type|Method ----|---|---|---|--- -label|Friendly name for the notification plan.|Required|String (1..255 chars)|`getLabel()` -critical_state|The notification list to send to when the state is `CRITICAL`.|Optional|Array|`getCriticalState()` -ok_state|The notification list to send to when the state is `OK`.|Optional|Array|`getOkState()` -warning_state|The notification list to send to when the state is `WARNING`.|Optional|Array|`getWarningState()` - -## Create Notification Plan -```php -$plan->create(array( - 'label' => 'New Notification Plan', - 'critical_state' => array('ntAAAA'), - 'ok_state' => array('ntBBBB'), - 'warning_state' => array('ntCCCC') -)); -``` - -## Update and delete Notification Plan - -```php -// Update -$plan->update(array( - 'label' => 'New label for my plan' -)); - -// Delete -$plan->delete(); -``` - -# Alarm Notification History - -## Info - -The monitoring service keeps a record of notifications sent for each alarm. This history is further subdivided by the check on which the notification occurred. Every attempt to send a notification is recorded, making this history a valuable tool in diagnosing issues with unreceived notifications, in addition to offering a means of viewing the history of an alarm's statuses. - -Alarm notification history is accessible as a Time Series Collection. By default alarm notification history is stored for 30 days and the API queries the last 7 days of information. - -## Setup - -Notification History is a sub-resource of an Alarm. For more information about working with Alarms, please consult the relevant [documentation](Alarms.md). - -## Discover which Checks have a Notification History - -This operation list checks for which alarm notification history is available: - -```php -$checks = $alarm->getRecordedChecks(); -``` - -## List Alarm Notification History for a particular Check -```php -$checkHistory = $alarm->getNotificationHistoryForCheck('chAAAA'); -``` - -## Get a particular Notification History item -```php -$checkId = 'chAAAA'; -$itemUuid = '646ac7b0-0b34-11e1-a0a1-0ff89fa2fa26'; - -$singleItem = $history->getNotificationHistoryItem($checkId, $itemUuid); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/notifications.html diff --git a/docs/userguide/CloudMonitoring/Service.md b/docs/userguide/CloudMonitoring/Service.md index 5647eedc2..6445de039 100644 --- a/docs/userguide/CloudMonitoring/Service.md +++ b/docs/userguide/CloudMonitoring/Service.md @@ -1,16 +1,5 @@ # Cloud Monitoring Service -Initializing the Cloud Monitoring is easy - and can be done in a similar way to all other Rackspace services: +Our docs have moved! Please visit the below link: -1. Create client and pass in auth details. For more information about creating clients, please consult the [Client documentation](../Clients.md). -2. Use the factory method, specifying additional parameters where necessary: - -```php -$service = $client->cloudMonitoringService('cloudMonitoring', 'ORD', 'publicURL'); -``` - -All three parameters are optional - if not specified, it will revert to the service's default values which are: - -- Name = `cloudMonitoring` -- Region = `DFW` -- URL type = `publicURL` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/index.html diff --git a/docs/userguide/CloudMonitoring/Views.md b/docs/userguide/CloudMonitoring/Views.md index b6b505efc..ac0017db0 100644 --- a/docs/userguide/CloudMonitoring/Views.md +++ b/docs/userguide/CloudMonitoring/Views.md @@ -1,19 +1,5 @@ # Views -## Info +Our docs have moved! Please visit the below link: -Views contain a combination of data that usually includes multiple, different objects. The primary purpose of a view is to save API calls and make data retrieval more efficient. Instead of doing multiple API calls and then combining the result yourself, you can perform a single API call against the view endpoint. - -## List all Views - -```php -$views = $service->getViews(); - -foreach ($views as $view) { - $entity = $view->getEntity(); - - echo $view->getTimestamp(); -} - ``` - -Please consult the [iterator doc](docs/userguide/Iterators.md) for more information about iterators. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/views.html diff --git a/docs/userguide/CloudMonitoring/Zones.md b/docs/userguide/CloudMonitoring/Zones.md index 338bb1053..fcad4b900 100644 --- a/docs/userguide/CloudMonitoring/Zones.md +++ b/docs/userguide/CloudMonitoring/Zones.md @@ -1,46 +1,5 @@ # Zones -## Info +Our docs have moved! Please visit the below link: -A monitoring zone is a location that Rackspace Cloud Monitoring collects data from. Examples of monitoring zones are "US West", "DFW1" or "ORD1". It is an abstraction for a general location from which data is collected. - -An "endpoint," also known as a "collector," collects data from the monitoring zone. The endpoint is mapped directly to an individual machine or a virtual machine. A monitoring zone contains many endpoints, all of which will be within the IP address range listed in the response. The opposite is not true, however, as there may be unallocated IP addresses or unrelated machines within that IP address range. - -A check references a list of monitoring zones it should be run from. - -## Setup -```php -$zoneId = 'mzAAAAA'; -$zone = $monitoringService->getMonitoringZone($zoneId); -``` - -## Attributes - -Name|Description|Data type|Method ----|---|---|---|--- -country_code|Country Code|String longer than 2 characters|`getCountryCode()` -label|Label|String|`getLabel()` -source_ips|Source IP list|Array|`getSourceIps()` - -## List all zones - -```php -$zones = $service->getMonitoringZones(); -``` - -Please consult the [iterator doc](docs/userguide/Iterators.md) for more information about iterators. - -## Perform a traceroute - -```php -$traceroute = $zone->traceroute(array( - 'target' => 'http://test.com', - 'target_resolver' => 'IPv4' -)); - -// How many hops? -echo count($traceroute); - -// What was the first hop's IP? -echo $traceroute[0]->ip; -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/monitoring/zones.html diff --git a/docs/userguide/Compute/Images.md b/docs/userguide/Compute/Images.md index d09b0b0eb..6cc06d37f 100644 --- a/docs/userguide/Compute/Images.md +++ b/docs/userguide/Compute/Images.md @@ -1,65 +1,5 @@ # Compute Images -## Intro +Our docs have moved! Please visit the below link: -An image is a collection of files for a specific operating system that you use to create or rebuild a server. Rackspace provides prebuilt images. You can also create custom images from servers that you have launched. - -In addition to creating images manually, you can also schedule images of your server automatically. Please consult the [official docs](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/scheduled_images.html) for more information about this extension, including enabling and disabling scheduled images and showing scheduled images. - -With standard servers, the entire disk (OS and data) is captured in the image. With Performance servers, only the system disk is captured in the image. The data disks should be backed up using Cloud Backup or Cloud Block Storage to ensure availability in case you need to rebuild or restore a server. - -## Setup - -You first need to setup a Compute service. For information, please consult the [Compute service](Service.md) documentation. - -## List images - -```php -$images = $service->imageList(); - -foreach ($images as $image) { - -} -``` - -For more information about [iterators](docs/userguide/Iterators.md), please consult the official documentation. - -### Query parameters - -You can also refine the list of images returned by providing specific URL parameters: - -|Field name|Description| -|---|---| -|server|Filters the list of images by server. Specify the server reference by ID or by full URL.| -|name|Filters the list of images by image name.| -|status|Filters the list of images by status. In-flight images have a status of `SAVING` and the conditional progress element contains a value from 0 to 100, which indicates the percentage completion. For a full list, please consult the `OpenCloud\Compute\Constants\ImageState` class. Images with an `ACTIVE` status are available for use.| -|changes-since|Filters the list of images to those that have changed since the changes-since time. See the [official docs](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ChangesSince.html) for more information.| -|marker|The ID of the last item in the previous list. See the [official docs](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Paginated_Collections-d1e664.html) for more information.| -|limit|Sets the page size. See the [official docs](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Paginated_Collections-d1e664.html) for more information.| -|type|Filters base Rackspace images or any custom server images that you have created. Can either be `BASE` or `SNAPSHOT`.| - -### Example - -You can return more information about each image by setting the `$details` argument to `true`. The second argument can be an array of query parameters: - -```php -use OpenCloud\Compute\Constants\ImageState; - -$list = $service->imageList(true, array( - 'server' => 'fooBar', - 'status' => ImageState::ACTIVE -)); -``` - -## Get an image - -```php -$imageId = '3afe97b2-26dc-49c5-a2cc-a2fc8d80c001'; -$image = $service->image($imageId); -``` - -## Delete an image - -```php -$image->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/compute/images.html diff --git a/docs/userguide/Compute/Keypair.md b/docs/userguide/Compute/Keypair.md index e314db32c..37e5080fe 100644 --- a/docs/userguide/Compute/Keypair.md +++ b/docs/userguide/Compute/Keypair.md @@ -1,91 +1,5 @@ # Keypairs -## Generate new keypair +Our docs have moved! Please visit the below link: -This operation creates a new keypair under a provided name; the public key value is automatically generated for you. - -```php -$keypair = $service->keypair(); - -$keypair->create(array( - 'name' => 'jamie_keypair_1' -)); - -echo $keypair->getPublicKey(); - -// Save private key to a file so you can use it to SSH into -// your server later. -$sshPrivateKeyFilename = 'jamie_keypair_1_rsa'; -$privateKey = $keypair->getPrivateKey(); -file_put_contents($sshPrivateKeyFilename, $privateKey); -chmod($sshPrivateKeyFilename, 0600); -``` - -## Upload existing keypair - -This operation creates a new keypair under a provided name using a provided public key value. This public key will probably exist on your local filesystem, and so provide easy access to your server when uploaded. - -```php -$keypair = $service->keypair(); - -$key = <<create(array( - 'name' => 'jamie_macbook', - 'publicKey' => $key -)); - -``` - -## List keypairs - -To list all existing keypairs: - -```php -$keys = $service->listKeypairs(); - -foreach ($keys as $key) { - // ... -} -``` - -For more information about iterators, please see [the docs](../Iterators.md). - -## Delete keypairs - -To delete a specific keypair: - -```php -$keypair->delete(); -``` - -## Creating a server with a keypair - -In order to spawn an instance with a saved keypair (allowing you to SSH in without passwords), you create your server -using the same operation as usual, with one extra parameter: - -```php -use Guzzle\Http\Exception\BadResponseException; -use OpenCloud\Compute\Constants\Network; - -$server = $compute->server(); - -try { - $response = $server->create(array( - 'name' => 'New server', - 'image' => $ubuntuImage, - 'flavor' => $twoGbFlavor, - 'networks' => array( - $compute->network(Network::RAX_PUBLIC), - $compute->network(Network::RAX_PRIVATE) - ), - 'keypair' => 'jamie_macbook' - )); -} catch (BadResponseException $e) { - // error... -} -``` - -So, as you can see, you specify the **name** of an existing keypair that you previously created on the API. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/compute/keypairs.html diff --git a/docs/userguide/Compute/Server.md b/docs/userguide/Compute/Server.md index 8cc0d17e7..e43e1cc42 100644 --- a/docs/userguide/Compute/Server.md +++ b/docs/userguide/Compute/Server.md @@ -1,180 +1,5 @@ # Servers -## Intro +Our docs have moved! Please visit the below link: -A server is a virtual machine instance in the Cloud Servers environment. - -## Setup - -Server objects are instantiated from the Compute service. For more details, see the [Service](Service.md) docs. - -## Get server - -The easiest way to retrieve a specific server is by its unique ID: - -```php -$serverId = 'ef08aa7a-b5e4-4bb8-86df-5ac56230f841'; -$server = $service->server($serverId); -``` - -## List servers - -You can list servers in two different ways: - -* return an _overview_ of each server (ID, name and links) -* return _detailed information_ for each server - -Knowing which option to use might help save unnecessary bandwidth and reduce latency. - -```php -// overview -$servers = $service->serverList(); - -// detailed -$servers = $service->serverList(true); -``` - -### URL parameters for filtering servers - -Name|Description|Type ----|---|--- -image|The image ID|string -flavor|The flavor ID|string -name|The server name|string -status|The server status. Servers contain a status attribute that indicates the current server state. You can filter on the server status when you complete a list servers request, and the server status is returned in the response body. For a full list, please consult `OpenCloud\Compute\Constants\ServerState`|string -changes-since|Value for checking for changes since a previous request|A valid ISO 8601 dateTime (2011-01-24T17:08Z) -RAX-SI:image_schedule|If scheduled images enabled or not. If the value is TRUE, the list contains all servers that have an image schedule resource set on them. If the value is set to FALSE, the list contains all servers that do not have an image schedule.|bool - -## Create server - -### Using an image - -There are a few parameter requirements when creating a server using an image: - -* **name** - needs to be a string; -- **flavor** - a `OpenCloud\Compute\Resource\Flavor` object, that is populated with the values of a real API flavor; -* **image** - a `OpenCloud\Compute\Resource\Image` object, that is populated with the values of a real API image; - -Firstly we need to find our flavor and image using their UUIDs. For more information about these concepts, including how to find flavor/image UUIDs, please consult §§ 3-4 in the [Getting Started guide](https://github.com/rackspace/php-opencloud/blob/master/docs/getting-started.md#3-select-your-server-image). - -```php -$ubuntuImage = $compute->image('868a0966-0553-42fe-b8b3-5cadc0e0b3c5'); -$twoGbFlavor = $compute->flavor('4'); -``` - -Now we're ready to create our instance: - -```php -use OpenCloud\Compute\Constants\Network; - -$server = $compute->server(); - -try { - $response = $server->create(array( - 'name' => 'My lovely server', - 'image' => $ubuntuImage, - 'flavor' => $twoGbFlavor - )); -} catch (\Guzzle\Http\Exception\BadResponseException $e) { - - // No! Something failed. Let's find out: - $responseBody = (string) $e->getResponse()->getBody(); - $statusCode = $e->getResponse()->getStatusCode(); - $headers = $e->getResponse()->getHeaderLines(); - - echo sprintf('Status: %s\nBody: %s\nHeaders: %s', $statusCode, $responseBody, implode(', ', $headers); -} -``` - -It's always best to be defensive when executing functionality over HTTP; you can achieve this best by wrapping calls in a try/catch block. It allows you to debug your failed operations in a graceful and efficient manner. - -### Using a bootable volume - -There are a few parameter requirements when creating a server using a bootable volume: - -* **name** - needs to be a string; -* **flavor** - a `OpenCloud\Compute\Resource\Flavor` object, that is populated with the values of a real API flavor; -* **volume** - a `OpenCloud\Volume\Resource\Volume` object, that is populated with the values of a real API volume; - -Firstly we need to find our flavor and volume using their IDs. - -```php -$volumeService = $client->volumeService(); -$bootableVolume = $volumeService->volume(''); -$flavor = $compute->flavor(''); -``` - -Now we're ready to create our instance: - -```php -use OpenCloud\Compute\Constants\Network; - -$server = $compute->server(); - -try { - $response = $server->create(array( - 'name' => 'My lovely server', - 'volume' => $bootableVolume, - 'flavor' => $flavor - )); -} catch (\Guzzle\Http\Exception\BadResponseException $e) { - // No! Something failed. Let's find out: - echo $e->getRequest() . PHP_EOL . PHP_EOL; - echo $e->getResponse(); -} -``` - -It's always best to be defensive when executing functionality over HTTP; you can achieve this best by wrapping calls in a try/catch block. It allows you to debug your failed operations in a graceful and efficient manner. - -### Create parameters - -Name|Description|Type|Required ----|---|---|--- -name|The server name. The name that you specify in a create request becomes the initial host name of the server. After the server is built, if you change the server name in the API or change the host name directly, the names are not kept in sync.|string|Yes -flavor|A populated `OpenCloud\Compute\Resource\Flavor` object representing your chosen flavor|object|Yes -image|A populated `OpenCloud\Compute\Resource\Image` object representing your chosen image|object|No, if volume is specified -volume|A populated `OpenCloud\Volume\Resource\Volume` object representing your chosen bootable volume|object|No, if image is specified -volumeDeleteOnTermination|`true` if the bootable volume should be deleted when the server is terminated; `false`, otherwise|boolean|No; default = `false` -OS-DCF:diskConfig|The disk configuration value. You can use two options: `AUTO` or `MANUAL`.

`AUTO` means the server is built with a single partition the size of the target flavor disk. The file system is automatically adjusted to fit the entire partition. This keeps things simple and automated. `AUTO` is valid only for images and servers with a single partition that use the EXT3 file system. This is the default setting for applicable Rackspace base images.

`MANUAL` means the server is built using whatever partition scheme and file system is in the source image. If the target flavor disk is larger, the remaining disk space is left unpartitioned. This enables images to have non-EXT3 file systems, multiple partitions, and so on, and enables you to manage the disk configuration.|string|No -networks|An array of populated `OpenCloud\Compute\Resource\Network` objects that indicate which networks your instance resides in.|array|No -metadata|An array of arbitrary data (key-value pairs) that adds additional meaning to your server.|array|No -keypair|You can install a registered keypair onto your newly created instance, thereby providing scope for keypair-based authentication.|array|No -personality|Files that you can upload to your newly created instance's filesystem.|array|No - -### Creating a server with keypairs - -Please see the [Keypair](Keypair.md) docs for more information. - -### Creating a server with personality files - -Before you execute the create operation, you can add "personality" files to your `OpenCloud\Compute\Resource\Server` object. These files are structured as a flat array. - -```php -$server->addFile('/var/test_file', 'FILE CONTENT'); -``` - -As you can see, the first parameter represents the filename, and the second is a string representation of its content. When the server is created these files will be created on its local filesystem. For more information about server personality files, please consult the [official documentation](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/Server_Personality-d1e2543.html). - -## Update server - -You can update certain attributes of an existing server instance. These attributes are detailed in the next section. - -```php -$server->update(array( - 'name' => 'NEW SERVER NAME' -)); -``` - -### Updatable attributes - -name|description ----|--- -name|The name of the server. If you edit the server name, the server host name does not change. Also, server names are not guaranteed to be unique. -accessIPv4|The IP version 4 address. -accessIPv6|The IP version 6 address. - -## Delete server - -```php -$server->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/compute/servers.html diff --git a/docs/userguide/Compute/Service.md b/docs/userguide/Compute/Service.md index faff788bb..ba49ff4e4 100644 --- a/docs/userguide/Compute/Service.md +++ b/docs/userguide/Compute/Service.md @@ -1,18 +1,5 @@ # Compute service -## Setup +Our docs have moved! Please visit the below link: -To instantiate a Compute service object, you first need to setup a Rackspace/OpenStack client. To do this, or for more -information, please consult the [Clients documentation](../Clients.md). - -```php -$service = $client->computeService(); -``` - -If no arguments are provided to the above method, certain values are set to their default values: - -|Param|Default value| -|---|---| -|`$name`|cloudServersOpenStack| -|`$region`|DFW| -|`$urltype`|publicURL| \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/compute/index.html diff --git a/docs/userguide/DNS/Domains.md b/docs/userguide/DNS/Domains.md index f0d94efee..d8d3a12d3 100644 --- a/docs/userguide/DNS/Domains.md +++ b/docs/userguide/DNS/Domains.md @@ -1,230 +1,5 @@ # Domains -A domain is an entity/container of all DNS-related information containing one or more records. +Our docs have moved! Please visit the below link: -## Setup - -Limit methods will be called on the DNS service, an instance of `OpenCloud\DNS\Service`. Please see the [DNS service](Service.md) documentation for setup instructions. - -## Get domain - -To retrieve a specific domain, you will need the domain's **id**, not its domain name. - -```php -$domain = $service->domain(12345); -``` - -If you are having trouble remembering or accessing the domain ID, you can do a domain list search for your domain and then access its ID. - -## List domains - -These calls provide a list of all DNS domains manageable by a given account. The resulting list is flat, and does not break the domains down hierarchically by subdomain. All representative domains are included in the list, even if a domain is conceptually a subdomain of another domain in the list. - -```php -$domains = $service->domainList(); - -# Return detailed information for each domain -$domains = $service->domainList(true); -``` - -Please consult the [iterator documentation](/docs/userguide/Iterators.md) for more information about iterators. - -### Filter parameters - -You can filter the aforementioned search by using the `name` parameter in a key/value array supplied as a method argument. For example, providing `array('name' => 'hoola.com')` will return hoola.com and similar names such as main.hoola.com and sub.hoola.com. - -```php -$hoolaDomains = $service->domainList(array( - 'name' => 'hoola.com' -)); -``` - -Filter criteria may consist of: - -- Any letter (A-Za-z) -- Numbers (0-9) -- Hyphen ("-") -- 1 to 63 characters - -Filter criteria should not include any of the following characters: - -> ' + , | ! " £ $ % & / ( ) = ? ^ * ç ° § ; : _ > ] [ @ à, é, ò - -### Finding a domain ID - -If you know a domain's name, but not its unique identifier, you can do this: - -```php -$domains = $service->domainList(array( - 'name' => 'foo.com' -)); - -foreach ($domains as $domain) { - $id = $domain->id; -} -``` - -## List domain changes - -This call shows all changes to the specified domain since the specified date/time. The since parameter is optional and defaults to midnight of the current day. - -```php -$changes = $domain->changes(); - -# Changes since last week -$since = date('c', strtotime('last week')); -$changes = $domain->changes($since); - -foreach ($changes->changes as $change) { - printf("Domain: %s\nAction: %s\nTarget: %s", $change->domain, $change->action, $change->targetType); - - foreach ($change->changeDetails as $detail) { - printf("Details: %s was changed from %s to %s", $detail->field, $detail->oldValue, $detail->newValue); - } -} -``` - -## Export domain - -This call provides the BIND (Berkeley Internet Name Domain) 9 formatted contents of the requested domain. This call is for a single domain only, and as such, does not traverse up or down the domain hierarchy for details (that is, no subdomain information is provided). - -```php -$asyncResponse = $domain->export(); -$body = $asyncResponse->waitFor('COMPLETED'); -echo $body['contents']; -``` - -## Create domain - -A domain is composed of DNS records (e.g. `A`, `CNAME` or `MX` records) and an optional list of sub-domains. You will need to specify these before creating the domain itself: - -```php -// get empty object -$domain = $service->domain(); - -// add A record -$aRecord = $domain->record(array( - 'type' => 'A', - 'name' => 'example.com', - 'data' => '192.0.2.17', - 'ttl' => 3600 -)); -$domain->addRecord($aRecord); - -// add optional C record -$cRecord = $domain->record(array( - 'type' => 'CNAME', - 'name' => 'www.example.com', - 'data' => 'example.com', - 'ttl' => 3600 -)); -$domain->addRecord($cRecord); - -// add optional MX record -$mxRecord = $domain->record(array( - 'type' => 'MX', - 'data' => 'mail.example.com', - 'name' => 'example.com', - 'ttl' => 3600, - 'priority' => 5 -)); -$domain->addRecord($mxRecord); - -// add optional NS records -$nsRecord1 = $domain->record(array( - 'type' => 'NS', - 'data' => 'dns1.stabletransit.com', - 'name' => 'example.com', - 'ttl' => 5400 -)); -$domain->addRecord($nsRecord1); - -$nsRecord2 = $domain->record(array( - 'type' => 'NS', - 'data' => 'dns2.stabletransit.com', - 'name' => 'example.com', - 'ttl' => 5400 -)); -$domain->addRecord($nsRecord2); - -// add optional subdomains -$sub1 = $domain->subdomain(array( - 'emailAddress' => 'foo@example.com', - 'name' => 'dev.example.com', - 'comment' => 'Dev portal' -)); -$domain->addSubdomain($sub1); - -// send to API -$domain->create(array( - 'emailAddress' => 'webmaster@example.com', - 'ttl' => 3600, - 'name' => 'example.com', - 'comment' => 'Optional comment' -)); -``` - -## Clone domain - -This call will duplicate a single existing domain configuration with a new domain name for the specified Cloud account. By default, all records and, optionally, subdomain(s) are duplicated as well. - -The method signature you will need to use is: - -```php -cloneDomain ( string $newDomainName [, bool $subdomains [, bool $comments [, bool $email [, bool $records ]]]] ) -``` - -Name|Data type|Default|Description ----|---|---|--- -`$newDomainName`|`string`|-|The new name for your cloned domain -`$subdomains`|`bool`|`true`|Set to `TRUE` to clone all the subdomains for this domain -`$comments`|`bool`|`true`|Set to `TRUE` to replace occurrences of the reference domain name with the new domain name in comments on the cloned (new) domain. -`$email`|`bool`|`true`|Set to `TRUE` to replace occurrences of the reference domain name with the new domain name in data fields (of records) on the cloned (new) domain. Does not affect NS records. - -For example: - -```php -$asyncResponse = $domain->cloneDomain('new-name.com', true); -``` - -## Import domain - -This call provisions a new DNS domain under the account specified by the BIND 9 formatted file configuration contents defined in the request object. - -You will need to ensure that the BIND 9 formatted file configuration contents are valid by adhering to the following rules: - -- Each record starts on a new line and on the first column. If a record will not fit on one line, use the BIND_9 line continuation convention where you put a left parenthesis and continue the one record on the next line and put a right parenthesis when the record ends. For example, - - > example2.net. 3600 IN SOA dns1.stabletransit.com. ( - sample@rackspace.com. 1308874739 3600 3600 3600 3600) - -- The attribute values of a record must be separated by a single blank or tab. No other white space characters. - -- If there are any NS records, the data field should not be dns1.stabletransit.com or dns2.stabletransit.com. They will result in "duplicate record" errors. - -For example: - -```php -$bind9Data = <<import($bind9Data); -``` - -## Modify domain - -This call modifies DNS domain(s) attributes only. Only the TTL, email address and comment attributes of a domain can be modified. Records cannot be added, modified, or removed through this API operation - you will need to use the [add records](/docs/userguide/DNS/Records.md#add-record), [modify records](/docs/userguide/DNS/Records.md#modify-record) or [remove records](/docs/userguide/DNS/Records.md#delete-record) operations respectively. - -```php -$domain->update(array( - 'ttl' => ($domain->ttl + 100), - 'emailAddress' => 'new_dev@foo.com' -)); -``` - -## Remove domain - -```php -$domain->delete(); -``` +https://doc.php-opencloud.com/en/latest/services/dns/domains.html diff --git a/docs/userguide/DNS/Limits.md b/docs/userguide/DNS/Limits.md index 6e7aeb042..70fac6504 100644 --- a/docs/userguide/DNS/Limits.md +++ b/docs/userguide/DNS/Limits.md @@ -1,58 +1,5 @@ # Limits -## Setup +Our docs have moved! Please visit the below link: -Limit methods will be called on the DNS service, an instance of `OpenCloud\DNS\Service`. Please see the [DNS service](Service.md) documentation for setup instructions. - -## List all limits - -This call provides a list of all applicable limits for the specified account. - -```php -$limits = $service->limits(); -``` - -### Absolute limits - -There are some absolute limits imposed on your account - such as how many domains you can create and how many records you can create for each domain: - -```php -$absoluteLimits = $limits->absolute; - -# Domain limit -echo $absoluteLimits->domains; - -# Record limit per domain -echo $absoluteLimits->{'records per domain'}; -``` - -## List limit types - -To find out the different limit types you can query, run: - -```php -$limitTypes = $service->limitTypes(); -``` - -will return: - -``` -array(3) { - [0] => - string(10) "RATE_LIMIT" - [1] => - string(12) "DOMAIN_LIMIT" - [2] => - string(19) "DOMAIN_RECORD_LIMIT" -} -``` - -## Query a specific limit - -```php -$limit = $service->limits('DOMAIN_LIMIT'); - -echo $limit->absolute->limits->value; - ->>> 500 -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/dns/limits.html diff --git a/docs/userguide/DNS/Records.md b/docs/userguide/DNS/Records.md index b8f71bda2..52998b955 100644 --- a/docs/userguide/DNS/Records.md +++ b/docs/userguide/DNS/Records.md @@ -1,87 +1,5 @@ # Records -A DNS record belongs to a particular domain and is used to specify information about the domain. +Our docs have moved! Please visit the below link: -There are several types of DNS records. Examples include mail exchange (MX) records, which specify the mail server for a particular domain, and name server (NS) records, which specify the authoritative name servers for a domain. - -It is represented by the `OpenCloud\DNS\Resource\Record` class. Records belong to a [Domain](Domains.md). - -## Get record - -In order to retrieve details for a specific DNS record, you will need its **id**: - -```php -$record = $domain->record('NS-1234567'); -``` - -If you do not have this ID at your disposal, you can traverse the record collection and do a string comparison (detailed below). - -## List records - -This call lists all records configured for the specified domain. - -```php -$records = $domain->recordList(); - -foreach ($records as $record) { - printf("Record name: %s, ID: %s, TTL: %s\n", $record->name, $record->id, $record->ttl); -} -``` - -Please consult the [iterator documentation](docs/userguide/Iterators.md) for more information about iterators. - -### Query parameters - -You can pass in an array of query parameters for greater control over your search: - -Name|Data type|Default|Description ----|---|---|--- -`type`|`string`|The record type -`name`|`string`|The record name -`data`|`string`|Data for this record - -### Find a record ID from its name - -For example: - -```php -$records = $domain->recordList(array( - 'name' => 'imap.example.com', - 'type' => 'MX' -)); - -foreach ($records as $record) { - $recordId = $record->id; -} -``` - -## Add record - -This call adds a new record to the specified domain: - -```php -$record = $domain->record(array( - 'type' => 'A', - 'name' => 'example.com', - 'data' => '192.0.2.17', - 'ttl' => 3600 -)); - -$record->create(); -``` - -Please be aware that records that are added with a different hostname than the parent domain might fail silently. - -## Modify record - -```php -$record = $domain->record(123456); -$record->ttl -= 100; -$record->update(); -``` - -## Delete record - -```php -$record->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/dns/records.html diff --git a/docs/userguide/DNS/Reverse-DNS.md b/docs/userguide/DNS/Reverse-DNS.md index a269a0057..e930431c1 100644 --- a/docs/userguide/DNS/Reverse-DNS.md +++ b/docs/userguide/DNS/Reverse-DNS.md @@ -1,71 +1,5 @@ # Reverse DNS -DNS usually determines an IP address associated with a domain name. Reverse DNS is the opposite process: resolving a domain name from an IP address. This is usually achieved with a domain name pointer. +Our docs have moved! Please visit the below link: -## Get PTR record - -PTR records refer to a parent device: either a Cloud Server or a Cloud Load Balancer with a public virtual IP address. You must supply a fully formed resource object in order to retrieve either one's PTR record: - -```php -/** @param $parent OpenCloud\DNS\Resource\HasPtrRecordsInterface */ - -$ptr = $service->ptrRecord(array( - 'parent' => $parent -)); -``` - -So, in the above example, a `$parent` could be an instance of `OpenCloud\Compute\Resource\Server` or `OpenCloud\LoadBalancer\Resource\LoadBalancer` - because they both implement `OpenCloud\DNS\Resource\HadPtrRecordsInterface`. Please consult the [server documentation](../Compute/Server.md) and [load balancer documentation](../LoadBalancer/USERGUIDE.md) for more detailed usage instructions. - -## List PTR records - -```php -/** @param $parent OpenCloud\DNS\Resource\HasPtrRecordsInterface */ - -$ptrRecords = $service->ptrRecordList($parent); - -foreach ($ptrRecords as $ptrRecord) { - -} -``` - -Please consult the [iterator documentation](docs/userguide/Iterators.md) for more information about iterators. - -## Add PTR record - -```php -$parent = $computeService->server('foo-server-id'); - -$ptr = $dnsService->ptrRecord(array( - 'parent' => $parent, - 'ttl' => 3600, - 'name' => 'example.com', - 'type' => 'PTR', - 'data' => '192.0.2.7' -)); - -$ptr->create(); -``` - -Here is a table that explains the above attributes: - -Name|Description|Required ----|---|--- -type|Specifies the record type as "PTR".|Yes -name|Specifies the name for the domain or subdomain. Must be a valid domain name.|Yes -data|The data field for PTR records must be a valid IPv4 or IPv6 IP address.|Yes -ttl|If specified, must be greater than 300. Defaults to 3600 if no TTL is specified.|No -comment|If included, its length must be less than or equal to 160 characters.|No - -## Modify PTR record - -```php -$ptr->update(array( - 'ttl' => $ptr->ttl * 2 -)); -``` - -## Delete PTR record - -```php -$ptr->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/dns/reverse-dns.html diff --git a/docs/userguide/DNS/Service.md b/docs/userguide/DNS/Service.md index ccabb1242..3404ed7c7 100644 --- a/docs/userguide/DNS/Service.md +++ b/docs/userguide/DNS/Service.md @@ -1,11 +1,5 @@ # DNS Service -To instantiate a Compute service object, you first need to setup a -Rackspace/OpenStack client. To do this, or for more information, please consult -the [Clients documentation](../Clients.md). +Our docs have moved! Please visit the below link: -You will then need to run: - -```php -$service = $client->dnsService(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/dns/index.html diff --git a/docs/userguide/Database/README.md b/docs/userguide/Database/README.md index 9a5822e5b..199d049e4 100644 --- a/docs/userguide/Database/README.md +++ b/docs/userguide/Database/README.md @@ -1,116 +1,5 @@ # Databases -A **cloud database** is a MySQL relational database service that allows -customers to programatically provision database instances of varying virtual -resource sizes without the need to maintain and/or update MySQL. +Our docs have moved! Please visit the below link: -## Getting started - -### 1. Instantiate a Rackspace client. - -```php -use OpenCloud\Rackspace; -use OpenCloud\Common\Constants\State; - -$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' -)); -``` - -### 2. Create a database server instance. - -```php -$databaseService = $client->databaseService('cloudDatabases', 'DFW'); - -$twoGbFlavor = $databaseService->flavor(3); - -$dbInstance = $databaseService->instance(); -$dbInstance->name = 'Demo database instance'; -$dbInstance->volume = new stdClass(); -$dbInstance->volume->size = 20; // GB -$dbInstance->flavor = $twoGbFlavor; -$dbInstance->create(); - -$dbInstance->waitFor(State::ACTIVE, null, function ($dbInstance) { - - printf("Database instance build status: %s\n", $dbInstance->status); - -}); -``` - -The example above creates a database server instance with 20GB of disk space and -2GB of memory, then waits for it to become ACTIVE. - -### 3. Create a database on the database server instance. - -```php -$db = $dbInstance->database(); -$db->name = 'demo_db'; - -$db->create(); -``` - -The example above creates a database named `demo_db` on the database server -instance created in the previous step. - -### 4. Create database user and give it access to database. - -```php -$user = $dbInstance->user(); -$user->name = 'demo_user'; -$user->password = 'h@X0r!'; -$user->databases = array('demo_db'); - -$user->create(); -``` - -The example above creates a database user named `demo_user`, sets its password -and gives it access to the `demo_db` database created in the previous step. - -### 5. Optional step: Create a load balancer to allow access to the database from the Internet. - -The database created in the previous step can only be accessed from the Rackspace -private network (aka `SERVICENET`). If you have a cloud server instance in the same -region as the database server instance, you will be able to connect to the database -from that cloud server instance. - -If, however, you would like to access the database from the Internet, you will -need to create a load balancer with an IP address that is routable from the -Internet and attach the database server instance as a back-end node of this load -balancer. - -```php -$loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); - -$loadBalancer = $loadBalancerService->loadBalancer(); - -$loadBalancer->name = 'Load balancer - DB'; -$loadBalancer->addNode($dbInstance->hostname, 3306); -$loadBalancer->port = 3306; -$loadBalancer->protocol = 'MYSQL'; -$loadBalancer->addVirtualIp('PUBLIC'); - -$loadBalancer->create(); - -$loadBalancer->waitFor(State::ACTIVE, null, function ($lb) { - printf("Load balancer build status: %s\n", $lb->status); -}); - -foreach ($loadBalancer->virtualIps as $vip) { - if ($vip->type == 'PUBLIC') { - printf("Load balancer public %s address: %s\n", $vip->ipVersion, $vip->address); - } -} -``` - -In the example above, a load balancer is created with the database server -instance as its only back-end node. Further, this load balancer is configured -to listen for MySQL connections on port 3306. Finally a virtual IP address (VIP) -is configured in the `PUBLIC` network address space so that this load balancer -may receive connections from the Internet. - -Once the load balancer is created and becomes `ACTIVE`, it's Internet-accessible -IP addresses are printed out. If you connect to any of these IP addresses on port -3306 using the MySQL protocol, you will be connected to the database created in -step 3. +https://doc.php-opencloud.com/en/latest/services/database/index.html diff --git a/docs/userguide/Debugging.md b/docs/userguide/Debugging.md index 0fc970c0a..0c6afa4d6 100644 --- a/docs/userguide/Debugging.md +++ b/docs/userguide/Debugging.md @@ -1,89 +1,5 @@ # Debugging -There are two important debugging strategies to use when encountering problems -with HTTP transactions. +Our docs have moved! Please visit the below link: -## Strategy 1: Meaningful exception handling - -If the API returns a `4xx` or `5xx` status code, it indicates that there was an -error with the sent request, meaning that the transaction cannot be adequately -completed. - -The Guzzle HTTP component, which forms the basis of our SDK's transport layer, -utilizes [numerous exception classes](https://github.com/guzzle/guzzle/tree/master/src/Guzzle/Http/Exception) -to handle this error logic. - -The two most common exception classes are: - -* `Guzzle\Http\Exception\ClientErrorResponseException`, which is thrown when a -`4xx` response occurs - -* `Guzzle\Http\Exception\ServerErrorResponseException`, which is thrown when a -`5xx` response occurs - -Both of these classes extend the base `BadResponseException` class. - -This provides you with the granularity you need to debug and handle exceptions. - -### An example with Swift - -If you're trying to retrieve a Swift resource, such as a Data Object, and you're -not completely certain that it exists, it makes sense to wrap your call in a -try/catch block: - -```php -use Guzzle\Http\Exception\ClientErrorResponseException; - -try { - return $service->getObject('foo.jpg'); -} catch (ClientErrorResponseException $e) { - // Okay, the resource probably does not exist - return false; -} catch (\Exception $e) { - // Some other exception was thrown, probably critical - $this->logException($e); - $this->alertDevs(); -} -``` - -Both `ClientErrorResponseException` and `ServerErrorResponseException` have -two methods that allow you to access the HTTP transaction: - -```php -// Find out the faulty request -$request = $e->getRequest(); - -// Display everything by casting as string -echo (string) $request; - -// Find out the HTTP response -$response = $e->getResponse(); - -// Output that too -echo (string) $response; -``` - -## Strategy 2: Wire logging - -Guzzle provides a [Log plugin](http://docs.guzzlephp.org/en/latest/plugins/log-plugin.html) -that allows you to log everything over the wire, which is useful if you don't -know what's going on. - -Here's how you enable it: - -#### Install the plugin - -```bash -php composer.phar require guzzle/plugin-log:~3.8 -``` - -#### Add to your client - -```php -use Guzzle\Plugin\Log\LogPlugin; - -$client->addSubscriber(LogPlugin::getDebugPlugin()); -``` - -The above will add a generic logging subscriber to your client, which will be -notified every time a relevant HTTP event is fired off. +https://doc.php-opencloud.com/en/latest/debugging.html diff --git a/docs/userguide/Identity/Roles.md b/docs/userguide/Identity/Roles.md index e2d49e71d..333d53c81 100644 --- a/docs/userguide/Identity/Roles.md +++ b/docs/userguide/Identity/Roles.md @@ -1,68 +1,5 @@ # Roles -## Intro +Our docs have moved! Please visit the below link: -A role is a personality that a user assumes when performing a specific set of operations. A role includes a set of rights and privileges. A user assuming a role inherits the rights and privileges associated with the role. A token that is issued to a user includes the list of roles the user can assume. When a user calls a service, that service determines how to interpret a user's roles. A role that grants access to a list of operations or resources within one service may grant access to a completely different list when interpreted by a different service. - -## Setup - -Role objects are instantiated from the Identity service. For more details, see the [Service](Service.md) docs. - -## Useful object properties/methods - -Property|Getter|Setter ----|---|--- -id|`getId()`|`setId()` -name|`getName()`|`setName()` -description|`getDescription()`|`setDescription()` - -## List roles - -This call lists the global roles available within a specified service. - -```php -$roles = $service->getRoles(); - -foreach ($roles as $role) { - // ... -} -``` - -For more information about how to use iterators, see the [documentation](../Iterators.md). - -## Get role - -This call lists detailed information (id, name, description) for a specified role. - -```php -$roleId = '123abc'; -$role = $service->getRole($roleId); -``` - -## Add/delete user roles - -To add/remove user roles, you must first instantiate a [user](Users.md) object: - -```php -$roleId = '123abc'; - -// add role to user -$user->addRole($roleId); - -// remove role from user -$user->removeRole($roleId); -``` - -## List user global roles - -This call returns a list of global roles associated with a user: - -```php -$roles = $user->getRoles(); - -foreach ($roles as $role) { - // ... -} -``` - -For more information about how to use iterators, see the [documentation](../Iterators.md). \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/identity/roles.html diff --git a/docs/userguide/Identity/Service.md b/docs/userguide/Identity/Service.md index 6cc80eb5a..579cf2a9f 100644 --- a/docs/userguide/Identity/Service.md +++ b/docs/userguide/Identity/Service.md @@ -1,24 +1,5 @@ # Identity service -## Intro +Our docs have moved! Please visit the below link: -The Identity service is regionless, so you do not need to specify a region when instantiating the service object. Although this was primarily based on Rackspace's implementation of Cloud Identity, it should also work for OpenStack Keystone. - -## A note on object creation - -Normally, when services are created the client handles authenticates automatically. But because Keystone/Identity is fundamental to the authentication process itself, it proves difficult to do this procedure as its normally done. For this reason, you have two options when creating the service object: - -1: Use the client's factory method - -```php -$identity = $client->identityService(); -``` - -2: Authenticate manually - -```php -use OpenCloud\Identity\Service as IdentityService; - -$identity = IdentityService::factory($client); -$identity->getClient()->authenticate(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/identity/index.html diff --git a/docs/userguide/Identity/Tenants.md b/docs/userguide/Identity/Tenants.md index b30cb661d..ae9bcdcb0 100644 --- a/docs/userguide/Identity/Tenants.md +++ b/docs/userguide/Identity/Tenants.md @@ -1,21 +1,5 @@ # Tenants -## Intro +Our docs have moved! Please visit the below link: -A tenant is a container used to group or isolate resources and/or identity objects. Depending on the service operator, a tenant may map to a customer, account, organization, or project. - -## Setup - -Tenant objects are instantiated from the Identity service. For more details, see the [Service](Service.md) docs. - -## List tenants - -```php -$tenants = $service->getTenants(); - -foreach ($tenants as $tenant) { - // ... -} -``` - -For more information about how to use iterators, see the [documentation](../Iterators.md). \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/identity/tenants.html diff --git a/docs/userguide/Identity/Tokens.md b/docs/userguide/Identity/Tokens.md index 04a3ec327..a60c57ab5 100644 --- a/docs/userguide/Identity/Tokens.md +++ b/docs/userguide/Identity/Tokens.md @@ -1,84 +1,5 @@ # Tokens -## Intro +Our docs have moved! Please visit the below link: -A token is an opaque string that represents an authorization to access cloud resources. Tokens may be revoked at any time and are valid for a finite duration. - -## Setup - -Token objects are instantiated from the Identity service. For more details, see the [Service](Service.md) docs. - -## Useful object properties/methods - -Property|Description|Getter|Setter ----|---|---|--- -id|The unique ID of the token|`getId()`|`setId()` -expires|Timestamp of when the token will expire|`getExpires()` or `hasExpired()`|`setExpires()` - -## Create token (authenticate) - -In order to generate a token, you must pass in the JSON template that is sent to the API. This is because Rackspace's operation expects a slightly different entity body than OpenStack Keystone. - -Request body for Rackspace's generate token operation: - -```json -{ - "auth": { - "RAX-KSKEY:apiKeyCredentials": { - "username": "foo", - "apiKey": "aaaaa-bbbbb-ccccc-12345678" - }, - "tenantId": "1100111" - } -} -``` - -Request body for Keystone's generate token operation: - -```json -{ - "auth": { - "passwordCredentials":{ - "username":"demoauthor", - "password":"theUsersPassword" - }, - "tenantId": "12345678" - } -} -``` - -The only real differences you'll notice is the name of the object key (`RAX-KSKEY:apiKeyCredentials`/`passwordCredentials`) and the secret (`apiKey`/`password`). The `tenantId` property in both templates are optional. You can also add `tenantName` too. - -```php -use OpenCloud\Common\Http\Message\Formatter; - -$template = sprintf( - '{"auth": {"RAX-KSKEY:apiKeyCredentials":{"username": "%s", "apiKey": "%s"}}}', - 'my_username', - 'my_api_key' -); - -$response = $service->generateToken($template); - -$body = Formatter::decode($response); - -// service catalog -$catalog = $body->access->serviceCatalog; - -// token -$token = $body->access->token; - -// user -$user = $body->access->user; -``` - -As you will notice, these variables will be stdClass objects - for fully fledged functionality, let the client authenticate by itself because it ends up stocking the necessary models for you. - -To see the response body structure, consult the [official docs](http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/POST_authenticate_v2.0_tokens_Token_Calls.html). - -## Revoke token (destroy session) - -```php -$tokenId = '1234567'; -$service->revokeToken($tokenId); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/identity/tokens.html diff --git a/docs/userguide/Identity/Users.md b/docs/userguide/Identity/Users.md index 286aa6007..e387cbee5 100644 --- a/docs/userguide/Identity/Users.md +++ b/docs/userguide/Identity/Users.md @@ -1,128 +1,5 @@ # Users -## Intro +Our docs have moved! Please visit the below link: -A user is a digital representation of a person, system, or service who consumes cloud services. Users have credentials and may be assigned tokens; based on these credentials and tokens, the authentication service validates that incoming requests are being made by the user who claims to be making the request, and that the user has the right to access the requested resources. Users may be directly assigned to a particular tenant and behave as if they are contained within that tenant. - -## Setup - -User objects are instantiated from the Identity service. For more details, see the [Service](Service.md) docs. - -## Useful object properties/methods - -Property|Description|Getter|Setter ----|---|---|--- -id|The unique ID for this user|`getId()`|`setId()` -username|Username for this user|`getUsername()`|`setUsername()` -email|User's email address|`getEmail()`|`setEmail()` -enabled|Whether or not this user can consume API functionality|`getEnabled()` or `isEnabled()`|`setEnabled()` -password|Either a user-defined string, or an automatically generated one, that provides security when authenticating.|`getPassword()` only valid on creation|`setPassword()` to set local property only. To set password on API (retention), use `updatePassword()`. -defaultRegion|Default region associates a user with a specific regional datacenter. If a default region has been assigned for this user and that user has **NOT** explicitly specified a region when creating a service object, the user will obtain the service from the default region.|`getDefaultRegion()`|`setDefaultRegion()` -domainId|Domain ID associates a user with a specific domain which was assigned when the user was created or updated. A domain establishes an administrative boundary for a customer and a container for a customer's tenants (accounts) and users. Generally, a domainId is the same as the primary tenant id of your cloud account.|`getDomainId()`|`setDomainId()` - -## List users - -```php -$users = $service->getUsers(); - -foreach ($users as $user) { - // ... -} -``` - -For more information about how to use iterators, see the [documentation](../Iterators.md). - -## Get user - -There are various ways to get a specific user: by name, ID and email address. - -```php -use OpenCloud\Identity\Constants\User as UserConst; - -// Get user by name -$user1 = $service->getUser('jamie'); - -// Get user by ID -$user2 = $service->getUser(123456, UserConst::MODE_ID); - -// Get user by email -$user3 = $service->getUser('jamie.hannaford@rackspace.com', UserConst::MODE_EMAIL); -``` - -## Create user - -There are a few things to remember when creating a user: - -* This operation is available only to users who hold the `identity:user-admin` role. This admin can create a user who holds the `identity:default` user role. - -* The created user **will** have access to APIs but **will not** have access to the Cloud Control Panel. - -* Within an account, a maximum of 100 account users can be added. - -* If you attempt to add a user who already exists, an HTTP error 409 results. - -The `username` and `email` properties are required for creating a user. Providing a `password` is optional; if omitted, one will be automatically generated and provided in the response. - -```php -use Guzzle\Http\Exception\ClientErrorResponseException; - -try { - // execute operation - $user = $service->createUser(array( - 'username' => 'newUser', - 'email' => 'foo@bar.com' - )); -} catch (ClientErrorResponseException $e) { - // catch 4xx HTTP errors - echo $e->getResponse()->toString(); -} - -// show generated password -echo $user->getPassword(); -``` - -## Update user - -When updating a user, specify which attribute/property you want to update: - -```php -$user->update(array( - 'email' => 'new_email@bar.com' -)); -``` - -### Updating a user password - -Updating a user password requires calling a distinct method: -```php -$user->updatePassword('password123'); -``` - -## Delete user - -```php -$user->delete(); -``` - -## List credentials - -This operation allows you to see your non-password credential types for all authentication methods available. - -```php -$creds = $user->getOtherCredentials(); -``` - -## Get user API key - -```php -echo $user->getApiKey(); -``` - -## Reset user API key - -When resetting an API key, a new one will be automatically generated for you: - -```php -$user->resetApiKey(); -echo $user->getApiKey(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/identity/users.html diff --git a/docs/userguide/Image/Images.md b/docs/userguide/Image/Images.md index c0efee9a1..1f593f17a 100644 --- a/docs/userguide/Image/Images.md +++ b/docs/userguide/Image/Images.md @@ -1,97 +1,5 @@ # Images -A virtual machine image is a single file which contains a virtual disk that has -an installed bootable operating system. In the Cloud Images API, an image is -represented by a JSON-encoded data structure (the image schema) and its raw -binary data (the image file). +Our docs have moved! Please visit the below link: -An Image is represented by the `OpenCloud\Image\Resource\Image` class. - -## Setup - -You instantiate an Image object from its `OpenCloud\Image\Service` class, which -is available from the OpenStack/Rackspace client: - -```php -$service = $client->imageService('cloudImages', 'IAD'); -``` - -View the guides for more information about [clients](../Clients.md) or -[services](../Services.md). - -## List images - -```php -$images = $service->listImages(); - -foreach ($images as $image) { - /** @param $image OpenCloud\Image\Resource\Image */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](../Iterators.md). - -## Get image details - -```php -/** @param $image OpenCloud\Image\Resource\Image */ -$image = $service->getImage(''); -``` - -### A note on schema classes - -Both `OpenCloud\Image\Resource\Image` and `OpenCloud\Image\Resource\Member` -extend the `AbstractSchemaResource` abstract class, which offers some unique -functionality. - -Because these resources are inherently dynamic - i.e. they are modelled on -dynamic JSON schema - you need to access their state in a way different than -conventional getter/setter methods, and even class properties. For this reason, -they implement SPL's native -[`ArrayAccess`](http://www.php.net/manual/en/class.arrayaccess.php) -interface which allows you to access their state as a conventional array: - -```php -$image = $service->getImage(''); - -$id = $image['id']; -$tags = $image['tags']; -``` - -## Update image - -You can only update your own custom images - you cannot update or delete base -images. The way in which you may update your image is dictated by its -[schema](Schemas.md). - -Although you should be able to add new and replace existing properties, always -prepare yourself for a situation where it might be forbidden: - -```php -use OpenCloud\Common\Exceptions\ForbiddenOperationException; - -try { - $image->update(array( - 'name' => 'foo', - 'newProperty' => 'bar' - )); -} catch (ForbiddenOperationException $e) { - // A 403 Forbidden was returned -} -``` - -There are three operations that can take place for each Image property: - -* If a `false` or `null` value is provided, a `REMOVE` operation will occur, -removing the property from the JSON document -* If a non-false value is provided and the property does not exist, an `ADD` -operation will add it to the document -* If a non-false value is provided and the property does exist, a `REPLACE` -operation will modify the property in the document - -## Delete image - -```php -$image->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/image/images.html diff --git a/docs/userguide/Image/Schemas.md b/docs/userguide/Image/Schemas.md index b634b5705..b37222b84 100644 --- a/docs/userguide/Image/Schemas.md +++ b/docs/userguide/Image/Schemas.md @@ -1,159 +1,5 @@ # JSON schemas -The Cloud Images API supplies json documents describing the JSON-encoded data -structures that represent domain objects, so that a client knows exactly what -to expect in an API response. +Our docs have moved! Please visit the below link: -A JSON Schema is represented by the `OpenCloud\Image\Resource\Schema\Schema` -class. - -## Schema types - -There are currently four types of schema: Images schema, Image schema, Members -schema, and Member schema. - -## Example response from the API - -A sample response from the API, for an Images schema might be: - -```json -{ - "name": "images", - "properties": { - "images": { - "items": { - "type": "array", - "name": "image", - "properties": { - "id": {"type": "string"}, - "name": {"type": "string"}, - "visibility": {"enum": ["public", "private"]}, - "status": {"type": "string"}, - "protected": {"type": "boolean"}, - "tags": { - "type": "array", - "items": {"type": "string"} - }, - "checksum": {"type": "string"}, - "size": {"type": "integer"}, - "created_at": {"type": "string"}, - "updated_at": {"type": "string"}, - "file": {"type": "string"}, - "self": {"type": "string"}, - "schema": {"type": "string"} - }, - "additionalProperties": {"type": "string"}, - "links": [ - {"href": "{self}", "rel": "self"}, - {"href": "{file}", "rel": "enclosure"}, - {"href": "{schema}", "rel": "describedby"} - ] - } - }, - "schema": {"type": "string"}, - "next": {"type": "string"}, - "first": {"type": "string"} - }, - "links": [ - {"href": "{first}", "rel": "first"}, - {"href": "{next}", "rel": "next"}, - {"href": "{schema}", "rel": "describedby"} - ] -} -``` - -The top-level schema is called `images`, and contains an array of links and -a properties object. Inside this properties object we see the structure of this -top-level `images ` object. So we know that it will take this form: - -```json -{ - "images": [something...] -} -``` - -Within this object, we can see that it contains an array of anonymous objects, -each of which is called `image` and has its own set of nested properties: - -```json -{ - "images": [ - { - [object 1...] - }, - { - [object 2...] - }, - { - [object 3...] - } - ] -} -``` - -The structure of these nested objects are defined as another schema - i.e. a -*subschema*. We know that each object has an ID property (string), a name -property (string), a visibility property (can either be `private` or `public`), etc. - -```json -{ - "images": [ - { - "id": "foo", - "name": "bar", - "visibility": "private", - // etc. - }, - { - "id": "foo", - "name": "bar", - "visibility": "private", - // etc. - }, - { - "id": "foo", - "name": "bar", - "visibility": "private", - // etc. - } - ] -} -``` - -Each nested property of a schema is represented by the -`OpenCloud\Image\Resource\Schema\Property` class. - -If you would like to find out more about schemas, Guzzle has good documentation -about [service descriptions](http://docs.guzzlephp.org/en/latest/webservice-client/guzzle-service-descriptions.html), -which is fairly analogous. - -## JSON Patch - -The Glance API has a unique way of updating certain dynamic resources: they use -JSON Patch method, as outlined in [RFC 6902](http://tools.ietf.org/html/rfc6902). - -Requests need to use the `application/openstack-images-v2.1-json-patch` -content-type. - -In order for the operation to occur, the request entity body needs to contain a -very particular structure: - -``` -[ - {"op": "replace", "path": "/name", "value": "Fedora 17"}, - {"op": "replace", "path": "/tags", "value": ["fedora", "beefy"]} -] -``` - -The `op` key refers to the type of Operation (see -`OpenCloud\Image\Enum\OperationType` for a full list). - -The `path` key is a JSON pointer to the document property you want to modify or -insert. JSON pointers are defined in [RFC 6901](http://tools.ietf.org/html/rfc6901). - -The `value` key is the value. - -Because this is all handled for you behind the scenes, we will not go into exhaustive depth -about how this operation is handled. You can browse the source code, consult -the various RFCs and the [official documentation](http://docs.rackspace.com/images/api/v2/ci-devguide/content/patch-method.html) -for additional information. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/image/schemas.html diff --git a/docs/userguide/Image/Sharing.md b/docs/userguide/Image/Sharing.md index e83470073..91515b9fa 100644 --- a/docs/userguide/Image/Sharing.md +++ b/docs/userguide/Image/Sharing.md @@ -1,110 +1,5 @@ # Sharing images -Images can be created and deleted by image producers, updated by image -consumers, and listed by both image producers and image consumers: +Our docs have moved! Please visit the below link: -Operation|Producer can?|Consumer can? ----|---|--- -Created|Yes|No -Deleted|Yes|No -Updated|No|Yes -Listed|Yes|Yes - -The producer shares an image with the consumer by making the consumer a *member* -of that image. The consumer then accepts or rejects the image by changing the -member status. Once accepted, the image appears in the consumer's image list. - -## Typical workflow - -1. The producer posts the availability of specific images on a public website. - -2. A potential consumer provides the producer with his/her tenant ID and email -address. - -3. The producer [creates a new Image Member]() with the consumer's details - -4. The producer notifies the consumer via email that the image has been shared -and provides the image's ID. - -5. If the consumer wishes the image to appear in his/her image list, the -consumer [updates their own Member status]() to `ACCEPTED`. - -### Additional notes - -* If the consumer subsequently wishes to hide the image, the consumer can change -their Member status to `REJECTED`. - -* If the consumer wishes to hide the image, but is open to the possibility of -being reminded by the producer that the image is available, the consumer can -change their Member status to `PENDING`. - -* Image producers add or remove image members, but may not modify the member -status of an image member. - -* Image consumers change their own member status, but may not add or remove -themselves as an image member. - -* Image consumers can boot from any image shared by the image producer, -regardless of the member status, as long as the image consumer knows the image ID. - -## Setup - -All member operations are executed against an [Image](Images.md), so you will -need to set this up first. - -## List image members - -This operation is available for both producers and consumers. - -```php -$members = $image->listMembers(); - -foreach ($members as $member) { - /** @param $member OpenCloud\Image\Resource\Member */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](../Iterators.md). - -## Create image member - -This operation is only available for producers. - -```php -$tenantId = 12345; - -/** @param $response Guzzle\Http\Message\Response */ -$response = $image->createMember($tenantId); -``` - -## Delete image member - -This operation is only available for producers. - -```php -$tenantId = 12345; - -/** @param $member OpenCloud\Image\Resource\Member */ -$member = $image->getMember($tenantId); - -$member->delete(); -``` - -## Update image member status - -This operation is only available for consumers. - -```php -use OpenCloud\Images\Enum\MemberStatus; - -$tenantId = 12345; - -/** @param $member OpenCloud\Image\Resource\Member */ -$member = $image->getMember($tenantId); - -$member->updateStatus(MemberStatus::ACCEPTED); -``` - -The acceptable states you may pass in are made available to you through the -constants defined in the `OpenCloud\Images\Enum\MemberStatus` class. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/image/sharing.html diff --git a/docs/userguide/Image/Tags.md b/docs/userguide/Image/Tags.md index 019e336e5..fc8bcd8aa 100644 --- a/docs/userguide/Image/Tags.md +++ b/docs/userguide/Image/Tags.md @@ -1,23 +1,5 @@ # Image tags -An image tag is a string of characters used to identify a specific image or -images. +Our docs have moved! Please visit the below link: -## Setup - -All member operations are executed against an [Image](Images.md), so you will -need to set this up first. - -## Add image tag - -```php -/** @param $response Guzzle\Http\Message\Response */ -$response = $image->addTag('jamie_dev'); -``` - -## Delete image tag - -```php -/** @param $response Guzzle\Http\Message\Response */ -$response = $image->deleteTag('jamie_dev'); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/image/tags.html diff --git a/docs/userguide/Iterators.md b/docs/userguide/Iterators.md index 553507937..114982668 100644 --- a/docs/userguide/Iterators.md +++ b/docs/userguide/Iterators.md @@ -1,118 +1,5 @@ # Iterators -## Intro +Our docs have moved! Please visit the below link: -Iterators allow you to traverse over collections of your resources in an efficient and easy way. Currently there are two Iterators provided by the SDK: - -- **ResourceIterator**. The standard iterator class that implements SPL's standard [Iterator](http://php.net/manual/en/class.iterator.php), [ArrayAccess](http://www.php.net/manual/en/class.arrayaccess.php) and [Countable](http://php.net/manual/en/class.countable.php) interfaces. In short, this allows you to traverse this object (using `foreach`), count its internal elements like an array (using `count` or `sizeof`), and access its internal elements like an array (using `$iterator[1]`). - - -- **PaginatedIterator**. This is a child of ResourceIterator, and as such inherits all of its functionality. The difference however is that when it reaches the end of the current collection, it attempts to construct a URL to access the API based on predictive paginated collection templates. - -## Common behaviour - -```php -$iterator = $computeService->flavorList(); -``` - -There are two ways to traverse an iterator. The first is the longer, more traditional way: - -```php -while ($iterator->valid()) { - $flavor = $iterator->current(); - - // do stuff.. - echo $flavor->id; - - $iterator->next(); -} -``` - -There is also a shorter and more intuitive version: - -```php -foreach ($iterator as $flavor) { - // do stuff... - echo $flavor->id; -} -``` - -Because the iterator implements PHP's native `Iterator` interface, it can inherit all the native functionality of traversible data structures with `foreach`. - -## Very important note - -Until now, users have been expected to do this: - -```php -while ($flavor = $iterator->next()) { - // ... -} -``` - -which is **incorrect**. The single responsibility of `next` is to move the internal pointer forward. It is the job of `current` to retrieve the current element. - -For your convenience, these two Iterator classes are fully backward compatible: they exhibit all the functionality you'd expect from a correctly implemented iterator, but they also allow previous behaviour. - -## Using paginated collections - -For large collections, such as retrieving DataObjects from CloudFiles/Swift, you need to use pagination. Each resource will have a different limit per page; so once that page is traversed, there needs to be another API call to retrieve to *next* page's resources. - -There are two key concepts: - -- **limit** is the amount of resources returned per page -- **marker** is the way you define a starting point. It is some form of identifier that allows the collection to begin from a specific resource - -### Resource classes - -When the iterator returns a current element in the internal list, it populates the relevant resource class with all the data returned to the API. In most cases, a `stdClass` object will become an instance of `OpenCloud\Common\PersistentObject`. - -In order for this instantiation to happen, the `resourceClass` option must correspond to some method in the parent class that creates the resource. For example, if we specify 'ScalingPolicy' as the `resourceClass`, the parent object (in this case `OpenCloud\Autoscale\Group`, needs to have some method will allows the iterator to instantiate the child resource class. These are all valid: - -1. `Group::scalingGroup($data);` - -2. `Group::getScalingGroup($data);` - -3. `Group::resource('ScalingGroup', $data);` - -where `$data` is the standard object. This list runs in order of precedence. - -## Setting up a PaginatedIterator - -```php -use OpenCloud\Common\Collection\PaginatedIterator; - -$service = $client->computeService(); - -$flavors = PaginatedIterator::factory($service, array( - 'resourceClass' => 'Flavor', - 'baseUrl' => $service->getUrl('flavors') - 'limit.total' => 350, - 'limit.page' => 100, - 'key.collection' => 'flavors' -)); - -foreach ($flavors as $flavor) { - echo $flavor->getId(); -} -``` - -As you can see, there are a lot of configuration parameters to pass in - and getting it right can be quite fiddly, involving a lot of API research. For this reason, using the convenience methods like `flavorList` is recommended because it hides the complexity. - -### PaginatedIterator options - -There are certain configuration options that the paginated iterator needs to work. These are: - -Name|Description|Type|Required|Default| ----|---|---|---|---| -resourceClass|The resource class that is instantiated when the current element is retrieved. This is relative to the parent/service which called the iterator.|string|Yes|- -baseUrl|The base URL that is used for making new calls to the API for new pages|`Guzzle\Http\Url`|Yes|- -limit.total|The total amount of resources you want to traverse in your collection. The iterator will stop as this limit is reached, regardless if there are more items in the list|int|No|10000 -limit.page|The amount of resources each page contains|int|No|100 -key.links|Often, API responses will contain "links" that allow easy access to the next page of a resource collection. This option specifies what that JSON element is called (its key). For example, for Rackspace Compute images it is `images_links`.|string|No|links -key.collection|The top-level key for the array of resources. For example, servers are returned with this data structure: `{"servers": [...]}`. The **key.collection** value in this case would be `servers`.|string|No|`null` -key.collectionElement|Rarely used. But it indicates the key name for each nested resource element. KeyPairs, for example, are listed like this: `{"keypairs": [ {"keypair": {...}} ] }`. So in this case the collectionElement key would be `keypair`.|string|No|`null` -key.marker|The value used as the marker. It needs to represent a valid property in the JSON resource objects. Often it is `id` or `name`.|string|No|name -request.method|The HTTP method used when making API calls for new pages|string|No|GET -request.headers|The HTTP headers to send when making API calls for new pages|array|No|`array()` -request.body|The HTTP entity body to send when making API calls for new pages|`Guzzle\Http\EntityBody`|No|`null` -request.curlOptions|Additional cURL options to use when making API calls for new pages|array|No|`array()` +https://doc.php-opencloud.com/en/latest/iterators.html diff --git a/docs/userguide/LoadBalancer/README.md b/docs/userguide/LoadBalancer/README.md index 03364f103..34008ab6c 100644 --- a/docs/userguide/LoadBalancer/README.md +++ b/docs/userguide/LoadBalancer/README.md @@ -1,80 +1,5 @@ # Load Balancers -A **load balancer** is a device that distributes incoming network traffic amongst -multiple back-end systems. These back-end systems are called the **nodes** of -the load balancer. +Our docs have moved! Please visit the below link: -## Getting started - -### 1. Instantiate a Rackspace client. - -```php - -use OpenCloud\Rackspace; - -$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' -)); -``` - -### 2. Retrieve the server instances you want to add as nodes of the load balancer. - -```php -$computeService = $client->computeService('cloudServersOpenStack', 'DFW'); - -$serverOne = $computeService->server('e836fc4e-056d-4447-a80e-fefcaa640216'); -$serverTwo = $computeService->server('5399cd36-a23f-41a6-bdf7-20902aec0e74'); -``` - -The example above uses two server instances that have already been created. It -retrieves the server instances using their IDs. See also: [creating server instances](). - -### 3. Obtain a Load Balancer service object from the client. - -This object will be used to first define the load balancer nodes and later create the load balancer itself. - -```php -$loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); -``` - -### 4. Define a load balancer node for each server. - -```php -$loadBalancer = $loadBalancerService->loadBalancer(); - -$serverOneNode = $loadBalancer->node(); -$serverOneNode->address = $serverOne->addresses->private[0]->addr; -$serverOneNode->port = 8080; -$serverOneNode->condition = 'ENABLED'; - -$serverTwoNode = $loadBalancer->node(); -$serverTwoNode->address = $serverTwo->addresses->private[0]->addr; -$serverTwoNode->port = 8080; -$serverTwoNode->condition = 'ENABLED'; -``` - -In the example above, each node runs a service that listens on port 8080. Further, -each node will start out as `ENABLED`, which means it will be ready to receive -network traffic from the load balancer as soon as it is created. - -### 5. Create the load balancer with the two nodes. - -```php -$loadBalancer->addVirtualIp('PUBLIC'); -$loadBalancer->create(array( - 'name' => 'My smart load balancer', - 'port' => 80, - 'protocol' => 'HTTP', - 'nodes' => array($serverOneNode, $serverTwoNode) -)); -``` - -In the example above, the load balancer will have a virtual IP address accessible -from the public Internet. Also notice that the port the load balancer listens -on (80) does not need to match the ports of its nodes (8080). - -## Next steps - -Once you have created a load balancer, there is a lot you can do with it. See -the [complete user guide for load balancers](USERGUIDE.md). \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/load-balancer/index.html diff --git a/docs/userguide/LoadBalancer/USERGUIDE.md b/docs/userguide/LoadBalancer/USERGUIDE.md index 0c15f0b29..0a5c3b15d 100644 --- a/docs/userguide/LoadBalancer/USERGUIDE.md +++ b/docs/userguide/LoadBalancer/USERGUIDE.md @@ -1,626 +1,5 @@ # The Complete User Guide to Load Balancers -## Prerequisites +Our docs have moved! Please visit the below link: -### Client -To use the load balancers service, you must first instantiate a `Rackspace` -client object. - -```php -use OpenCloud\Rackspace; - -$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' -)); -``` - -### Load Balancer Service -All operations on load balancers are done via a load balancer service object. - -```php -$loadBalancerService = $client->loadBalancerService('cloudLoadBalancers', 'DFW'); -``` - -### Cloud Servers -Many of the examples in this document use two cloud servers as nodes for -the load balancer. The variables `$serverOne` and `$serverTwo` refer to these -two cloud servers. - -## Load Balancers - -A **load balancer** is a device that distributes incoming network traffic amongst -multiple back-end systems. These back-end systems are called the **nodes** of -the load balancer. - -### Create Load Balancer - -```php -$loadBalancer = $loadBalancerService->loadBalancer(); - -$serverOneNode = $loadBalancer->node(); -$serverOneNode->address = $serverOne->addresses->private[0]->addr; -$serverOneNode->port = 8080; -$serverOneNode->condition = 'ENABLED'; - -$serverTwoNode = $loadBalancer->node(); -$serverTwoNode->address = $serverTwo->addresses->private[0]->addr; -$serverTwoNode->port = 8080; -$serverTwoNode->condition = 'ENABLED'; - -$loadBalancer->addVirtualIp('PUBLIC'); -$loadBalancer->create(array( - 'name' => 'My smart load balancer', - 'port' => 80, - 'protocol' => 'HTTP', - 'nodes' => array($serverOneNode, $serverTwoNode) -)); -``` - -### List Load Balancer Details - -You can retrieve a single load balancer's details by using its ID. - -```php -$loadBalancer = $loadBalancerService->loadBalancer('254889'); - -/** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ -``` - -### List Load Balancers - -You can retrieve a list of all your load balancers. An instance of `OpenCloud\Common\Collection\PaginatedIterator` -is returned. - -```php -$loadBalancers = $loadBalancerService->loadBalancerList(); -foreach ($loadBalancers as $loadBalancer) { - /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ -} -``` - -### Update Load Balancer Attributes - -You can update one or more of the following load balancer attributes: - -* `name`: The name of the load balancer -* `algorithm`: The algorithm used by the load balancer to distribute traffic amongst its nodes. See also: [Load balancing algorithms](#algorithms). -* `protocol`: The network protocol used by traffic coming in to the load balancer. See also: [Protocols](#protocols). -* `port`: The network port on which the load balancer listens for incoming traffic. -* `halfClosed`: Enable or Disable Half-Closed support for the load balancer. -* `timeout`: The timeout value for the load balancer to communicate with its nodes. -* `httpsRedirect`: Enable or disable HTTP to HTTPS redirection for the load balancer. When enabled, any HTTP request will return status code 301 (Moved Permanently), and the requestor will be redirected to the requested URL via the HTTPS protocol on port 443. For example, http://example.com/page.html would be redirected to https:// example.com/page.html. Only available for HTTPS protocol (`port` = 443), or HTTP Protocol with a properly configured SSL Termination (`secureTrafficOnly=true, securePort=443). See also: [SSL Termination](#ssl-termination). - -#### Updating a single attribute of a load balancer -```php -$loadBalancer->update(array( - 'name' => 'New name' -)); -``` - -#### Updating multiple attributes of a load balancer -```php -$loadBalancer->update(array( - 'name' => 'New name', - 'algorithm' => 'ROUND_ROBIN' -)); -``` - -### Remove Load Balancer - -When you no longer have a need for the load balancer, you can remove it. - -```php -$loadBalancer->delete(); -``` - -## Nodes - -A **node** is a backend device that provides a service on specified IP and port. An example of a load balancer node might be a web server serving HTTP traffic on port 8080. - -A load balancer typically has multiple nodes attached to it so it can distribute incoming network traffic amongst them. - -### List Nodes - -You can list the nodes attached to a load balancer. An instance of `OpenCloud\Common\Collection\PaginatedIterator` -is returned. - -```php -$nodes = $loadBalancer->nodeList(); -foreach ($nodes as $node) { - /** @var $node OpenCloud\LoadBalancer\Resource\Node **/ -} -``` - -### Add Nodes - -You can attach additional nodes to a load balancer. Assume `$loadBalancer` already has two nodes attached to it - `$serverOne` and `$serverTwo` - and you want to attach a third node to it, say `$serverThree`, which provides a service on port 8080. - -**Important:** Remember to call `$loadBalancer->addNodes()` after all the calls to `$loadBalancer->addNode()` as shown below. - -```php -$address = $serverThree->addresses->private[0]->addr; -$loadBalancer->addNode($address, 8080); -$loadBalancer->addNodes(); -``` - -The `addNode` method accepts three more optional parameters, in addition to the two shown above: - -| Position | Description | Data type | Required? | Default value | -| ----------- | --------------- | --------------| -------------- | ----------------- | -| 1 | IP address of node | String | Yes | - | -| 2 | Port used by node's service | Integer | Yes | - | -| 3 | Starting condition of node:
  • `ENABLED` – Node is ready to receive traffic from the load balancer.
  • `DISABLED` – Node should not receive traffic from the load balancer.
  • `DRAINING` – Node should process any traffic it is already receiving but should not receive any further traffic from the load balancer.
| String | No | `ENABLED` | -| 4 | Type of node to add:
  • `PRIMARY` – Nodes defined as PRIMARY are in the normal rotation to receive traffic from the load balancer.
  • `SECONDARY` – Nodes defined as SECONDARY are only in the rotation to receive traffic from the load balancer when all the primary nodes fail.
| String | No | `PRIMARY` | -| 5 | Weight, between 1 and 100, given to node when distributing traffic using either the `WEIGHTED_ROUND_ROBIN` or the `WEIGHTED_LEAST_CONNECTIONS` load balancing algorithm. | Integer | No | 1 | - -### Modify Nodes -You can modify one or more of the following node attributes: - -* `condition`: The condition of the load balancer: - * `ENABLED` – Node is ready to receive traffic from the load balancer. - * `DISABLED` – Node should not receive traffic from the load balancer. - * `DRAINING` – Node should process any traffic it is already receiving but should not receive any further traffic from the load balancer. -* `type`: The type of the node: - * `PRIMARY` – Nodes defined as PRIMARY are in the normal rotation to receive traffic from the load balancer. - * `SECONDARY` – Nodes defined as SECONDARY are only in the rotation to receive traffic from the load balancer when all the primary nodes fail. -* `weight`: The weight, between 1 and 100, given to node when distributing traffic using either the `WEIGHTED_ROUND_ROBIN` or the `WEIGHTED_LEAST_CONNECTIONS` load balancing algorithm. - -#### Modifying a single attribute of a node -```php -use OpenCloud\LoadBalancer\Enum\NodeCondition; - -$node->update(array( - 'condition' => NodeCondition::DISABLED -)); -``` - -#### Modifying multiple attributes of a node -```php -use OpenCloud\LoadBalancer\Enum\NodeCondition; -use OpenCloud\LoadBalancer\Enum\NodeType; - -$node->update(array( - 'condition' => NodeCondition::DISABLED, - 'type' => NodeType::SECONDARY -)); -``` - -### Remove Nodes - -There are two ways to remove a node. - -#### Given an `OpenCloud\LoadBalancer\Resource\Node` instance -```php -$node->delete(); -``` - -#### Given an `OpenCloud\LoadBalancer\Resource\LoadBalancer` instance and a node ID -```php -$loadBalancer->removeNode(490639); -``` - -The `removeNode` method, as shown above, accepts the following arguments: - -|Position| Description | Data type | Required? | Default value | -|----------- | --------------- | -------------- |-------------- | ----------------- | -| 1 | ID of node | Integer | Yes | - | - -### View Node Service Events -You can view events associated with the activity between a node and a load balancer. An instance of `OpenCloud\Common\Collection\PaginatedIterator` is returned. - -```php -$nodeEvents = $loadBalancer->nodeEventList(); -foreach ($nodeEvents as $nodeEvent) { - /** @var $nodeEvent OpenCloud\LoadBalancer\Resource\NodeEvent **/ -} -``` - -## Virtual IPs - -A **virtual IP (VIP)** makes a load balancer accessible by clients. The load balancing service supports either a public VIP address (`PUBLIC`), routable on the public Internet, or a ServiceNet VIP address (`SERVICENET`), routable only within the region in which the load balancer resides. - -### List Virtual IPs - -You can list the VIPs associated with a load balancer. An instance of `OpenCloud\Common\Collection\PaginatedIterator` is returned. - -```php -$vips = $loadBalancer->virtualIpList(); -foreach ($vips as $vip) { - /** @var $vip of OpenCloud\LoadBalancer\Resource\VirtualIp **/ -} -``` - -### Add Virtual IPv6 - -You can add additional IPv6 VIPs to a load balancer. - -```php -use OpenCloud\LoadBalancer\Enum\IpType; - -$loadBalancer->addVirtualIp(IpType::PUBLIC, 6); -``` - -The `addVirtualIp` method, as shown above, accepts the following arguments: - -| Position | Description | Data type | Required? | Default value | -| ----------- | --------------- | -------------- |-------------- | ----------------- | -| 1 | Type of VIP:
  • `PUBLIC` – An IP address that is routable on the public Internet.
  • `SERVICENET` – An IP address that is routable only on ServiceNet.
| String | No | `PUBLIC` | -| 2 | IP version: Must be `6` | Integer | Yes | - | - - -### Remove Virtual IPs - -You can remove a VIP from a load balancer. - -```php -$vip->remove(); -``` - -Please note that a load balancer must have at least one VIP associated with it. If you try to remove a load balancer's last VIP, a `ClientErrorResponseException` will be thrown. - -## Algorithms - -Load balancers use an **algorithm** to determine how incoming traffic is distributed amongst the back-end nodes. - -### List Load Balancing Algorithms - -You can list all supported load balancing algorithms using a load balancer service object. An instance of `OpenCloud\Common\Collection\PaginatedIterator` is returned. - -```php -$algorithms = $loadBalancerService->algorithmList(); -foreach ($algorithms as $algorithm) { - /** @var $algorithm OpenCloud\LoadBalancer\Resource\Algorithm **/ -} -``` - -## Protocols - -When a load balancer is created a network protocol must be specified. This network protocol should be based on the network protocol of the back-end service being load balanced. - -### List Load Balancing Protocols - -You can list all supported network protocols using a load balancer service object. An instance of `OpenCloud\Common\Collection\PaginatedIterator` is returned. - -```php -$protocols = $loadBalancerService->protocolList(); -foreach ($protocols as $protocol) { - /** @var $protocol OpenCloud\LoadBalancer\Resource\Protocol **/ -} -``` - -## Session Persistence - -**Session persistence** is a feature of the load balancing service that forces multiple requests, of the same protocol, from clients to be directed to the same node. This is common with many web applications that do not inherently share application state between back-end servers. - -There are two types (or modes) of session persistence: - -| Name | Description | -| -------- | --------------- | -| `HTTP_COOKIE` | A session persistence mechanism that inserts an HTTP cookie and is used to determine the destination back-end node. This is supported for HTTP load balancing only. | -| `SOURCE_IP` | A session persistence mechanism that will keep track of the source IP address that is mapped and is able to determine the destination back-end node. This is supported for HTTPS pass-through and non-HTTP load balancing only. | - -### List Session Persistence Configuration - -```php -$sessionPersistence = $loadBalancer->sessionPersistence(); -$sessionPersistenceType = $sessionPersistence->persistenceType; - -/** @var $sessionPersistenceType null | 'HTTP_COOKIE' | 'SOURCE_IP' **/ -``` - -In the example above: - -* If session persistence is enabled, the value of `$sessionPersistenceType` is the type of session persistence: either `HTTP_COOKIE` or `SOURCE_IP`. -* If session persistence is disabled, the value of `$sessionPersistenceType` is `null`. - -### Enable Session Persistence - -```php -$sessionPersistence = $loadBalancer->sessionPersistence(); -$sessionPersistence->update(array( - 'persistenceType' => 'HTTP_COOKIE' -)); -``` - -### Disable Session Persistence - -```php -$sessionPersistence = $loadBalancer->sessionPersistence(); -$sessionPersistence->delete(); -``` - -## Connection Logging - -The **connection logging** feature allows logs to be delivered to a Cloud Files account every hour. For HTTP-based protocol traffic, these are Apache-style access logs. For all other traffic, this is connection and transfer logging. - -### Check Logging Configuration - -```php -/** @var $connectionLogging bool **/ - -$connectionLogging = $loadBalancer->hasConnectionLogging(); -``` -In the example above: - -* If connection logging is enabled, the value of `$connectionLogging` is `true`. -* If connection logging is disabled, the value of `$connectionLogging` is `false`. - -### Enable Connection Logging - -```php -$loadBalancer->enableConnectionLogging(true); -``` - -### Disable Connection Logging - -```php -$loadBalancer->enableConnectionLogging(false); -``` - -## Error Page - -An **error page** is the html file that is shown to the end user when an error in the service has been thrown. By default every virtual server is provided with the default error file. It is also possible to set a custom error page for a load balancer. - -### View Error Page Content - -```php -$errorPage = $loadBalancer->errorPage(); -$errorPageContent = $errorPage->content; - -/** @var $errorPageContent string **/ -``` - -In the example above the value of `$errorPageContent` is the HTML for that page. This could either be the HTML of the default error page or of your custom error page. - -### Set Custom Error Page - -```php -$errorPage = $loadBalancer->errorPage(); -$errorPage->update(array( - 'content' => '' -)); -``` - -### Delete Custom Error Page - -```php -$errorPage = $loadBalancer->errorPage(); -$errorPage->delete(); -``` - -## Allowed Domains - -**Allowed domains** are a restricted set of domain names that are allowed to add load balancer nodes. - -### List Allowed Domains - -You can list all allowed domains using a load balancer service object. An instance of `OpenCloud\Common\Collection\PaginatedIterator` -is returned. - -```php -$allowedDomains = $loadBalancerService->allowedDomainList(); -foreach ($allowedDomains as $allowedDomain) { - /** @var $allowedDomain OpenCloud\LoadBalancer\Resource\AllowedDomain **/ -} -``` - -## Access Lists - -**Access Lists** allow fine-grained network access to a load balancer's VIP. Using access lists, network traffic to a load balancer's VIP can be allowed or denied from a single IP address, multiple IP addresses or entire network subnets. - -Note that `ALLOW` network items will take precedence over `DENY` network items in an access list. - -To reject traffic from all network items except those with the `ALLOW` type, add a `DENY` network item with the address of `0.0.0.0/0`. - -### View Access List - -You can view a load balancer's access list. An instance of `OpenCloud\Common\Collection\PaginatedIterator` -is returned. - -```php -$accessList = $loadBalancer->accessList(); -foreach ($accessList as $networkItem) { - /** @var $networkItem OpenCloud\LoadBalancer\Resource\Access **/ -} -``` - -### Add Network Items To Access List - -You can add network items to a load balancer's access list very easily: - -```php -$loadBalancer->createAccessList(array( - (object) array( - 'type' => 'ALLOW', - 'address' => '206.160.165.1/24' - ), - (object) array( - 'type' => 'DENY', - 'address' => '0.0.0.0/0' - ) -)); -``` - -In the above example, we allowed access for 1 IP address, and used the "0.0.0.0" - wildcard to blacklist all other traffic. - -### Remove Network Item From Access List - -You an remove a network item from a load balancer's access list. - -```php -$networkItem->delete(); -``` - -## Content Caching - -When **content caching** is enabled on a load balancer, recently-accessed files are stored on the load balancer for easy retrieval by web clients. Requests to the load balancer for these files are serviced by the load balancer itself, which reduces load off its back-end nodes and improves response times as well. - -### Check Content Caching Configuration - -```php -/** @var $contentCaching bool **/ - -$contentCaching = $loadBalancer->hasContentCaching(); -``` -In the example above: - -* If content caching is enabled, the value of `$contentCaching` is `true`. -* If content caching is disabled, the value of `$contentCaching` is `false`. - -### Enable Content Caching - -```php -$loadBalancer->enableContentCaching(true); -``` - -### Disable Content Caching - -```php -$loadBalancer->enableContentCaching(false); -``` - -## SSL Termination - -The SSL Termination feature allows a load balancer user to terminate SSL traffic at the load balancer layer versus at the web server layer. A user may choose to configure SSL Termination using a key and an SSL certificate or an (Intermediate) SSL certificate. - -When SSL Termination is configured on a load balancer, a secure shadow server is created that listens only for secure traffic on a user-specified port. This shadow server is only visible to and manageable by the system. Existing or updated attributes on a load balancer with SSL Termination will also apply to its shadow server. For example, if Connection Logging is enabled on an SSL load balancer, it will also be enabled on the shadow server and Cloud Files logs will contain log files for both. - -### View current SSL termination config - -```php -/** @var $sslConfig OpenCloud\LoadBalancer\Resource\SSLTermination **/ - -$sslConfig = $loadBalancer->SSLTermination(); -``` - -### Update SSL termination config - -```php -$sslConfig->update(array( - 'enabled' => true, - 'securePort' => 443, - 'privateKey' => $key, - 'certificate' => $cert -)); -``` - -For a full list, with explanations, of required and optional attributes, please consult the [official documentation](http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguide/content/SSLTermination-d1e2479.html) - -### Delete SSL termination config - -```php -$sslConfig->delete(); -``` - -## Metadata - -Metadata can be associated with each load balancer and each node for the client's personal use. It is defined using key-value pairs where the key and value consist of alphanumeric characters. A key is unique per load balancer. - -### List metadata - -```php -$metadataList = $loadBalancer->metadataList(); - -foreach ($metadataList as $metadataItem) { - printf("Key: %s, Value: %s", $metadataItem->key, $metadataItem->value); -} -``` - -Please consult the [iterator documentation](docs/userguide/Iterators.md) for more information about iterators. - -### Add metadata - -```php -$metadataItem = $loadBalancer->metadata(); -$metadataItem->create(array( - 'key' => 'foo', - 'value' => 'bar' -)); -``` - -### Modify metadata - -```php -$metadataItem = $loadBalancer->metadata('foo'); -$metadataItem->update(array( - 'value' => 'baz' -)); -``` - -### Remove metadata - -```php -$metadataItem->delete(); -``` - -## Monitors - -The load balancing service includes a health monitoring operation which periodically checks your back-end nodes to ensure they are responding correctly. If a node is not responding, it is removed from rotation until the health monitor determines that the node is functional. In addition to being performed periodically, the health check also is performed against every node that is added to ensure that the node is operating properly before allowing it to service traffic. Only one health monitor is allowed to be enabled on a load balancer at a time. - -```php -/** @var $healthMonitor OpenCloud\LoadBalancer\Resource\HealthMonitor **/ - -$healthMonitor = $loadBalancer->healthMonitor(); - -printf( - "Monitoring type: %s, delay: %s, timeout: %s, attempts before deactivation: %s", - $healthMonitor->type, $healthMonitor->delay, $healthMonitor->timeout -); -``` - -For a full list, with explanations, of required and optional attributes, please consult the [official documentation](http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguide/content/Monitor_Connections-d1e3536.html) - -### Update or delete - -```php -// Update -$healthMonitor->update(array( - 'delay' => 120, - 'timeout' => 60, - 'type' => 'CONNECT' - 'attemptsBeforeDeactivation' => 3 -)); - -// Delete -$healthMonitor->delete(); -``` - -## Statistics - -You can retrieve detailed stats about your load balancer, including the following information: - -- `connectTimeOut` – Connections closed by this load balancer because the 'connect_timeout' interval was exceeded. -- `connectError` – Number of transaction or protocol errors in this load balancer. -- `connectFailure` – Number of connection failures in this load balancer. -- `dataTimedOut` – Connections closed by this load balancer because the 'timeout' interval was exceeded. -- `keepAliveTimedOut` – Connections closed by this load balancer because the 'keepalive_timeout' interval was exceeded. -- `maxConn` – Maximum number of simultaneous TCP connections this load balancer has processed at any one time. - -```php -/** @var $stats OpenCloud\LoadBalancer\Resource\Stats **/ - -$stats = $loadBalancer->stats(); -``` - -## Usage Reports - -The load balancer usage reports provide a view of all transfer activity, average number of connections, and number of virtual IPs associated with the load balancing service. Current usage represents all usage recorded within the preceding 24 hours. Values for both incomingTransfer and outgoingTransfer are expressed in bytes transferred. - -The optional startTime and endTime parameters can be used to filter all usage. If the startTime parameter is supplied but the endTime parameter is not, then all usage beginning with the startTime will be provided. Likewise, if the endTime parameter is supplied but the startTime parameter is not, then all usage will be returned up to the endTime specified. - -```php -# View billable LBs -$billable = $service->billableLoadBalancerList(); - -foreach ($billable as $loadBalancer) { - /** @var $loadBalancer OpenCloud\LoadBalancer\Resource\LoadBalancer **/ - - # View usage - /** @var $usage OpenCloud\LoadBalancer\Resource\UsageRecord **/ - $usage = $loadBalancer->usage(); - - echo $usage->averageNumConnections, PHP_EOL; -} -``` +https://doc.php-opencloud.com/en/latest/services/load-balancer/index.html diff --git a/docs/userguide/Networking/README.md b/docs/userguide/Networking/README.md index ee1de981e..1778646ad 100644 --- a/docs/userguide/Networking/README.md +++ b/docs/userguide/Networking/README.md @@ -1,76 +1,5 @@ # Networking -**Networking** is a service that you can use to create virtual networks and attach cloud devices such as servers to these networks. +Our docs have moved! Please visit the below link: -## Concepts - -## Concepts - -To use the Networking service effectively, you should understand the following key concepts: - -* **Network**: A network is an isolated virtual layer-2 broadcast domain that is typically reserved for the tenant who created it unless you configure the network to be shared. The network is the main entity in the Networking service. Ports and subnets are always associated with a network. - -* **Subnet**: A subnet represents an IP address block that can be used to assign IP addresses to virtual instances (such as servers created using the Compute service). Each subnet must have a CIDR and must be associated with a network. - -* **Port**: A port represents a virtual switch port on a logical network switch. Virtual instances (such as servers created using the Compute service) attach their interfaces into ports. The port also defines the MAC address and the IP address(es) to be assigned to the interfaces plugged into them. When IP addresses are associated to a port, this also implies the port is associated with a subet, as the IP address is taken from the allocation pool for a specific subnet. - - -## Getting started - -### 1. Instantiate an OpenStack or Rackspace client. - -To use the Networking service, you must first instantiate a `OpenStack` or `Rackspace` client object. - -* If you are working with an OpenStack cloud, instantiate an `OpenCloud\OpenStack` client as follows: - - ```php - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - ``` - -* If you are working with the Rackspace cloud, instantiate a `OpenCloud\Rackspace` client as follows: - - ```php - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - ``` - -### 2. Obtain an Networking service object from the client. -All Networking operations are done via an _networking service object_. To -instantiate this object, call the `networkingService` method on the `$client` -object. This method takes two arguments: - -| Position | Description | Data type | Required? | Default value | Example value | -| -------- | ----------- | ----------| --------- | ------------- | ------------- | -| 1 | Name of the service, as it appears in the service catalog | String | No | `null`; automatically determined when possible | `cloudNetworks` | -| 2 | Cloud region | String | Yes | - | `DFW` | - - -```php -$region = ''; -$networkingService = $client->networkingService(null, $region); -``` - -Any networks, subnets, and ports created with this `$networkingService` instance will -be stored in the cloud region specified by `$region`. - -### 3. Create a network. -```php -$network = $networkingService->createNetwork(array( - 'name' => 'My private backend network' -)); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-network.php) ] - -## Next steps - -Once you have created a network, there is more you can do with it. See [complete user guide for networking](USERGUIDE.md). +https://doc.php-opencloud.com/en/latest/services/networking/index.html diff --git a/docs/userguide/Networking/USERGUIDE.md b/docs/userguide/Networking/USERGUIDE.md index 5a7beb07f..376daa093 100644 --- a/docs/userguide/Networking/USERGUIDE.md +++ b/docs/userguide/Networking/USERGUIDE.md @@ -1,617 +1,5 @@ # Complete User Guide for the Networking Service -Networking is a service that you can use to create virtual networks and attach -cloud devices such as servers to these networks. +Our docs have moved! Please visit the below link: -This user guide introduces you the entities in the Networking service — -networks, subnets, and ports — and shows you how to create and manage -these entities. - -## Table of contents - * [Concepts](#concepts) - * [Prerequisites](#prerequisites) - * [Client](#client) - * [Networking service](#networking-service) - * [Networks](#networks) - * [Create a network](#create-a-network) - * [Create multiple networks](#create-multiple-networks) - * [List networks](#list-networks) - * [Get a network](#get-a-network) - * [Update a network](#update-a-network) - * [Delete a network](#delete-a-network) - * [Subnets](#subnets) - * [Create a subnet](#create-a-subnet) - * [Create multiple subnets](#create-multiple-subnets) - * [List subnets](#list-subnets) - * [Get a subnet](#get-a-subnet) - * [Update a subnet](#update-a-subnet) - * [Delete a subnet](#delete-a-subnet) - * [Ports](#ports) - * [Create a port](#create-a-port) - * [Create multiple ports](#create-multiple-ports) - * [List ports](#list-ports) - * [Get a port](#get-a-port) - * [Update a port](#update-a-port) - * [Delete a port](#delete-a-port) - * [Security Groups](#security-groups) - * [Create a security group](#create-a-security-group) - * [List security groups](#list-security-groups) - * [Get a security group](#get-a-security-group) - * [Delete a security group](#delete-a-security-group) - * [Security group rule Rules](#security-group-rules) - * [Create a security group rule](#create-a-security-group-rule) - * [List security group rules](#list-security-group-rules) - * [Get a security group rule](#get-a-security-group-rule) - * [Delete a security group rule](#delete-a-security-group-rule) - -## Concepts - -To use the Networking service effectively, you should understand the following -key concepts: - -* **Network**: An isolated virtual layer-2 broadcast domain that is typically -reserved for the tenant who created it unless it is configured to be shared. The -network is the main entity in the Networking service. Ports and subnets are -always associated with a network. - -* **Subnet**: An IP address block that can be used to assign IP addresses to -virtual instances (such as servers created using the Compute service). Each -subnet must have a CIDR and must be associated with a network. - -* **Port**: A virtual switch port on a logical network switch. Virtual instances -(such as servers created using the Compute service) attach their interfaces into -ports. The port also defines the MAC address and the IP address or addresses to -be assigned to the interfaces plugged into them. When IP addresses are -associated with a port, this also implies the port is associated with a subnet -because the IP address is taken from the allocation pool for a specific subnet. - -* **Security Group**: A named container for security group rules. - -* **Security Group Rule**: Provide users the ability to specify the types of traffic that are allowed to pass through to and from ports on a virtual server instance. - -## Prerequisites - -### Client -To use the Networking service, you must first instantiate a `OpenStack` or -`Rackspace` client object. - -* If you are working with an OpenStack cloud, instantiate an -`OpenCloud\OpenStack` client as follows: - - ```php - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - ``` - -* If you are working with the Rackspace cloud, instantiate an -`OpenCloud\Rackspace` client as follows: - - ```php - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - ``` - -### Networking service - -All Networking operations are done via a _networking service object_. To -instantiate this object, call the `networkingService` method on the `$client` -object. This method takes the following arguments: - -| Position | Description | Data type | Required? | Default value | Example value | -| -------- | ----------- | ----------| --------- | ------------- | ------------- | -| 1 | Name of the service, as it appears in the service catalog | String | No | `null`; automatically determined when possible | `cloudNetworks` | -| 2 | Cloud region | String | Yes | - | `DFW` | - - -```php -$region = ''; -$networkingService = $client->networkingService(null, $region); -``` - -Any networks, subnets, and ports created with this `$networkingService` instance -are stored in the cloud region specified by `$region`. - -## Networks - -A network is an isolated virtual layer-2 broadcast domain that is typically -reserved for the tenant who created it unless it is configured to be shared. The -network is the main entity in the Networking service. Ports and subnets are -always associated with a network. - -### Create a network - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | A human-readable name for the network. This name might not be unique. | String | No | `null` | `My private backend network` | -| `adminStateUp` | The administrative state of network. If `false` (down), the network does not forward packets. | Boolean | No | `true` | `true` | -| `shared` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | `false` | `false` | -| `tenantId` | Owner of network. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the network | `123456` | - -You can create a network as shown in the following example: - -```php -$network = $networkingService->createNetwork(array( - 'name' => 'My private backend network' -)); -/** @var $network OpenCloud\Networking\Resource\Network **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-network.php) ] - -### Create multiple networks - -This operation takes one parameter, an indexed array. Each element of this array must -be an associative array with the keys shown in [the preceding table](#create-a-network). - -You can create multiple networks as shown in the following example: - -```php -$networks = $networkingService->createNetworks(array( - array( - 'name' => 'My private backend network #1' - ), - array( - 'name' => 'My private backend network #2' - ) -)); - -foreach ($networks as $network) { - /** @var $network OpenCloud\Networking\Resource\Network **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-networks.php) ] - -### List networks - -You can list all the networks to which you have access as shown in the following example: - -```php -$networks = $networkingService->listNetworks(); -foreach ($networks as $network) { - /** @var $network OpenCloud\Networking\Resource\Network **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/list-networks.php) ] - -### Get a network - -You can retrieve a specific network by using that network's ID, as shown in the following example: - -```php -$network = $networkingService->getNetwork('eb60583c-57ea-41b9-8d5c-8fab2d22224c'); -/** @var $network OpenCloud\Networking\Resource\Network **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/get-network.php) ] - -### Update a network - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | A human-readable name for the network. This name might not be unique. | String | No | `null` | `My updated private backend network` | -| `adminStateUp` | The administrative state of network. If `false` (down), the network does not forward packets. | Boolean | No | `true` | `true` | -| `shared` | Specifies whether the network resource can be accessed by any tenant. | Boolean | No | `false` | `false` | - -You can update a network as shown in the following example: - -```php -$network->update(array( - 'name' => 'My updated private backend network' -)); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/update-network.php) ] - -### Delete a network - -You can delete a network as shown in the following example: - -```php -$network->delete(); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/delete-network.php) ] - -## Subnets - -A subnet represents an IP address block that can be used to assign IP addresses -to virtual instances (such as servers created using the Compute service). Each -subnet must have a CIDR and must be associated with a network. - -### Create a subnet - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `networkId` | Network this subnet is associated with | String | Yes | - | `eb60583c-57ea-41b9-8d5c-8fab2d22224c` | -| `ipVersion` | IP version | Integer (`4` or `6`) | Yes | - | `4` | -| `cidr` | CIDR representing the IP address range for this subnet | String (CIDR) | Yes | - | `192.168.199.0/25` | -| `name` | A human-readable name for the subnet. This name might not be unique. | String | No | `null` | `My subnet` | -| `gatewayIp` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | `192.168.199.128` | -| `dnsNameservers` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | `array('4.4.4.4', '8.8.8.8')` | -| `allocationPools` | Subranges of the CIDR available for dynamic allocation to ports | Indexed array of associative arrays | No | Every IP address in CIDR, excluding gateway IP address if configured | `array(array('start' => '192.168.199.2', 'end' => '192.168.199.127'))` | -| `hostRoutes` | Routes that should be used by devices with IP addresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | `array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.19.20'))` | -| `enableDhcp` | Specifies whether DHCP is enabled for this subnet | Boolean | No | `true` | `false` | -| `tenantId` | Owner of the subnet. Only admin users can specify a tenant ID other than their own. | String | No | Same as tenant creating the subnet | `123456` | - -You can create a subnet as shown in the following example: - -```php -$subnet = $networkingService->createSubnet(array( - 'name' => 'My subnet', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c', - 'ipVersion' => 4, - 'cidr' => '192.168.199.0/25' -)); -/** @var $subnet OpenCloud\Networking\Resource\Subnet **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-subnet.php) ] - -### Create multiple subnets - -This operation takes one parameter, an indexed array. Each element of this array must -be an associative array with the keys shown in [the preceding table](#create-a-subnet). - -You can create multiple subnets as shown in the following example: - -```php -$subnets = $networkingService->createSubnets(array( - array( - 'name' => 'My subnet #1' - ), - array( - 'name' => 'My subnet #2' - ) -)); - -foreach ($subnets as $subnet) { - /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-subnets.php) ] - -### List subnets - -You can list all the subnets to which you have access as shown in the following -example: - -```php -$subnets = $networkingService->listSubnets(); -foreach ($subnets as $subnet) { - /** @var $subnet OpenCloud\Networking\Resource\Subnet **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/list-subnets.php) ] - -### Get a subnet - -You can retrieve a specific subnet by using that subnet's ID, as shown in the -following example: - -```php -$subnet = $networkingService->getSubnet('d3f15879-fb11-49bd-a30b-7704fb98ab1e'); -/** @var $subnet OpenCloud\Networking\Resource\Subnet **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/get-subnet.php) ] - -### Update a subnet - -This operation takes one parameter, an associative array, with the following -keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | A human-readable name for the subnet. This name might not be unique. | String | No | `null` | `My updated subnet` | -| `gatewayIp` | IP address of the default gateway used by devices on this subnet | String (IP address) | No | First IP address in CIDR | `192.168.62.155` | -| `dnsNameservers` | DNS nameservers used by hosts in this subnet | Indexed array of strings | No | Empty array | `array('4.4.4.4', '8.8.8.8')` | -| `hostRoutes` | Routes that should be used by devices with IP adresses from this subnet (not including the local subnet route) | Indexed array of associative arrays | No | Empty array | `array(array('destination' => '1.1.1.0/24', 'nexthop' => '192.168.17.19'))` | -| `enableDhcp` | Specifies whether DHCP is enabled for this subnet | Boolean | No | `true` | `false` | - -You can update a subnet as shown in the following example: - -```php -$subnet->update(array( - 'name' => 'My updated subnet', - 'hostRoutes' => array( - array( - 'destination' => '1.1.1.0/24', - 'nexthop' => '192.168.17.19' - ) - ), - 'gatewayIp' => '192.168.62.155' -)); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/update-subnet.php) ] - -### Delete a subnet - -You can delete a subnet as shown in the following example: - -```php -$subnet->delete(); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/delete-subnet.php) ] - -## Ports - -A port represents a virtual switch port on a logical network switch. Virtual -instances (such as servers created using the Compute service) attach their -interfaces into ports. The port also defines the MAC address and the IP address -or addresses to be assigned to the interfaces plugged into them. When IP -addresses are associated with a port, this also implies the port is associated -with a subnet because the IP address is taken from the allocation pool for a -specific subnet. - -### Create a port - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `networkId` | Network this port is associated with | String | Yes | - | `eb60583c-57ea-41b9-8d5c-8fab2d22224c` | -| `name` | A human-readable name for the port. This name might not be unique. | String | No | `null` | `My port` | -| `adminStateUp` | The administrative state of port. If `false` (down), the port does not forward packets. | Boolean | No | `true` | `true` | -| `macAddress` | MAC address to use on this port | String (MAC address in 6-octet form separated by colons) | No | Generated | `0F:5A:6F:70:E9:5C` | -| `fixedIps` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | `array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.17'))` | -| `deviceId` | Identifies the device (for example, virtual server) using this port | String | No | `null` | `5e3898d7-11be-483e-9732-b2f5eccd2b2e` | -| `deviceOwner` | Identifies the entity (for example, DHCP agent) using this port | String | No | `null` | `network:router_interface` | -| `securityGroups` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | `array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')` | -| `tenantId` | Owner of the port. Only admin users can specify a tenant ID other than their own. | String | No | Same as the tenant creating the port | `123456` | - -You can create a port as shown in the following example: - -```php -$port = $networkingService->createPort(array( - 'name' => 'My port', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' -)); -/** @var $port OpenCloud\Networking\Resource\Port **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-port.php) ] - -### Create multiple ports - -This operation takes one parameter, an indexed array. Each element of this -array must be an associative array with the keys shown in -[the preceding table](#create-a-port). - -You can create multiple ports as shown in the following example: - -```php -$ports = $networkingService->createPorts(array( - array( - 'name' => 'My port #1', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' - ), - array( - 'name' => 'My port #2', - 'networkId' => 'eb60583c-57ea-41b9-8d5c-8fab2d22224c' - ) -)); - -foreach ($ports as $port) { - /** @var $port OpenCloud\Networking\Resource\Port **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-ports.php) ] - -### List ports - -You can list all the ports to which you have access as shown in the following -example: - -```php -$ports = $networkingService->listPorts(); -foreach ($ports as $port) { - /** @var $port OpenCloud\Networking\Resource\Port **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/list-ports.php) ] - -### Get a port - -You can retrieve a specific port by using that port's ID, as shown in the -following example: - -```php -$port = $networkingService->getPort('75906d20-6625-11e4-9803-0800200c9a66'); -/** @var $port OpenCloud\Networking\Resource\Port **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/get-port.php) ] - -### Update a port - -This operation takes one parameter, an associative array, with the following -keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | A human-readable name for the port. This name might not be unique. | String | No | `null` | `My port` | -| `adminStateUp` | The administrative state of port. If `false` (down), the port does not forward packets. | Boolean | No | `true` | `true` | -| `fixedIps` | IP addresses for this port | Indexed array of associative arrays | No | Automatically allocated from the pool | `array(array('subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', 'ipAddress' => '192.168.199.59'))` | -| `deviceId` | Identifies the device (for example, virtual server) using this port | String | No | `null` | `5e3898d7-11be-483e-9732-b2f5eccd2b2e` | -| `deviceOwner` | Identifies the entity (for example, DHCP agent) using this port | String | No | `null` | `network:router_interface` | -| `securityGroups` | Specifies the IDs of any security groups associated with this port | Indexed array of strings | No | Empty array | `array('f0ac4394-7e4a-4409-9701-ba8be283dbc3')` | - -You can update a port as shown in the following example: - -```php -$port->update(array( - 'fixedIps' => array( - array( - 'subnetId' => '75906d20-6625-11e4-9803-0800200c9a66', - 'ipAddress' => '192.168.199.59' - ) - ) -)); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/update-port.php) ] - -### Delete a port - -You can delete a port as shown in the following example: - -```php -$port->delete(); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/delete-port.php) ] - -## Security Groups - -A security group is a named container for [security group rules](#security-group-rules). - -### Create a security group - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | A human-readable name for the security group. This name might not be unique. | String | Yes | - | `new-webservers` | -| `description` | Description of the security group. | String | No | `null` | `security group for webservers` | - -You can create a security group as shown in the following example: - -```php -$securityGroup = $networkingService->createSecurityGroup(array( - 'name' => 'new-webservers', - 'description' => 'security group for webservers' -)); -/** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-security-group.php) ] - -### List security groups - -You can list all the security groups to which you have access as shown in the following -example: - -```php -$securityGroups = $networkingService->listSecurityGroups(); -foreach ($securityGroups as $securityGroup) { - /** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/list-security-groups.php) ] - -### Get a security group - -You can retrieve a specific security group by using that security group's ID, as shown in the -following example: - -```php -$securityGroup = $networkingService->getSecurityGroup('2076db17-a522-4506-91de-c6dd8e837028'); -/** @var $securityGroup OpenCloud\Networking\Resource\SecurityGroup **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/get-security-group.php) ] - -### Delete a security group - -You can delete a security group as shown in the following example: - -```php -$securityGroup->delete(); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/delete-security-group.php) ] - -## Security Group Rules - -A security group rule provides users the ability to specify the types of traffic that are allowed to pass through to and from ports on a virtual server instance. - -### Create a security group rule - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `securityGroupId` | The security group ID to associate with this security group rule. | String | Yes | - | `2076db17-a522-4506-91de-c6dd8e837028` | -| `direction` | The direction in which the security group rule is applied. For a compute instance, an ingress security group rule is applied to incoming (ingress) traffic for that instance. An egress rule is applied to traffic leaving the instance. | String (`ingress` or `egress`) | Yes | - | `ingress` | -| `ethertype` | Must be IPv4 or IPv6, and addresses represented in CIDR must match the ingress or egress rules. | String (`IPv4` or `IPv6`) | No | `IPv4` | `IPv6` | -| `portRangeMin` | The minimum port number in the range that is matched by the security group rule. If the protocol is TCP or UDP, this value must be less than or equal to the value of the `portRangeMax` attribute. If the protocol is ICMP, this value must be an ICMP type. | Integer | No | `null` | `80` | -| `portRangeMax` | The maximum port number in the range that is matched by the security group rule. The port_range_min attribute constrains the attribute. If the protocol is ICMP, this value must be an ICMP type. | Integer | No | `null` | `80` | -| `protocol` | The protocol that is matched by the security group rule. | String (`tcp`, `udp`, `icmp`) | No | `null` | `tcp` | -| `remoteGroupId` | The remote group ID to be associated with this security group rule. You can specify either `remoteGroupId` or `remoteGroupPrefix`. | String | Optional | `null` | `85cc3048-abc3-43cc-89b3-377341426ac5` | -| `remoteIpPrefix` | The remote IP prefix to be associated with this security group rule. You can specify either `remoteGroupId` or `remoteGroupPrefix`. | String | Optional | `null` | `192.168.5.0` | - -You can create a security group rule as shown in the following example: - -```php -$securityGroupRule = $networkingService->createSecurityGroupRule(array( - 'securityGroupId' => '2076db17-a522-4506-91de-c6dd8e837028', - 'direction' => 'egress', - 'ethertype' => 'IPv4', - 'portRangeMin' => 80, - 'portRangeMax' => 80, - 'protocol' => 'tcp', - 'remoteGroupId' => '85cc3048-abc3-43cc-89b3-377341426ac5' -)); -/** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/create-security-group-rule.php) ] - -### List security group rules - -You can list all the security group rules to which you have access as shown in the following -example: - -```php -$securityGroupRules = $networkingService->listSecurityGroupRules(); -foreach ($securityGroupRules as $securityGroupRule) { - /** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ -} -``` - -[ [Get the executable PHP script for this example](/samples/Networking/list-security-group-rules.php) ] - -### Get a security group rule - -You can retrieve a specific security group rule by using that security group rule's ID, as shown in the -following example: - -```php -$securityGroupRule = $networkingService->getSecurityGroupRule(''); -/** @var $securityGroupRule OpenCloud\Networking\Resource\SecurityGroupRule **/ -``` - -[ [Get the executable PHP script for this example](/samples/Networking/get-security-group-rule.php) ] - -### Delete a security group rule - -You can delete a security group rule as shown in the following example: - -```php -$securityGroupRule->delete(); -``` - -[ [Get the executable PHP script for this example](/samples/Networking/delete-security-group-rule.php) ] +https://doc.php-opencloud.com/en/latest/services/networking/index.html diff --git a/docs/userguide/ObjectStore/Access.md b/docs/userguide/ObjectStore/Access.md index 0b15a2d19..8e224392a 100644 --- a/docs/userguide/ObjectStore/Access.md +++ b/docs/userguide/ObjectStore/Access.md @@ -1,66 +1,5 @@ ## Setup -```php -use OpenCloud\Rackspace; +Our docs have moved! Please visit the below link: -$client = new Rackspace(RACKSPACE_US, array( - -)); - -$service = $client->objectStoreService('cloudFiles', 'IAD'); # Second argument is the region you want -``` - -## Temporary URLs - -Temporary URLs allow you to create time-limited Internet addresses that allow you to grant access to your Cloud Files -account. Using Temporary URL, you may allow others to retrieve or place objects in your containers - regardless of -whether they're CDN-enabled. - -### Set "temporary URL" metadata key - -You must set this "secret" value on your account, where it can be used in a global state: - -```php -$account = $service->getAccount(); -$account->setTempUrlSecret('my_secret'); - -echo $account->getTempUrlSecret(); -``` - -The string argument of `setTempUrlSecret()` is optional - if left out, the SDK will generate a random hashed secret -for you. - -### Create a temporary URL - -Once you've set an account secret, you can create a temporary URL for your object. To allow GET access to your object -for 1 minute: - -```php -$object->getTemporaryUrl(60, 'GET'); -``` - -To allow PUT access for 1 hour: - -```php -$object->getTemporaryUrl(360, 'PUT'); -``` - -## Hosting websites on CloudFiles - -To host a static (i.e. HTML) website on CloudFiles, you must follow these steps: - -1. CDN-enable a container -2. Upload all HTML content. You can use nested directory structures. -3. Tell CloudFiles what to use for your default index page like this: - -```php -$container->setStaticIndexPage('index.html'); -``` - -4. (Optional) Tell CloudFiles which error page to use by default: - -```php -$container->setStaticErrorPage('error.html'); -``` - -Bear in mind that steps 3 & 4 do not upload content, but rather specify a reference to an existing page/CloudFiles object. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/object-store/access.html diff --git a/docs/userguide/ObjectStore/Account.md b/docs/userguide/ObjectStore/Account.md index edd26c2c1..fc60751a8 100644 --- a/docs/userguide/ObjectStore/Account.md +++ b/docs/userguide/ObjectStore/Account.md @@ -1,28 +1,5 @@ ## Setup -```php -use OpenCloud\Rackspace; +Our docs have moved! Please visit the below link: -$client = new Rackspace(RACKSPACE_US, array( - -)); - -$service = $client->objectStoreService('cloudFiles'); -``` - -## View Account Details - -To see how many containers you have in your account (X-Account-Container-Count), how many objects are in your account -(X-Account-Object-Count), and how many total bytes your account uses (X-Account-Bytes-Used): - -```php -$account = $service->getAccount(); - -// Either return the full Metadata object -$details = $account->getDetails(); - -// or individual values -$account->getContainerCount(); -$account->getObjectCount(); -$account->getBytesUsed(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/object-store/account.html diff --git a/docs/userguide/ObjectStore/CDN/Container.md b/docs/userguide/ObjectStore/CDN/Container.md index 642ee968d..9f3b4a5ca 100644 --- a/docs/userguide/ObjectStore/CDN/Container.md +++ b/docs/userguide/ObjectStore/CDN/Container.md @@ -1,78 +1,5 @@ ## Setup -```php -use OpenCloud\Rackspace; +Our docs have moved! Please visit the below link: -$client = new Rackspace(RACKSPACE_US, array( - -)); - -$service = $client->objectStoreService('cloudFiles'); -``` - -To access the CDN functionality of a particular container: - -```php -$container = $service->getContainer('foo_bar'); - -$cdn = $container->getCdn(); -``` - -## List CDN-enabled container - -To list CDN-only containers, follow the same operation for Storage which lists all containers. The only difference is -which service object you execute the method on: - -```php -$cdnService = $service->getCdnService(); -$cdnContainers = $cdnService->listContainers(); - -foreach ($cdnContainers as $cdnContainer) { - -} -``` - -## CDN-enable and -disable a container - -Before a container can be CDN-enabled, it must exist in the storage system. When a container is CDN-enabled, any objects -stored in it are publicly accessible over the Content Delivery Network by combining the container's CDN URL with the -object name. - -Any CDN-accessed objects are cached in the CDN for the specified amount of time called the TTL. The default TTL value is -259200 seconds, or 72 hours. Each time the object is accessed after the TTL expires, the CDN refetches and caches the -object for the TTL period. - -```php -$container->enableCdn(); -$container->disableCdn(); -``` - -## Serving containers through SSL - -```php -$cdn->getCdnSslUri(); -``` - -## Streaming CDN-enabled containers - -```php -$cdn->getCdnStreamingUri(); -``` - -## iOS streaming - -The Cloud Files CDN allows you to stream video to iOS devices without needing to convert your video. Once you -CDN-enable your container, you have the tools necessary for streaming media to multiple devices. - -```php -$cdn->getIosStreamingUri(); -``` - -## CDN logging - -To enable and disable logging for your CDN: - -```php -$cdn->enableCdnLogging(); -$cdn->disableCdnLogging(); -``` +https://doc.php-opencloud.com/en/latest/services/object-store/cdn.html diff --git a/docs/userguide/ObjectStore/CDN/Object.md b/docs/userguide/ObjectStore/CDN/Object.md index 79e3d4cdc..9f3b4a5ca 100644 --- a/docs/userguide/ObjectStore/CDN/Object.md +++ b/docs/userguide/ObjectStore/CDN/Object.md @@ -1,20 +1,5 @@ ## Setup -You will need to instantiate the container object and access its CDN functionality as -[documented here](https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/ObjectStore/CDN/Container.md). +Our docs have moved! Please visit the below link: -## Purge CDN-enabled objects - -To remove a CDN object from public access: - -```php -$object->purge(); -``` - -You can also provide an optional e-mail address (or comma-delimeted list of e-mails), which the API will send a -confirmation message to once the object has been completely purged: - -```php -$object->purge('jamie.hannaford@rackspace.com'); -$object->purge('hello@example.com,hallo@example.com'); -``` +https://doc.php-opencloud.com/en/latest/services/object-store/cdn.html diff --git a/docs/userguide/ObjectStore/README.md b/docs/userguide/ObjectStore/README.md index 33ad706dd..ea43fcdf7 100644 --- a/docs/userguide/ObjectStore/README.md +++ b/docs/userguide/ObjectStore/README.md @@ -1,65 +1,5 @@ # Object Store -**Object Store** is an object-based storage system that stores content and metadata as objects in a cloud. +Our docs have moved! Please visit the below link: -Specifically, a cloud is made up of one or more regions. Each region can have several **containers**, created by a user. Each container can container several **objects** (sometimes referred to as files), uploaded by the user. - -## Getting started - -### 1. Instantiate an OpenStack or Rackspace client. - -Choose one of the following two options: - -* If you are working with a vanilla OpenStack cloud, instantiate an `OpenCloud\OpenStack` client as shown below. - - ```php - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - ``` - -* If you are working with the Rackspace cloud, instantiate a `OpenCloud\Rackspace` client as shown below. - - ```php - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - ``` - -### 2. Obtain an Object Store service object from the client. -```php -$region = 'DFW'; -$objectStoreService = $client->objectStoreService(null, $region); -``` - -In the example above, you are connecting to the ``DFW`` region of the cloud. Any containers and objects created with this `$objectStoreService` instance will be stored in that cloud region. - -### 3. Create a container for your objects (also referred to as files). - -```php -$container = $objectStoreService->createContainer('logos'); -``` - -> **Note:** when working with names that contain non-standard alphanumerical characters (such as spaces or non-English characters), you must ensure they are encoded with [`urlencode`](http://php.net/urlencode) before passing them in - -### 4. Upload an object to the container. - -```php -$localFileName = '/path/to/local/php-elephant.jpg'; -$remoteFileName = 'php-elephant.jpg'; - -$fileData = fopen($localFileName, 'r'); -$container->uploadObject($remoteFileName, $fileData); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/quickstart.php) ] - -## Next steps - -There is a lot more you can do with containers and objects. See -the [complete user guide to the Object Store service](USERGUIDE.md). +https://doc.php-opencloud.com/en/latest/services/object-store/index.html diff --git a/docs/userguide/ObjectStore/Storage/Container.md b/docs/userguide/ObjectStore/Storage/Container.md index 5f75de9d1..e9fd5af14 100644 --- a/docs/userguide/ObjectStore/Storage/Container.md +++ b/docs/userguide/ObjectStore/Storage/Container.md @@ -1,182 +1,5 @@ ## Setup -```php -use OpenCloud\Rackspace; +Our docs have moved! Please visit the below link: -// Create a client object to communicate with various Rackspace Cloud services. -$client = new Rackspace(RACKSPACE_US, array( - 'username' => 'Replace this with your Rackspace Cloud user name', - 'apiKey' => 'Replace this with your Rackspace Cloud API key' -)); - -// Create a service object to use the object store service. The sample code -// creates the object store in the 'DFW' region. -$service = $client->objectStoreService('cloudFiles', 'DFW'); -``` - -## Create container - -To create a new container, you just need to define its name: - -```php -$container = $service->createContainer('my_amazing_container'); -``` - -If the response returned is `FALSE`, there was an API error - most likely due to the fact you have a naming collision. - -Container names must be valid strings between 0 and 256 characters. Forward slashes are not currently permitted. - -> **Note:** when working with names that contain non-standard alphanumerical characters (such as spaces or non-English characters), you must ensure they are encoded with [`urlencode`](http://php.net/urlencode) before passing them in - -## List containers - -### Return a list of containers - -```php -$containerList = $service->listContainers(); - -while ($container = $containerList->next()) { - // Do stuff; some examples below - printf("Container name: %s\n", $container->name); - printf("Number of objects within container: %d\n", $container->getObjectCount()); -} -``` - -Container names are sorted based on a binary comparison, a single built-in collating sequence that compares string -data using SQLite's memcmp() function, regardless of text encoding. - -The list is limited to 10,000 containers at a time. See 1.3 for ways to limit and navigate this list. - -### Return a formatted list of containers - -Currently, the SDK only supports JSON-formatted responses. - -### Controlling a large list of containers - -You may limit and control this list of results by using the `marker` and `end_marker` parameters. The former parameter -(`marker`) tells the API where to begin the list, and the latter (`end_marker`) tells it where to end the list. You may -use either of them independently or together. You may also use the `limit` parameter to fix the number of containers -returned. - -To list a set of containers between two fixed points: - -```php -$someContainers = $service->listContainers(array( - 'marker' => 'container_55', - 'end_marker' => 'container_2001' -)); -``` - -Or to return a limited set: - -```php -$someContainers = $service->listContainers(array('limit' => 560)); -``` - -## Get container - -To retrieve a certain container, either to access its object or metadata: - -```php -$container = $service->getContainer('container_name'); - -echo $container->getObjectCount(); -echo $container->getBytesUsed(); -``` - -## Delete container - -Deleting a container is easy: -```php -$container->delete(); -``` - -Please bear mind that you must delete all objects inside a container before deleting it. This is done for you if you -set the `$deleteObjects` parameter to `TRUE` like so: - -```php -$container->delete(TRUE); -``` - -You can also do it manually: - -```php -$container->deleteAllObjects(); -$container->delete(); -``` - -## Create or update container metadata - -```php -$container->saveMetadata(array( - 'Author' => 'Virginia Woolf', - 'Published' => '1931' -)); -``` - -Please bear in mind that this action will set metadata to this array - overriding existing values and wiping those left -out. To _append_ values to the current metadata: - -```php -$metadata = $container->appendToMetadata(array( - 'Publisher' => 'Hogarth' -)); -``` - -If you only want to set the metadata to the local object, and not immediately retain these values on the API, you can -use a standard setter method - which can contribute to eventual actions like an update: - -```php -$container->setMetadata(array('Foo' => 'Bar')); -``` - -## Container quotas - -The container_quotas middleware implements simple quotas that can be imposed on Cloud Files containers by a user. -Setting container quotas can be useful for limiting the scope of containers that are delegated to non-admin users, -exposed to formpost uploads, or just as a self-imposed sanity check. - -To set quotas for a container: - -```php -use OpenCloud\Common\Constants\Size; - -$container->setCountQuota(1000); -$container->setBytesQuota(2.5 * Size::GB); -``` - -And to retrieve them: - -```php -echo $container->getCountQuota(); -echo $container->getBytesQuota(); -``` - -## Access log delivery - -To view your object access, turn on Access Log Delivery. You can use access logs to analyze the number of people who -access your objects, where they come from, how many requests for each object you receive, and time-based usage patterns -(such as monthly or seasonal usage). - -```php -$container->enableLogging(); -$container->disableLogging(); -``` - -## Syncing containers - -You can synchronize local directories with your CloudFiles/Swift containers very easily. When you do this, the container -will mirror exactly the nested file structure within your local directory: - -```php -$container->uploadDirectory('/home/Jamie/blog'); -``` - -There are four scenarios you should be aware of: - -Local|Remote|Comparison|Action ----|---|---|--- -File exists|File exists|Identical checksum|No action -File exists|File exists|Different checksum|Local file overwrites remote -File exists|File does not exist|-|Local file created in Swift -Files does not exist|File exists|-|Remote file deleted \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/object-store/containers.html diff --git a/docs/userguide/ObjectStore/Storage/Migrating.md b/docs/userguide/ObjectStore/Storage/Migrating.md index d92528cbf..8d12c382a 100644 --- a/docs/userguide/ObjectStore/Storage/Migrating.md +++ b/docs/userguide/ObjectStore/Storage/Migrating.md @@ -1,83 +1,5 @@ # Migrating containers (across regions) -## Introduction +Our docs have moved! Please visit the below link: -Currently, there exists no single API operation to copy containers across geographic endpoints. Although the API offers -a `COPY` operation for individual files, this does not work for cross-region copying. The SDK, however, does offer this -functionality. - -You **will** be charged for bandwidth between regions, so it's advisable to use ServiceNet where possible (which is -free). - -## Requirements - -* You must install the full Guzzle package, so that the process can take advantage of Guzzle's batching functionality -(it allows parallel requests to be batched for greater efficiency). You can do this by running: - -```bash -php composer.phar install --dev -``` - -* Depending on the size and number of transfer items, you will need to raise PHP's memory limit: - -```php -ini_set('memory_limit', '512M'); -``` - -* You will need to enact some kind of backoff/retry strategy for rate limits. Guzzle comes with a convenient feature -that just needs to be added as a normal subscriber: - -```php -use Guzzle\Plugin\Backoff\BackoffPlugin; - -$client->addSubscriber(BackoffPlugin::getExponentialBackoff(10, array(500, 503, 408))); -``` - -This tells the client to retry up to `10` times for failed requests have resulted in these HTTP status codes: `500`, -`503` or `408`. - -## Setup - -You can access all this functionality by executing: - -```php -$ordService = $client->objectStoreService('cloudFiles', 'ORD'); -$iadService = $client->objectStoreService('cloudFiles', 'IAD'); - -$oldContainer = $ordService->getContainer('old_container'); -$newContainer = $iadService->getContainer('new_container'); - -$iadService->migrateContainer($oldContainer, $newContainer); -``` - -It's advisable to do this process in a Cloud Server in one of the two regions you're migrating to/from. This allows you -to use `privateURL` as the third argument in the `objectStoreService` methods like this: - -```php -$client->objectStoreService('cloudFiles', 'IAD', 'privateURL'); -``` - -This will ensure that traffic between your server and your new IAD container will be held over the internal Rackspace -network which is free. - -## Options - -You can pass in an array of arguments to the method: - -```php -$options = array( - 'read.batchLimit' => 100, - 'read.pageLimit' => 100, - 'write.batchLimit' => 50 -); - -$iadService->migrateContainer($oldContainer, $newContainer, $options); -``` - -### Options explained - -Name|Description|Default ----|---|--- -`read.pageLimit`|When the process begins, it has to collect all the files that exist in the old container. It does this through a conventional `objectList` method, which calls the `PaginatedIterator`. This iterator has the option to specify the page size for the collection (i.e. how many items are contained per page in responses from the API)|10,000 -`read.batchLimit`|After the data objects are collected, the process needs to send an individual GET request to ascertain more information. In order to make this process faster, these individual GET requests are batched together and sent in parallel. This limit refers to how many of these GET requests are batched together.|1,000 -`write.batchLimit`|Once each file has been retrieved from the API, a PUT request is executed against the new container. Similar to above, these PUT requests are batched - and this number refers to the amount of PUT requests batched together.|100 \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/object-store/migrating-containers.html diff --git a/docs/userguide/ObjectStore/Storage/Object.md b/docs/userguide/ObjectStore/Storage/Object.md index 4127b2610..0c58ca9fb 100644 --- a/docs/userguide/ObjectStore/Storage/Object.md +++ b/docs/userguide/ObjectStore/Storage/Object.md @@ -1,275 +1,5 @@ ## Setup -Conceptually, a container contains objects (also known as files). In order to work with -objects, you will need to instantiate a container object first as [documented here](https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/ObjectStore/Storage/Container.md). +Our docs have moved! Please visit the below link: -## Note on object properties - -Please be aware that you cannot directly access the properties of DataObject anymore, you __must__ use appropriate getter/ -setter methods: - -|Property|Method| -|--------|------| -|Parent container|`getContainer`| -|Name|`getName`| -|Body of file|`getContent`| -|Size of file|`getContentLength`| -|Type of file|`getContentType`| -|ETag checksum|`getEtag`| -|Last modified date|`getLastModified`| - -## Create an object - -There are three ways to upload a new file, each of which has different business needs. - -> **Note:** Unlike previous versions, you do not need to manually specify your object's content type. The API will do this -for you. - -> **Note:** when working with names that contain non-standard alphanumerical characters (such as spaces or non-English characters), you must ensure they are encoded with [`urlencode`](http://php.net/urlencode) before passing them in - -### To upload a single/basic file: - -```php -use OpenCloud\ObjectStore\Resource\DataObject; - -$data = fopen('/path/to/sample.mp3', 'r+'); - -// alternatively, you can pass in a string as the file contents `$data` argument (instead of a resource) - -$meta = array( - 'Author' => 'Camera Obscura', - 'Origin' => 'Glasgow' -); - -$metaHeaders = DataObject::stockHeaders($meta); -$customHeaders = array(); -$allHeaders = $metaHeaders + $customHeaders; - -$container->uploadObject('sample.mp3', $data, $allHeaders); -``` - -### To upload multiple small-to-mid sized files: - -```php -$files = array( - array( - 'name' => 'apache.log', - 'path' => '/etc/httpd/logs/error_log' - ), - array( - 'name' => 'mysql.log', - 'body' => fopen('/tmp/mysql.log', 'r+') - ), - array( - 'name' => 'to_do_list.txt', - 'body' => 'PHONE HOME' - ) -); - -$container->uploadObjects($files); -``` - -As you can see, the `name` key is required for every file. You must also specify _either_ a path key (to an existing -file), or a `body`. The `body` can either be a PHP resource or a string representation of the content you want to upload. - -### To upload large files - -For files over 5GB, you will need to use the `OpenCloud\ObjectStore\Upload\TransferBuilder` factory to build your transfer, -upon which you can execute your upload functionality. For your convenience, the Container resource object contains a -simple method to do this heavy lifting for you: - -```php -$transfer = $container->setupObjectTransfer(array( - 'name' => 'video.mov', - 'path' => '/home/jamie/video.mov', - 'metadata' => array( - 'Author' => 'Jamie' - ), - 'concurrency' => 4, - 'partSize' => 1.5 * Size::GB -)); - -$transfer->upload(); -``` - -You can specify how many concurrent cURL connections are used to upload parts of your file. The file is fragmented into -chunks, each of which is uploaded individually as a separate file (the filename of each part will indicate that it's a -segment rather than the full file). After all parts are uploaded, a manifest is uploaded. When the end-user accesses -the 5GB by its true filename, it actually references the manifest file which concatenates each segment into a streaming -download. - -## List objects in a container - -To return a list of objects: - -```php -$files = $container->objectList(); - -foreach ($files as $file) { - // ... do something -} -``` - -By default, 10,000 objects are returned as a maximum. To get around this, you can construct a query which refines your -result set. For a full specification of query parameters relating to collection filtering, see the [official docs](http://docs.openstack.org/api/openstack-object-storage/1.0/content/list-objects.html). - -```php -$container->objectList(array('prefix' => 'logFile_')); -``` - -## Get object - -To retrieve a specific file from Cloud Files: - -```php -$file = $container->getObject('summer_vacation.mp4'); -``` - -### Conditional requests - -You can also perform conditional requests according to [RFC 2616 specification](http://www.ietf.org/rfc/rfc2616.txt) -(§§ 14.24-26). Supported headers are `If-Match`, `If-None-Match`, `If-Modified-Since` and `If-Unmodified-Since`. - -So, to retrieve a file's contents only if it's been recently changed - -```php -$file = $container->getObject('error_log.txt', array( - 'If-Modified-Since' => 'Tue, 15 Nov 1994 08:12:31 GMT' -)); - -if ($file->getContentLength()) { - echo 'Has been changed since the above date'; -} else { - echo 'Has not been changed'; -} -``` - -Retrieve a file only if it has NOT been modified (and expect a 412 on failure): - -``` -use Guzzle\Http\Exception\ClientErrorResponseException; - -try { - $oldImmutableFile = $container->getObject('payroll_2001.xlsx', array( - 'If-Unmodified-Since' => 'Mon, 31 Dec 2001 23:00:00 GMT' - )); -} catch (ClientErrorResponseException $e) { - echo 'This file has been modified...'; -} -``` - -Finally, you can specify a range - which will return a subset of bytes from the file specified. To return the last 20B -of a file: - -```php -$snippet = $container->getObject('output.log', array('range' => 'bytes=-20')); -``` - -## Update an existing object - -Updating content is easy: - -```php -$file->setContent(fopen('/path/to/new/content', 'r+')); -$file->update(); -``` - -Bear in mind that updating a file name will result in a new file being generated (under the new name). You will need to -delete the old file. - -## Copy object - -To copy a file to another location, you need to specify a string-based destination path: - -```php -$object->copy('/container_2/new_object_name'); -``` - -## Delete object - -```php -$object->delete(); -``` - -## Get object metadata -You can fetch just the object metadata without fetching the full content: -```php -$container->getPartialObject('summer_vacation.mp4'); -``` - -In order to access the metadata on a partial or complete object, use: - -```php -$object->getMetadata(); -``` - -You can turn a partial object into a full object to get the content after looking at the metadata: -```php -$object->refresh(); -``` - -You can also update to get the latest metadata: - -```php -$object->retrieveMetadata(); -``` - -## Update object metadata - -Similarly, with setting metadata there are two options: you can update the metadata values of the local object (i.e. no -HTTP request) if you anticipate you'll be executing one soon (an update operation for example): - -```php -// There's no need to execute a HTTP request, because we'll soon do one anyway for the update operation -$object->setMetadata(array( - 'Author' => 'Hemingway' -)); - -// ... code here - -$object->update(); -``` - -Alternatively, you can update the API straight away - so that everything is retained: - -```php -$object->saveMetadata(array( - 'Author' => 'Hemingway' -)); -``` - -Please be aware that these methods override and wipe existing values. If you want to append values to your metadata, use -the correct method: - -```php -$metadata = $object->appendToMetadata(array( - 'Author' => 'Hemingway' -)); - -$object->saveMetadata($metadata); -``` - -## Extract archive - -CloudFiles provides you the ability to extract uploaded archives to particular destinations. The archive will be extracted -and its contents will populate the particular area specified. To upload file (which might represent a directory structure) -into a particular container: - -```php -use OpenCloud\ObjectStore\Constants\UrlType; - -$service->bulkExtract('container_1', fopen('/home/jamie/files.tar.gz','r'), UrlType::TAR_GZ); -``` - -You can also omit the container name (i.e. provide an empty string as the first argument). If you do this, the API will -create the containers necessary to house the extracted files - this is done based on the filenames inside the archive. - -## Bulk delete - -Bulk delete a set of paths: - -```php -$pathsToBeDeleted = array('/container_1/old_file', '/container_2/notes.txt', '/container_1/older_file.log'); - -$service->bulkDelete($pathsToBeDeleted); -``` +https://doc.php-opencloud.com/en/latest/services/object-store/objects.html diff --git a/docs/userguide/ObjectStore/USERGUIDE.md b/docs/userguide/ObjectStore/USERGUIDE.md index fa04bdeaf..6881ee3e6 100644 --- a/docs/userguide/ObjectStore/USERGUIDE.md +++ b/docs/userguide/ObjectStore/USERGUIDE.md @@ -1,625 +1,5 @@ # The Complete User Guide to the Object Store Service -**Object Store** is an object-based storage system that stores content and metadata as objects in a cloud. +Our docs have moved! Please visit the below link: -## Prerequisites - -### Client -To use the object store service, you must first instantiate a `OpenStack` or `Rackspace` client object. - -* If you are working with a vanilla OpenStack cloud, instantiate an `OpenCloud\OpenStack` client as shown below. - - ```php - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'apiKey' => '' - )); - ``` - -* If you are working with the Rackspace cloud, instantiate a `OpenCloud\Rackspace` client as shown below. - - ```php - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - ``` - -### Object Store Service -All operations on the object store are done via an object store service object. - -```php -$region = 'DFW'; -$objectStoreService = $client->objectStoreService(null, $region); -``` - -In the example above, you are connecting to the ``DFW`` region of the cloud. Any containers and objects created with this `$objectStoreService` instance will be stored in that cloud region. - -## Containers -A **container** defines a namespace for **objects**. An object with the same name in two different containers represents two different objects. - -For example, you may create a container called `logos` to hold all the image files for your blog. - -A container may contain zero or more objects in it. - -> **Note:** when working with names that contain non-standard alphanumerical characters (such as spaces or non-English characters), you must ensure they are encoded with [`urlencode`](http://php.net/urlencode) before passing them in - -### Create Container - -```php -$container = $objectStoreService->createContainer('logos'); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/create-container.php) ] - -### Get Container Details -You can retrieve a single container's details by using its name. An instance of `OpenCloud\ObjectStore\Resource\Container` is returned. - -```php -$container = $objectStoreService->getContainer('logos'); - -/** @var $container OpenCloud\ObjectStore\Resource\Container **/ -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-container.php) ] - -### List Containers -You can retrieve a list of all your containers. An instance of `OpenCloud\Common\Collection\PaginatedIterator` -is returned. - -```php -$containers = $objectStoreService->listContainers(); -foreach ($containers as $container) { - /** @var $container OpenCloud\ObjectStore\Resource\Container **/ -} -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/list-containers.php) ] - -### Set or Update Container Metadata -You can set metadata on a container. - -```php -$container->saveMetadata(array( - 'author' => 'John Doe' -)); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/set-container-metadata.php) ] - -### Get Container Metadata -You can retrieve the metadata for a container. - -```php -$containerMetadata = $container->getMetadata(); - -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-container-metadata.php) ] - -### Delete Container -When you no longer have a need for the container, you can remove it. - -If the container is empty (that is, it has no objects in it), you can remove it as shown below: - -```php -$container->delete(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/delete-container.php) ] - -If the container is not empty (that is, it has objects in it), you have two choices in how to remove it: - -* [Individually remove each object](#delete-object) in the container, then remove the container itself as shown above, or - -* Remove the container and all the objects within it as shown below: - - ```php - $container->delete(true); - ``` - [ [Get the executable PHP script for this example](/samples/ObjectStore/delete-container-recursive.php) ] - -### Get Object Count - -You can quickly find out how many objects are in a container. - -```php -$containerObjectCount = $container->getObjectCount(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-container-object-count.php) ] - -In the example above, `$containerObjectCount` will contain the number of objects in the container represented by `$container`. - -### Get Bytes Used - -You can quickly find out the space used by a container, in bytes. - -```php -$containerSizeInBytes = $container->getBytesUsed(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-container-bytes-used.php) ] - -In the example above, `$containerSizeInBytes` will contain the space used, in bytes, by the container represented by `$container`. - -### Container Quotas - -#### Set Quota for Number of Objects - -You can set a quota for the maximum number of objects that may be stored in a container. - -```php -$maximumNumberOfObjectsAllowedInContainer = 25; -$container->setCountQuota($maximumNumberOfObjectsAllowedInContainer); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/set-container-count-quota.php) ] - -#### Set Quota for Total Size of Objects - -You can set a quota for the maximum total space (in bytes) used by objects in a container. - -```php -use OpenCloud\Common\Constants\Size; - -$maximumTotalSizeOfObjectsInContainer = 5 * Size::GB; -$container->setBytesQuota($maximumTotalSizeOfObjectsInContainer); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/set-container-bytes-quota.php) ] - -#### Get Quota for Number of Objects - -You can retrieve the quota for the maximum number of objects that may be stored in a container. - -```php -$maximumNumberOfObjectsAllowedInContainer = $container->getCountQuota(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-container-count-quota.php) ] - -#### Get Quota for Total Size of Objects - -You can retrieve the quota for the maximum total space (in bytes) used by objects in a container. - -```php -$maximumTotalSizeOfObjectsAllowedInContainer = $container->getBytesQuota(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-container-bytes-quota.php) ] - -## Objects - -An **object** (sometimes referred to as a file) is the unit of storage in an Object Store. An object is a combination of content (data) and metadata. - -For example, you may upload an object named `php-elephant.jpg`, a JPEG image file, to the `logos` container. Further, you may assign metadata to this object to indicate that the author of this object was someone named Jane Doe. - -> **Note:** when working with names that contain non-standard alphanumerical characters (such as spaces or non-English characters), you must ensure they are encoded with [`urlencode`](http://php.net/urlencode) before passing them in - -### Upload Object - -Once you have created a container, you can upload objects to it. - -```php -$localFileName = '/path/to/local/php-elephant.jpg'; -$remoteFileName = 'php-elephant.jpg'; - -$fileData = fopen($localFileName, 'r'); -$object = $container->uploadObject($remoteFileName, $fileData); -/** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/upload-object.php) ] - -In the example above, an image file from the local filesystem (`path/to/local/php-elephant.jpg`) is uploaded to a container in the Object Store. - -Note that while we call `fopen` to open the file resource, we do not call `fclose` at the end. The file resource is automatically closed inside the `uploadObject` call. - -It is also possible to upload an object and associate metadata with it. - -```php -use OpenCloud\ObjectStore\Resource\DataObject; - -$localFileName = '/path/to/local/php-elephant.jpg'; -$remoteFileName = 'php-elephant.jpg'; -$metadata = array('author' => 'Jane Doe'); - -$customHeaders = array(); -$metadataHeaders = DataObject::stockHeaders($metadata); -$allHeaders = $customHeaders + $metadataHeaders; - -$fileData = fopen($localFileName, 'r'); -$container->uploadObject($remoteFileName, $fileData, $allHeaders); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/upload-object-with-metadata.php) ] - -Note that while we call `fopen` to open the file resource, we do not call `fclose` at the end. The file resource is automatically closed inside the `uploadObject` call. - -#### Pseudo-hierarchical Folders -Although you cannot nest directories in an Object Store, you can simulate a hierarchical structure within a single container by adding forward slash characters (`/`) in the object name. - -```php -$localFileName = '/path/to/local/php-elephant.jpg'; -$remoteFileName = 'languages/php/elephant.jpg'; - -$fileData = fopen($localFileName, 'r'); -$container->uploadObject($remoteFileName, $fileData); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/pseudo-hierarchical-folders.php) ] - -In the example above, an image file from the local filesystem (`/path/to/local/php-elephant.jpg`) is uploaded to a container in the Object Store. Within that container, the filename is `languages/php/elephant.jpg`, where `languages/php/` is a pseudo-hierarchical folder hierarchy. - -Note that while we call `fopen` to open the file resource, we do not call `fclose` at the end. The file resource is automatically closed inside the `uploadObject` call. - -#### Upload Multiple Objects -You can upload more than one object at a time to a container. - -```php -$objects = array( - array( - 'name' => 'php-elephant.jpg', - 'path' => '/path/to/local/php-elephant.jpg' - ), - array( - 'name' => 'python-snake.jpg', - 'path' => '/path/to/local/python-snake.jpg' - ), - a -); - -$responses = $container->uploadObjects($objects); -foreach ($responses as $response) { - /** @var $response \Guzzle\Http\Message\Response **/ -} -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/upload-multiple-objects.php) ] - -In the above example, the contents of two files present on the local filesystem are uploaded as objects to the container referenced by `$container`. - -Instead of specifying the `path` key in an element of the `$objects` array, you can specify a `body` key whose value is a string or a stream representation. - -You can pass headers as the second parameter to the `uploadObjects` method. These headers will be applied to every object that is uploaded. - -``` -$metadata = array('author' => 'Jane Doe'); - -$customHeaders = array(); -$metadataHeaders = DataObject::stockHeaders($metadata); -$allHeaders = $customHeaders + $metadataHeaders; - -$container->uploadObjects($objects, $allHeaders); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/upload-multiple-objects-with-metadata.php) ] - -In the example above, every object referenced within the `$objects` array will be uploaded with the same metadata. - -Finally, if you want the `uploadObjects` method to return an array of `OpenCloud\ObjectStore\Resource\DataObject` objects instead of an array of `Guzzle\Http\Message\Response` objects, you can specify a third parameter to the `uploadObjects` method: - -``` -use OpenCloud\ObjectStore\Enum\ReturnType; - -$dataObjects = $container->uploadObjects($objects, $allHeaders, ReturnType::DATA_OBJECT_ARRAY); -foreach ($dataObjects as $dataObject) { - /** @var $dataObject OpenCloud\ObjectStore\Resource\DataObject **/ -} -``` - -### Large Objects - -If you want to upload objects larger than 5GB in size, you must use a different upload process. - -```php -$options = array( - 'name' => 'san_diego_vacation_video.mp4', - 'path' => '/path/to/local/videos/san_diego_vacation.mp4' -); -$objectTransfer = $container->setupObjectTransfer($options); -$objectTransfer->upload(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/upload-large-object.php) ] - -The process shown above will automatically partition your large object into small chunks and upload them concurrently to the container represented by `$container`. - -You can tune the parameters of this process by specifying additional options in the `$options` array. Here is a complete listing of keys that can be specified in the `$options` array: - -| Key name | Description | Data Type | Required? | Default Value | Example | -| -------------- | --------------- | ------------- | -------------- | ------------------ | ----------- | -| `name` | Name of large object in container | String | Yes | - | `san_diego_vacation_video.mp4` | -| `path` | Path to file containing object data on local filesystem | String | One of `path` or `body` must be specified | - | `/path/to/local/videos/san_diego_vacation.mp4` | -| `body` | String or stream representation of object data | String \| Stream | One of `path` or `body` must be specified | - | `... lots of data ...` | -| `metadata` | Metadata for the object | Associative array of metadata key-value pairs | No | `array()` | `array( "Author" => "Jane Doe" )` | -| `partSize` | The size, in bytes, of each chunk that the large object is partitioned into prior to uploading | Integer | No | `1073741824` (1GB) | `52428800` (50MB) | -| `concurrency` | The number of concurrent transfers to execute as part of the upload | Integer | No | `1` (no concurrency; upload chunks serially) | `10` | -| `progress` | A [callable function or method](http://us1.php.net/manual/en/language.types.callable.php) which is called to report progress of the the upload. See [`CURLOPT_PROGRESSFUNCTION` documentation](http://us2.php.net/curl_setopt) for details on parameters passed to this callable function or method. | String (callable function or method name) | No | None | `reportProgress` | - -### Auto-extract Archive Files - -You can upload a tar archive file and have the Object Store service automatically extract it into a container. - -```php -use OpenCloud\ObjectStore\Constants\UrlType; - -$localArchiveFileName = '/path/to/local/image_files.tar.gz'; -$remotePath = 'images/'; - -$fileData = fopen($localArchiveFileName, 'r'); -$objectStoreService->bulkExtract($remotePath, $fileData, UrlType::TAR_GZ); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/auto-extract-archive-files.php) ] - -In the above example, a local archive file named `image_files.tar.gz` is uploaded to an Object Store container named `images` (defined by the `$remotePath` variable). - -Note that while we call `fopen` to open a file resource, we do not call `fclose` at the end. The file resource is automatically closed inside the `bulkExtract` call. - -The third parameter to `bulkExtract` is the type of the archive file being uploaded. The acceptable values for this are: - -* `UrlType::TAR` for tar archive files, *or*, -* `UrlType:TAR_GZ` for tar archive files that are compressed with gzip, *or* -* `UrlType::TAR_BZ` for tar archive file that are compressed with bzip - -Note that the value of `$remotePath` could have been a (pseudo-hierarchical folder)[#pseudo-hierarchical-folders] such as `images/blog` as well. - -### List Objects in a Container -You can list all the objects stored in a container. An instance of `OpenCloud\Common\Collection\PaginatedIterator` is returned. - -```php -$objects = $container->objectList(); -foreach ($objects as $object) { - /** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ -} -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/list-objects.php) ] - -You can list only those objects in the container whose names start with a certain prefix. - -```php -$options = array( - 'prefix' => 'php' -); - -$objects = $container->objectList($options); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/list-objects-with-prefix.php) ] - -In general, the `objectList()` method described above takes an optional parameter (`$options` in the example above). This parameter is an associative array of various options. Here is a complete listing of keys that can be specified in the `$options` array: - -| Key name | Description | Data Type | Required? | Default Value | Example | -| -------------- | --------------- | ------------- | -------------- | ------------------ | ----------- | -| `prefix` | Given a string x, limits the results to object names beginning with x. | String | No | | `php` | -| `limit` | Given an integer n, limits the number of results to at most n values. | Integer | No | | 10 | -| `marker` | Given a string x, returns object names greater than the specified marker. | String | No | | `php-elephant.jpg` | -| `end_marker` | Given a string x, returns object names less than the specified marker. | String | No | | `python-snakes.jpg` | - -### Retrieve Object -You can retrieve an object and its metadata, given the object's container and name. - -```php -$objectName = 'php-elephant.jpg'; -$object = $container->getObject($objectName); - -/** @var $object OpenCloud\ObjectStore\Resource\DataObject **/ - -$objectContent = $object->getContent(); - -/** @var $objectContent Guzzle\Http\EntityBody **/ - -// Write object content to file on local filesystem. -$objectContent->rewind(); -$stream = $objectContent->getStream(); -$localFilename = tempnam("/tmp", 'php-opencloud-'); -file_put_contents($localFilename, $stream); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-object.php) ] - -In the example above, `$object` is the object named `php-elephant.jpg` in the container represented by `$container`. Further, `$objectContent` represents the contents of the object. It is of type [`Guzzle\Http\EntityBody`](http://api.guzzlephp.org/class-Guzzle.Http.EntityBody.html). - -### Retrieve Object Metadata -You can retrieve just an object's metadata without retrieving its contents. - -```php -$objectName = 'php-elephant.jpg'; -$object = $container->getPartialObject($objectName); -$objectMetadata = $object->getMetadata(); - -/** @var $objectMetadata \OpenCloud\Common\Metadata **/ -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-object-metadata.php) ] - -In the example above, while `$object` is an instance of `OpenCloud\ObjectStore\Resource\DataObject`, that instance is only partially populated. Specifically, only properties of the instance relating to object metadata are populated. - -### Temporary URLs - -The Temporary URL feature allows you to create limited-time Internet addresses that allow you to grant limited access to your Object Store account. Using this feature, you can allow others to retrieve or place objects in your Object Store account for a specified amount of time. Access to the temporary URL is independent of whether or not your account is [CDN-enabled](#cdn-containers). Even if you do not CDN-enable a container, you can still grant temporary public access through a temporary URL. - -First, you must set the temporary URL secret on your account. This is a one-time operation; you only need to perform it the very first time you wish to use the temporary URLs feature. - -```php -$account->setTempUrlSecret(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/set-account-temp-url-secret.php) ] - -Note that this operation is carried out on `$account`, which is an instance of `OpenCloud\ObjectStore\Resource\Account`, a class representing [your object store account](#accounts). - -The above operation will generate a random secret and set it on your account. Instead of a random secret, if you wish to provide a secret, you can supply it as a parameter to the `setTempUrlSecret` method. - -```php -$account->setTempUrlSecret(''); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/set-account-temp-url-secret-specified.php) ] - -Once a temporary URL secret has been set on your account, you can generate a temporary URL for any object in your Object Store. - -```php -$expirationTimeInSeconds = 3600; // one hour from now -$httpMethodAllowed = 'GET'; -$tempUrl = $object->getTemporaryUrl($expirationTimeInSeconds, $httpMethodAllowed); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-object-temporary-url.php) ] - -In the example above, a temporary URL for the object is generated. This temporary URL will provide public access to the object for an hour (3600 seconds), as specified by the `$expirationTimeInSeconds` variable. Further, only GET HTTP methods will be allowed on this URL, as specified by the `$httpMethodAllowed` variable. The other value allowed for the `$httpMethodAllowed` variable would be `PUT`. - -You can also retrieve the temporary URL secret that has been set on your account. - -```php -$tempUrlSecret = $account->getTempUrlSecret(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-account-temp-url-secret.php) ] - -### Update Object - -You can update an object's contents (as opposed to [updating its metadata](#update-object-metadata)) by simply re-[uploading the object](#upload-object) to its container using the same object name as before. - -### Update Object Metadata - -You can update an object's metadata after it has been uploaded to a container. - -```php -$object->saveMetadata(array( - 'author' => 'John Doe' -)); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/update-object-metadata.php) ] - -### Copy Object - -You can copy an object from one container to another, provided the destination container already exists. - -```php -$object->copy('logos_copy/php.jpg'); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/copy-object.php) ] - -In the example above, both the name of the destination container (`logos_copy`)and the name of the destination object (`php.jpg`) have to be specified, separated by a `/`. - -### Delete Object - -When you no longer need an object, you can delete it. - -```php -$object->delete(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/delete-object.php) ] - -### Bulk Delete - -While you can delete individual objects as shown above, you can also delete objects and empty containers in bulk. - -```php -$objectStoreService->bulkDelete(array( - 'logos/php-elephant.png', - 'logos/python-snakes.png', - 'some_empty_container' -)); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/bulk-delete.php) ] - -In the example above, two objects (`some_container/object_a.png`, `some_other_container/object_z.png`) and one empty container (`some_empty_container`) are all being deleted in bulk via a single command. - -## CDN Containers - -Note: The functionality described in this section is available only on the Rackspace cloud. It will not work as described when working with a vanilla OpenStack cloud. - -Any container can be converted to a CDN-enabled container. When this is done, the objects within the container can be accessed from anywhere on the Internet via a URL. - -### Enable CDN Container - -To take advantage of CDN capabilities for a container and its objects, you must CDN-enable that container. - -```php -$container->enableCdn(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/enable-container-cdn.php) ] - -### Public URLs - -Once you have CDN-enabled a container, you can retrieve a publicly-accessible URL for any of its objects. There are four types of publicly-accessible URLs for each object. Each type of URL is meant for a different purpose. The sections below describe each of these URL types and how to retrieve them. - -#### HTTP URL -You can use this type of URL to access the object over HTTP. - -``` -$httpUrl = $object->getPublicUrl(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-cdn-object-http-url.php) ] - -#### Secure HTTP URL -You can use this type of URL to access the object over HTTP + TLS/SSL. - -``` -use OpenCloud\ObjectStore\Constants\UrlType; - -$httpsUrl = $object->getPublicUrl(UrlType::SSL); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-cdn-object-https-url.php) ] - -#### Streaming URL -You can use this type of URL to stream a video or audio object using Adobe's HTTP Dynamic Streaming. - -``` -use OpenCloud\ObjectStore\Constants\UrlType; - -$streamingUrl = $object->getPublicUrl(UrlType::STREAMING); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-cdn-object-streaming-url.php) ] - -#### IOS Streaming URL - -You can use this type of URL to stream an audio or video object to an iOS device. - -``` -use OpenCloud\ObjectStore\Constants\UrlType; - -$iosStreamingUrl = $object->getPublicUrl(UrlType::IOS_STREAMING); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-cdn-object-ios-streaming-url.php) ] - -### Update CDN Container TTL -You can update the TTL of a CDN-enabled container. - -```php -$cdnContainer = $container->getCdn(); -$cdnContainer->setTtl(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/set-cdn-container-ttl.php) ] - -### Disable CDN Container - -If you no longer need CDN capabilities for a container, you can disable them. - -```php -$container->disableCdn(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/disable-container-cdn.php) ] - -## Accounts -An **account** defines a namespace for **containers**. An account can have zero or more containers in it. - -### Retrieve Account -You must retrieve the account before performing any operations on it. - -```php -$account = $objectStoreService->getAccount(); -``` - -### Get Container Count - -You can quickly find out how many containers are in your account. - -```php -$accountContainerCount = $account->getContainerCount(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-account-container-count.php) ] - -### Get Object Count - -You can quickly find out how many objects are in your account. - -```php -$accountObjectCount = $account->getObjectCount(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-account-object-count.php) ] - -In the example above, `$accountObjectCount` will contain the number of objects in the account represented by `$account`. - -### Get Bytes Used - -You can quickly find out the space used by your account, in bytes. - -```php -$accountSizeInBytes = $account->getBytesUsed(); -``` -[ [Get the executable PHP script for this example](/samples/ObjectStore/get-account-bytes-used.php) ] - -In the example above, `$accountSizeInBytes` will contain the space used, in bytes, by the account represented by `$account`. +https://doc.php-opencloud.com/en/latest/services/object-store/index.html diff --git a/docs/userguide/Orchestration/README.md b/docs/userguide/Orchestration/README.md index cb3c6245a..862a61ed7 100644 --- a/docs/userguide/Orchestration/README.md +++ b/docs/userguide/Orchestration/README.md @@ -1,81 +1,5 @@ # Orchestration -**Orchestration** is a service that can be used to create and manage cloud -resources. Examples of such resources are databases, load balancers, -servers and software installed on them. +Our docs have moved! Please visit the below link: -## Concepts - -To use the Orchestration service effectively, you should understand several -key concepts: - -* **Template**: An Orchestration template is a JSON or YAML document that -describes how a set of resources should be assembled to produce a working -deployment. The template specifies what resources should be used, what -attributes of these resources are parameterized and what information is -output to the user when a template is instantiated. - -* **Resource**: A resource is a template artifact that represents some component of your desired architecture (a Cloud Server, a group of scaled Cloud Servers, a load balancer, some configuration management system, and so forth). - -* **Stack**: A stack is a running instance of a template. When a stack is created, -the resources specified in the template are created. - -## Getting started - -### 1. Instantiate an OpenStack or Rackspace client. - -To use the Orchestration service, you must first instantiate a `OpenStack` or `Rackspace` client object. - -* If you are working with an OpenStack cloud, instantiate an `OpenCloud\OpenStack` client as follows: - - ```php - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - ``` - -* If you are working with the Rackspace cloud, instantiate a `OpenCloud\Rackspace` client as follows: - - ```php - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - ``` - -### 2. Obtain an Orchestration service object from the client. -All Orchestration operations are done via an _orchestration service object_. To -instantiate this object, call the `orchestrationService` method on the `$client` -object as shown in the following example: - -```php -$region = ''; -$orchestrationService = $client->orchestrationService(null, $region); -``` - -Any stacks and resources created with this `$orchestrationService` instance will -be stored in the cloud region specified by `$region`. - -### 3. Create a stack from a template. -```php -$stack = $orchestrationService->createStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 -)); -``` - -[ [Get the executable PHP script for this example](/samples/Orchestration/quickstart.php) ] - -## Next steps - -Once you have created a stack, there is more you can do with it. See [complete user guide for orchestration](USERGUIDE.md). +https://doc.php-opencloud.com/en/latest/services/orchestration/index.html diff --git a/docs/userguide/Orchestration/USERGUIDE.md b/docs/userguide/Orchestration/USERGUIDE.md index a6d8af0f9..902d7741b 100644 --- a/docs/userguide/Orchestration/USERGUIDE.md +++ b/docs/userguide/Orchestration/USERGUIDE.md @@ -1,506 +1,5 @@ # Complete User Guide for the Orchestration Service -Orchestration is a service that you can use to create and manage cloud resources -such as databases, load balancers, and servers, and the software installed on -servers. +Our docs have moved! Please visit the below link: -## Table of Contents - -* [Concepts](#concepts) -* [Prerequisites](#prerequisites) - * [Client](#client) - * [Orchestration service](#orchestration-service) -* [Templates](#templates) - * [Validate template](#validate-template) - * [Validate a template from a file](#validate-a-template-from-a-file) - * [Validate Template from URL](#validate-template-from-url) -* [Stacks](#stacks) - * [Preview stack](#preview-stack) - * [Preview a stack from a template file](#preview-a-stack-from-a-template-file) - * [Preview a stack from a template URL](#preview-a-stack-from-a-template-url) - * [Create stack](#create-stack) - * [Create a stack from a template file](#create-a-stack-from-a-template-file) - * [Create a stack from a template URL](#create-a-stack-from-a-template-url) - * [List stacks](#list-stacks) - * [Get stack](#get-stack) - * [Get stack template](#get-stack-template) - * [Update stack](#update-stack) - * [Update a stack from a template file](#update-a-stack-from-a-template-file) - * [Update Stack from Template URL](#update-stack-from-template-url) - * [Delete stack](#delete-stack) - * [Abandon Stack](#abandon-stack) - * [Adopt stack](#adopt-stack) -* [Stack resources](#stack-resources) - * [List stack resources](#list-stack-resources) - * [Get stack resource](#get-stack-resource) - * [Get stack resource metadata](#get-stack-resource-metadata) -* [Stack resource events](#stack-resource-events) - * [List stack events](#list-stack-events) - * [List stack resource events](#list-stack-resource-events) - * [Get stack resource event](#get-stack-resource-event) -* [Resource types](#resource-types) - * [List resource types](#list-resource-types) - * [Get resource type](#get-resource-type) - * [Get resource type template](#get-resource-type-template) -* [Build info](#build-info) - * [Get build info](#get-build-info) - -## Concepts - -To use the Orchestration service effectively, you should understand the following -key concepts: - -* **Template**: A JSON or YAML document that describes how a set of resources should -be assembled to produce a working deployment. The template specifies the resources -to use, the attributes of these resources that are parameterized and the information -that is sent to the user when a template is instantiated. - -* **Resource**: Some component of your architecture (a cloud server, a group of scaled -cloud servers, a load balancer, some configuration management system, and so on) that -is defined in a template. - -* **Stack**: A running instance of a template. When a stack is created, the resources -specified in the template are created. - -## Prerequisites - -### Client -To use the Orchestration service, you must first instantiate a `OpenStack` or `Rackspace` client object. - -* If you are working with an OpenStack cloud, instantiate an `OpenCloud\OpenStack` client as follows: - - ```php - use OpenCloud\OpenStack; - - $client = new OpenStack('', array( - 'username' => '', - 'password' => '' - )); - ``` - -* If you are working with the Rackspace cloud, instantiate a `OpenCloud\Rackspace` client as follows: - - ```php - use OpenCloud\Rackspace; - - $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => '', - 'apiKey' => '' - )); - ``` - -### Orchestration service -All Orchestration operations are done via an _orchestration service object_. To -instantiate this object, call the `orchestrationService` method on the `$client` -object. This method takes two arguments: - -| Position | Description | Data type | Required? | Default value | Example value | -| -------- | ----------- | ----------| --------- | ------------- | ------------- | -| 1 | Name of the service, as it appears in the service catalog | String | No | `null`; automatically determined when possible | `cloudOrchestration` | -| 2 | Cloud region | String | Yes | - | `DFW` | - - -```php -$region = ''; -$orchestrationService = $client->orchestrationService(null, $region); -``` - -Any stacks and resources created with this `$orchestrationService` instance will -be stored in the cloud region specified by `$region`. - -## Templates -An Orchestration template is a JSON or YAML document that -describes how a set of resources should be assembled to produce a working -deployment (known as a [stack](#stacks)). The template specifies the resources -to use, the attributes of these resources that are parameterized and the -information that is sent to the user when a template is instantiated. - -### Validate template -Before you use a template to create a stack, you might want to validate it. - -#### Validate a template from a file -If your template is stored on your local computer as a JSON or YAML file, you -can validate it as shown in the following example: - -```php -use OpenCloud\Common\Exceptions\InvalidTemplateError; - -try { - $orchestrationService->validateTemplate(array( - 'template' => file_get_contents(__DIR__ . '/lamp.yaml') - )); -} catch (InvalidTemplateError $e) { - // Use $e->getMessage() for explanation of why template is invalid -} -``` - -[ [Get the executable PHP script for this example](/samples/Orchestration/validate-template-from-template-url.php) ] - -#### Validate Template from URL -If your template is stored as a JSON or YAML file in a remote location accessible -via HTTP or HTTPS, you can validate it as shown in the following example: - -```php -use OpenCloud\Common\Exceptions\InvalidTemplateError; - -try { - $orchestrationService->validateTemplate(array( - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml' - )); -} catch (InvalidTemplateError $e) { - // Use $e->getMessage() for explanation of why template is invalid -} -``` - -[ [Get the executable PHP script for this example](/samples/Orchestration/validate-template-from-template-url.php) ] - -## Stacks -A stack is a running instance of a template. When a stack is created, the -[resources](#stack-resources) specified in the template are created. - -### Preview stack -Before you create a stack from a template, you might want to see what that stack -will look like. This is called _previewing the stack_. - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, `_`, `-` or `.` characters | Yes | - | `simple-lamp-setup` | -| `template` | Template contents | String. JSON or YAML | No, if `templateUrl` is specified | `null` | `heat_template_version: 2013-05-23\ndescription: LAMP server\n` | -| `templateUrl` | URL of the template file | String. HTTP or HTTPS URL | No, if `template` is specified | `null` | `https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml` | -| `parameters` | Arguments to the template, based on the template's parameters. For example, see the parameters in [this template section](https://github.com/rackspace-orchestration-templates/lamp/blob/master/lamp.yaml#L22) | Associative array | No | `null` | `array('flavor_id' => 'general1-1')` | - -#### Preview a stack from a template file - -If your template is stored on your local computer as a JSON or YAML file, you -can use it to preview a stack as shown in the following example: - -```php -$stack = $orchestrationService->previewStack(array( - 'name' => 'simple-lamp-setup', - 'template' => file_get_contents(__DIR__ . '/lamp.yml'), - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ) -)); -/** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -``` - -[ [Get the executable PHP script for this example](/samples/Orchestration/preview-stack-from-template-file.php) ] - -#### Preview a stack from a template URL - -If your template is stored as a JSON or YAML file in a remote location accessible -via HTTP or HTTPS, you can use it to preview a stack as shown in the following -example: - -```php -$stack = $orchestrationService->previewStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ) -)); -/** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -``` - -[ [Get the executable PHP script for this example](/samples/Orchestration/preview-stack-from-template-url.php) ] - -### Create stack -You can create a stack from a template. - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `name` | Name of the stack | String. Must start with an alphabetic character, and must contain only alphanumeric, `_`, `-` or `.` characters. | Yes | - | `simple-lamp-setup` | -| `template` | Template contents | String. JSON or YAML | No, if `templateUrl` is specified | `null` | `heat_template_version: 2013-05-23\ndescription: LAMP server\n` | -| `templateUrl` | URL of template file | String. HTTP or HTTPS URL | No, if `template` is specified | `null` | `https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml` | -| `parameters` | Arguments to the template, based on the template's parameters | Associative array | No | `null` | `array('server_hostname' => 'web01')` | -| `timeoutMins` | Duration, in minutes, after which stack creation should time out | Integer | Yes | - | 5 | - -#### Create a stack from a template file - -If your template is stored on your local computer as a JSON or YAML file, you -can use it to create a stack as shown in the following example: - -```php -$stack = $orchestrationService->createStack(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 -)); -/** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/create-stack-from-template-file.php) ] - -#### Create a stack from a template URL -If your template is stored as a JSON or YAML file in a remote location accessible -via HTTP or HTTPS, you can use it to create a stack as shown in the following -example: - -```php -$stack = $orchestrationService->stack(); -$stack->create(array( - 'name' => 'simple-lamp-setup', - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 -)); -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/create-stack-from-template-url.php) ] - -### List stacks -You can list all the stacks that you have created as shown in the following example: - -```php -$stacks = $orchestrationService->listStacks(); -foreach ($stacks as $stack) { - /** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/list-stacks.php) ] - -### Get stack -You can retrieve a specific stack using its name, as shown in the following example: - -```php -$stack = $orchestrationService->getStack('simple-lamp-setup'); -/** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-stack.php) ] - -### Get stack template -You can retrieve the template used to create a stack. Note that a JSON string is -returned, regardless of whether a JSON or YAML template was used to create the stack. - -```php -$stackTemplate = $stack->getTemplate(); -/** @var $stackTemplate string **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-stack-template.php) ] - -### Update stack -You can update a running stack. - -This operation takes one parameter, an associative array, with the following keys: - -| Name | Description | Data type | Required? | Default value | Example value | -| ---- | ----------- | --------- | --------- | ------------- | ------------- | -| `template` | Template contents | String. JSON or YAML | No, if `templateUrl` is specified | `null` | `heat_template_version: 2013-05-23\ndescription: LAMP server\n` | -| `templateUrl` | URL of template file | String. HTTP or HTTPS URL | No, if `template` is specified | `null` | `https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml` | -| `parameters` | Arguments to the template, based on the template's parameters | Associative array | No | `null`| `array('flavor_id' => 'general1-1')` | -| `timeoutMins` | Duration, in minutes, after which stack update should time out | Integer | Yes | - | 5 | - -#### Update a stack from a template file - -If your template is stored on your local computer as a JSON or YAML file, you -can use it to update a stack as shown in the following example: - -```php -$stack->update(array( - 'template' => file_get_contents(__DIR__ . '/lamp-updated.yml'), - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 -)); -/** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/update-stack-from-template-file.php) ] - -#### Update Stack from Template URL - -If your template is stored as a JSON or YAML file in a remote location accessible -via HTTP or HTTPS, you can use it to update a stack as shown in the following -example: - -```php -$stack->update(array( - 'templateUrl' => 'https://raw.githubusercontent.com/rackspace-orchestration-templates/lamp/master/lamp-updated.yaml', - 'parameters' => array( - 'server_hostname' => 'web01', - 'image' => 'Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM)' - ), - 'timeoutMins' => 5 -)); -/** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/update-stack-from-template-url.php) ] - -### Delete stack - -If you no longer need a stack and all its resources, you can delete the stack -_and_ the resources as shown in the following example: - -```php -$stack->delete(); -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/delete-stack.php) ] - -### Abandon Stack - -If you want to delete a stack but preserve all its resources, you can abandon -the stack as shown in the following example: - -```php -$abandonStackData = $stack->abandon(); -/** @var $abandonStackData string **/ - -file_put_contents(__DIR__ . '/sample_adopt_stack_data.json', $abandonStackData); -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/abandon-stack.php) ] - -Note that this operation returns data about the abandoned stack as a string. You -can use this data to recreate the stack by using the [adopt stack](#adopt-stack) -operation. - -### Adopt stack - -If you have data from an abandoned stack, you can re-create the stack as shown -in the following example: - -```php -$stack = $orchestrationService->adoptStack(array( - 'name' => 'simple-lamp-setup', - 'template' => file_get_contents(__DIR__ . '/lamp.yml'), - 'adoptStackData' => $abandonStackData, - 'timeoutMins' => 5 -)); -/** @var $stack OpenCloud\Orchestration\Resource\Stack **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/adopt-stack.php) ] - -## Stack resources - -A stack is made up of zero or more resources such as databases, load balancers, -and servers, and the software installed on servers. - -### List stack resources - -You can list all the resources for a stack as shown in the following example: - -```php -$resources = $stack->listResources(); -foreach ($resources as $resource) { - /** @var $resource OpenCloud\Orchestration\Resource\Resource **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/list-stack-resources.php) ] - -### Get stack resource - -You can retrieve a specific resource in a stack bt using that resource's name, -as shown in the following example: - -```php -$resource = $stack->getResource('load-balancer'); -/** @var $resource OpenCloud\Orchestration\Resource\Resource **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-stack-resource.php) ] - -### Get stack resource metadata - -You can retrieve the metadata for a specific resource in a stack as shown in the -following example: - -```php -$resourceMetadata = $resource->getMetadata(); -/** @var $resourceMetadata \stdClass **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-stack-resource-metadata.php) ] - -## Stack resource events -Operations on resources within a stack (such as the creation of a resource) produce -events. - -### List stack events -You can list all of the events for all of the resources in a stack as shown in -the following example: - -```php -$stackEvents = $stack->listEvents(); -foreach ($stackEvents as $stackEvent) { - /** @var $stackEvent OpenCloud\Orchestration\Resource\Event **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/list-stack-events.php) ] - -### List stack resource events -You can list all of the events for a specific resource in a stack as shown in the -following example: - -```php -$resourceEvents = $resource->listEvents(); -foreach ($resourceEvents as $resourceEvent) { - /** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/list-stack-resource-events.php) ] - -### Get stack resource event -You can retrieve a specific event for a specific resource in a stack, by using -the resource event's ID, as shown in the following example: - -```php -$resourceEvent = $resource->getEvent('c1342a0a-59e6-4413-9af5-07c9cae7d729'); -/** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-stack-resource-event.php) ] - -## Resource types -When you define a template, you must use resource types supported by your cloud. - -### List resource types -You can list all supported resource types as shown in the following example: - -```php -$resourceTypes = $orchestrationService->listResourceTypes(); -foreach ($resourceTypes as $resourceType) { - /** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/list-resource-types.php) ] - -### Get resource type -You can retrieve a specific resource type's schema as shown in the following example: - -```php -$resourceType = $orchestrationService->getResourceType('OS::Nova::Server'); -/** @var $resourceType OpenCloud\Orchestration\Resource\ResourceType **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-resource-type.php) ] - -### Get resource type template -You can retrieve a specific resource type's representation as it would appear -in a template, as shown in the following example: - -```php -$resourceTypeTemplate = $resourceType->getTemplate(); -/** @var $resourceTypeTemplate string **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-resource-type-template.php) ] - -## Build info - -### Get build info -You can retrieve information about the current Orchestration service build as -shown in the following example: - -```php -$buildInfo = $orchestrationService->getBuildInfo(); -/** @var $resourceType OpenCloud\Orchestration\Resource\BuildInfo **/ -``` -[ [Get the executable PHP script for this example](/samples/Orchestration/get-build-info.php) ] +https://doc.php-opencloud.com/en/latest/services/orchestration/index.html diff --git a/docs/userguide/Queues/Claim.md b/docs/userguide/Queues/Claim.md index dbaa53ba9..0e338956c 100644 --- a/docs/userguide/Queues/Claim.md +++ b/docs/userguide/Queues/Claim.md @@ -1,123 +1,5 @@ ## 1. Introduction -A __Claim__ is the process of a worker checking out a message to perform a task. Claiming a message prevents other -workers from attempting to process the same messages. +Our docs have moved! Please visit the below link: -## 2. Setup - -A Claim is initialized on its parent object, a Queue: - -```php -// To initialize an empty object: -$claim = $queue->getClaim(); - -// or retrieve a specific claim: -$claim = $queue->getClaim('51db7067821e727dc24df754'); -``` - -## 3. Claim messages - -### 3.1 Description - -This operation claims a set of messages (up to the value of the limit parameter) from oldest to newest and skips any -messages that are already claimed. If no unclaimed messages are available, the API returns a `204 No Content` message. - -When a client (worker) finishes processing a message, it should delete the message before the claim expires to ensure -that the message is processed only once. As part of the delete operation, workers should specify the claim ID (which is -best done by simply using the provided href). If workers perform these actions, then if a claim simply expires, the -server can return an error and notify the worker of the race condition. This action gives the worker a chance to roll -back its own processing of the given message because another worker can claim the message and process it. - -The age given for a claim is relative to the server's clock. The claim's age is useful for determining how quickly -messages are getting processed and whether a given message's claim is about to expire. - -When a claim expires, it is released. If the original worker failed to process the message, another client worker can -then claim the message. - -### 3.2 Attributes - -The `ttl` attribute specifies how long the server waits before releasing the claim. The ttl value must be between 60 and -43200 seconds (12 hours). You must include a value for this attribute in your request. - -The `grace` attribute specifies the message grace period in seconds. The value of grace value must be between 60 and -43200 seconds (12 hours). You must include a value for this attribute in your request. To deal with workers that have -stopped responding (for up to 1209600 seconds or 14 days, including claim lifetime), the server extends the lifetime of -claimed messages to be at least as long as the lifetime of the claim itself, plus the specified grace period. If a -claimed message would normally live longer than the grace period, its expiration is not adjusted. - -The `limit` attribute specifies the number of messages to return, up to 20 messages. If limit is not specified, limit - defaults to 10. The limit parameter is optional. - -### 3.3 Code - -```php -use OpenCloud\Common\Constants\Datetime; - -$queue->claimMessages(array( - 'limit' => 15, - 'grace' => 5 * Datetime::MINUTE, - 'ttl' => 5 * Datetime::MINUTE -)); -``` - -## 4. Query claim - -### 4.1 Description - -This operation queries the specified claim for the specified queue. Claims with malformed IDs or claims that are not -found by ID are ignored. - -### 4.2 Attributes - -Claim ID. - -### 4.3 Code - -```php -$claim = $queue->getClaim('51db7067821e727dc24df754'); -``` - -## 5. Update claim - -### 5.1 Description - -This operation updates the specified claim for the specified queue. Claims with malformed IDs or claims that are not -found by ID are ignored. - -Clients should periodically renew claims during long-running batches of work to avoid losing a claim while processing a -message. The client can renew a claim by executing this method on a specific __Claim__ and including a new TTL. The API - will then reset the age of the claim and apply the new TTL. - -### 5.2 Attributes - -See section 4.2. - -### 5.3 Code - -```php -use OpenCloud\Common\Constants\Datetime; - -$claim->update(array( - 'ttl' => 10 * Datetime::MINUTE -)); -``` - -## 6. Release claim - -### 6.1 Description - -This operation immediately releases a claim, making any remaining undeleted messages that are associated with the -claim available to other workers. Claims with malformed IDs or claims that are not found by ID are ignored. - -This operation is useful when a worker is performing a graceful shutdown, fails to process one or more messages, or is -taking longer than expected to process messages, and wants to make the remainder of the messages available to other workers. - -### 6.2 Attributes - -See section 4.2. - -### 6.3 Code - -```php -$message->delete(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/queues/claims.html diff --git a/docs/userguide/Queues/Message.md b/docs/userguide/Queues/Message.md index d27f2fbbf..ce0f54b07 100644 --- a/docs/userguide/Queues/Message.md +++ b/docs/userguide/Queues/Message.md @@ -1,207 +1,5 @@ ## 1. Introduction -A __Message__ is a task, a notification, or any meaningful data that a producer or publisher sends to the queue. A -message exists until it is deleted by a recipient or automatically by the system based on a TTL (time-to-live) value. +Our docs have moved! Please visit the below link: -## 2. Setup - -A message is initialized from its parent object, a Queue: - -```php -// Setup an empty object -$message = $queue->getMessage(); - -// or retrieve an existing one -$message = $queue->getMessage(''); -``` - -## 3. Post message - -### 3.1 Description - -This operation posts the specified message or messages. You can submit up to 10 messages in a single request. - -When posting new messages, you specify only the `body` and `ttl` for the message. The API will insert metadata, such as -ID and age. - -### 3.2 Parameters - -How you pass through the array structure depends on whether you are executing multiple (3.3.2) or single (3.3.3) posts, -but the keys are the same. - -The `body` attribute specifies an arbitrary document that constitutes the body of the message being sent. The size of -this body is limited to 256 KB, excluding whitespace. - -The `ttl` attribute specifies how long the server waits before marking the message as expired and removing it from the -queue. The value of ttl must be between 60 and 1209600 seconds (14 days). Note that the server might not actually -delete the message until its age has reached up to (ttl + 60) seconds, to allow for flexibility in storage implementations. - -### 3.3 Code samples - -#### 3.3.1 Posting a single message - -``` -use OpenCloud\Common\Constants\Datetime; - -$queue->createMessage(array( - 'body' => (object) array( - 'event' => 'BackupStarted', - 'deadline' => '26.12.2013 - ), - 'ttl' => 2 * Datetime::DAY -)); -``` - -#### 3.3.2 Post a batch of messages - -Please note that the list of messages will be truncated at 10. For more, please execute another method call. - -```php -use OpenCloud\Common\Constants\Datetime; - -$messages = array( - array( - 'body' => (object) array( - 'play' => 'football' - ), - 'ttl' => 2 * Datetime::DAY - ), - array( - 'body' => (object) array( - 'play' => 'tennis' - ), - 'ttl' => 50 * Datetime::HOUR - ) -); - -$queue->createMessages($messages); -``` - -## 4. Get messages - -### 4.1 Description - -This operation gets the message or messages in the specified queue. - -Message IDs and markers are opaque strings. Clients should make no assumptions about their format or length. Furthermore, -clients should assume that there is no relationship between markers and message IDs (that is, one cannot be derived -from the other). This allows for a wide variety of storage driver implementations. - -Results are ordered by age, oldest message first. - -### 4.2 Parameters - -A hash of options. - -|Name|Style|Type|Description| -|----|----|----|----| -|marker|Query|String|Specifies an opaque string that the client can use to request the next batch of messages. The marker parameter communicates to the server which messages the client has already received. If you do not specify a value, the API returns all messages at the head of the queue (up to the limit). Optional.| -|limit|Query|Integer|When more messages are available than can be returned in a single request, the client can pick up the next batch of messages by simply using the URI template parameters returned from the previous call in the "next" field. Specifies up to 10 messages (the default value) to return. If you do not specify a value for the limit parameter, the default value of 10 is used. Optional.| -|echo|Query|Boolean|Determines whether the API returns a client's own messages. The echo parameter is a Boolean value (true or false) that determines whether the API returns a client's own messages, as determined by the uuid portion of the User-Agent header. If you do not specify a value, echo uses the default value of false. If you are experimenting with the API, you might want to set echo=true in order to see the messages that you posted. The echo parameter is optional. -|include_claimed|Query|​Boolean|Determines whether the API returns claimed messages and unclaimed messages. The include_claimed parameter is a Boolean value (true or false) that determines whether the API returns claimed messages and unclaimed messages. If you do not specify a value, include_claimed uses the default value of false (only unclaimed messages are returned). Optional. - -### 4.3 Code sample - -```php -$messages = $queue->listMessages(array( - 'marker' => '51db6f78c508f17ddc924357', - 'limit' => 20, - 'echo' => true -)); - -while ($message = $messages->next()) { - echo $message->getId() . PHP_EOL; -} -``` - -## 5. Get a set of messages by ID - -### 5.1 Description - -This operation provides a more efficient way to query multiple messages compared to using a series of individual GET. -Note that the list of IDs cannot exceed 20. If a malformed ID or a nonexistent message ID is provided, it is ignored, -and the remaining messages are returned. - -### 5.2 Parameters - -A hash of options. - -|Name|Style|Type|Description| -|----|-----|----|-----------| -|ids|Query|String|Specifies the IDs of the messages to get. Format multiple message ID values by separating them with -commas (comma-separated). Optional.| -|claim_id|Query|​String|Specifies the claim ID with which the message is associated. Optional.| -|----|-----|----|-----------| - -### 5.3 Code sample - -```php -$ids = array('51db6f78c508f17ddc924357', 'f5b8c8a7c62b0150b68a50d6'); - -$messages = $queue->listMessages(array('ids' => $ids)); - -while ($message = $messages->next()) { - echo $message->getId() . PHP_EOL; -} -``` - -## 6. Delete a set of messages by ID - -### 6.1 Description - -This operation immediately deletes the specified messages. If any of the message IDs are malformed or non-existent, -they are ignored. The remaining valid messages IDs are deleted. - -### 6.2 Parameters - -An array of IDs. - -### 6.3 Code sample - -```php -$ids = array('51db6f78c508f17ddc924357', 'f5b8c8a7c62b0150b68a50d6'); - -$response = $queue->deleteMessages($ids); -``` - -## 7. Get a specific message - -### 7.1 Description - -This operation gets the specified message from the specified queue. - -### 7.2 Parameters - -Message ID. - -### 7.3 Object properties - -`href` is an opaque relative URI that the client can use to uniquely identify a message resource and interact with it. - -`ttl` is the TTL that was set on the message when it was posted. The message expires after (ttl - age) seconds. - -`age` is the number of seconds relative to the server's clock. - -`body` is the arbitrary document that was submitted with the original request to post the message. - -### 7.4 Code sample - -```php -$message = $queue->getMessage('51db6f78c508f17ddc924357'); -``` - -## 8. Delete message - -### 8.1 Description - -This operation immediately deletes the specified message. - -### 8.2 Parameters - -None. - -### 8.3 Code sample - -```php -$message->delete(); -``` +https://doc.php-opencloud.com/en/latest/services/queues/messages.html diff --git a/docs/userguide/Queues/Queue.md b/docs/userguide/Queues/Queue.md index 16290f445..01bb95e74 100644 --- a/docs/userguide/Queues/Queue.md +++ b/docs/userguide/Queues/Queue.md @@ -1,156 +1,5 @@ ## 1. Introduction -A Queue is an entity that holds messages. Ideally, a queue is created per work type. For example, if you want to -compress files, you would create a queue dedicated to this job. Any application that reads from this queue would only -compress files. +Our docs have moved! Please visit the below link: -## 2. Setup - -```php -$service = $client->queuesService('cloudQueues', 'ORD'); -``` - -## 3. Client IDs - -With most of Marconi's operation, you must specify a __Client ID__ which will be used as a unique identifier for the -process accessing this Queue. This is basically a UUID that must be unique to each client accessing the API - it can be -an arbitrary string. - -```php -$service->setClientId(); - -echo $service->getClientId(); -``` - -If you call `setClientId` without any parameters, a UUID is automatically generated for you. - -## 4. List queues - -### 4.1 Description - -This operation lists queues for the project. The queues are sorted alphabetically by name. - -### 4.2 Parameters - -|Name|Style|Type|Description| -|----|-----|----|-----------| -|marker|Query|​String|Specifies the name of the last queue received in a previous request, or none to get the first page - of results. Optional.| -|limit|Query|Integer|Specifies the number of queues to return. The default value for the number of queues returned is -10. If you do not specify this parameter, the default number of queues is returned. Optional.| -|detailed|Query|​Boolean|Determines whether queue metadata is included in the response. The default value for this - parameter is false, which excludes the metadata. Optional.| - |----|-----|----|-----------| - -### 4.3 Code sample - -```php -$queues = $service->listQueues(); - -while ($queue = $queues->next()) { - echo $queue->getName() . PHP_EOL; -} -``` - -## 5. Create queue - -### 5.1 Description - -This operation creates a new queue. - -### 5.2 Parameters - -A string representation of the name for your new Queue. The name must not exceed 64 bytes in length, and it is limited -to US-ASCII letters, digits, underscores, and hyphens. - -### 5.3 Code sample - -```php -$queue = $service->createQueue('new_queue'); -``` - -## 6. Retrieve queue - -### 6.1 Description - -Returns a `Queue` object for use. - -### 6.2 Parameters - -Queue name. - -### 6.3 Code sample - -```php -$queue = $service->getQueue('new_queue'); -``` - -## 7. Check queue existence - -### 7.1 Description - -This operation verifies whether the specified queue exists by returning `TRUE` or `FALSE`. - -### 7.2 Parameters - -### 7.3 Code sample - -```php -if ($service->hasQueue('new_queue')) { - // do something -} -``` - -## 8. Update queue metadata (permanently to the API) - -### 4.1 Description - -This operation replaces any existing metadata document in its entirety. Ensure that you do not accidentally overwrite -existing metadata that you want to retain. If you want to _append_ metadata, ensure you merge a new array to the -existing values. - -### 4.2 Parameters - -Hash of key pairs. - -### 4.3 Code sample - -```php -$queue->saveMetadata(array( - 'foo' => 'bar' -)); -``` - -## 9. Retrieve the queue metadata (fresh from the API) - -### 4.1 Description - -This operation returns metadata, such as message TTL, for the queue. - -### 4.2 Parameters - -None. - -### 4.3 Code sample - -```php -$metadata = $queue->retrieveMetadata(); - -print_r($metadata->toArray()); -``` - -## 10. Get queue stats - -### 4.1 Description - -This operation returns queue statistics, including how many messages are in the queue, categorized by status. - -### 4.2 Parameters - -None. - -### 4.3 Code sample - -```php -$queue->getStats(); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/queues/queues.html diff --git a/docs/userguide/README.md b/docs/userguide/README.md index 934951e24..0be239d94 100644 --- a/docs/userguide/README.md +++ b/docs/userguide/README.md @@ -1,74 +1,5 @@ # Table of contents -## Auto Scale -- [Groups](/docs/userguide/Autoscale/Groups.md) -- [Policies](/docs/userguide/Autoscale/Policies.md) -- [Webhooks](/docs/userguide/Autoscale/Webhooks.md) +Our docs have moved! Please visit the below link: -## Cloud Monitoring -- [Agents](/docs/userguide/CloudMonitoring/Agents.md) -- [Alarms](/docs/userguide/CloudMonitoring/Alarms.md) -- [Changelogs](/docs/userguide/CloudMonitoring/Changelogs.md) -- [Checks](/docs/userguide/CloudMonitoring/Checks.md) -- [Entities](/docs/userguide/CloudMonitoring/Entities.md) -- [Metrics](/docs/userguide/CloudMonitoring/Metrics.md) -- [Notifications](/docs/userguide/CloudMonitoring/Notifications.md) -- [Views](/docs/userguide/CloudMonitoring/Views.md) -- [Zones](/docs/userguide/CloudMonitoring/Zones.md) - -## Compute -- [Servers](/docs/userguide/Compute/Server.md) -- [Images](/docs/userguide/Compute/Images.md) -- [Flavors](/docs/userguide/flavors.md) -- [Keypairs](/docs/userguide/Compute/Keypairs.md) - -## DNS -- [Records](/docs/userguide/DNS/Records.md) -- [Domains](/docs/userguide/DNS/Domains.md) -- [Reverse DNS](/docs/userguide/DNS/Reverse-DNS.md) - -## Databases -- [Getting Started](/docs/userguide/Database/README.md) - -## Identity -- [Users](/docs/userguide/Identity/Users.md) -- [Roles](/docs/userguide/Identity/Roles.md) -- [Tokens](/docs/userguide/Identity/Tokens.md) -- [Tenants](/docs/userguide/Identity/Tenants.md) - -## Images -- [Images](/docs/userguide/Image/Images.md) -- [Sharing](/docs/userguide/Image/Sharing.md) -- [Tagging](/docs/userguide/Image/Tags.md) - -## Load Balancers -- [Getting Started](/docs/userguide/LoadBalancer/README.md) -- [Complete userguide](/docs/userguide/LoadBalancer/USERGUIDE.md) - -## Networking -- [Getting Started](/docs/userguide/Networking/README.md) -- [Complete userguide](/docs/userguide/Networking/USERGUIDE.md) - -## Object Store -- [Objects](/docs/userguide/ObjectStore/Storage/Object.md) -- [Containers](/docs/userguide/ObjectStore/Storage/Container.md) -- [Migrating containers across regions](/docs/userguide/ObjectStore/Storage/Migrating.md) -- [Access control](/docs/userguide/ObjectStore/Access.md) -- [Accounts](/docs/userguide/ObjectStore/Account.md) -- [CDN-enabled containers](/docs/userguide/ObjectStore/CDN/Container.md) -- [Purging objects from the CDN](/docs/userguide/ObjectStore/CDN/Object.md) - -## Orchestration -- [Getting Started](/docs/userguide/Orchestration/README.md) -- [Complete userguide](/docs/userguide/Orchestration/USERGUIDE.md) - -## Queues -- [Queues](/docs/userguide/Queues/Queue.md) -- [Messages](/docs/userguide/Queues/Message.md) -- [Claims](/docs/userguide/Queues/Claim.md) - -## Miscelleneous -- [Client setup](/docs/userguide/Clients.md) -- [Debugging](/docs/userguide/Debugging.md) -- [Iterators](/docs/userguide/Iterators.md) -- [Caching credentials](/docs/userguide/caching-credentials.md) +https://doc.php-opencloud.com/en/latest/index.html diff --git a/docs/userguide/Services.md b/docs/userguide/Services.md index 6f67222a2..9c9946e34 100644 --- a/docs/userguide/Services.md +++ b/docs/userguide/Services.md @@ -1,47 +1,5 @@ # Services -Both OpenStack and Rackspace are comprised of different services: Compute (Nova), -Object Storage (Swift), Queues (Marconi), etc. Each of these services is -encapsulated in its own class which implements the -`OpenCloud\Common\Service\ServiceInterface` interface. +Our docs have moved! Please visit the below link: -Each service class is nested in its own namespace: - -Service|OpenStack codename|FQCN ----|---|--- -Compute|Nova|`OpenCloud\Compute\Service` -Object Storage|Swift|`OpenCloud\ObjectStore\Service` -Identity|Keystone|`OpenCloud\Identity\Service` -Queues|Marconi|`OpenCloud\Queues\Service` - -## Instantiating a service - -The easiest way to instantiate a service, is using the convenient factory -methods of the client class. For more information about clients, see the -[client documentation](Clients.md). - -To create a Compute service, for example: - -```php -$service = $client->computeService('cloudServersOpenStack', 'DFW'); -``` - -### Method arguments - -As you will notice, each factory method accepts three arguments: - -Position|Name|Required?|Type|Description ----|---|---|---|--- -1|Service name|Yes|string|The name of the service as it appears in the [Service Catalog](https://github.com/rackspace/php-opencloud/blob/master/docs/userguide/Clients.md#service-catalog) -2|Region|Yes|string|The region you want your service to operate in -3|URL type|No|enum|Each service has two different URL types for API transactions: a public URL (i.e. over the Internet) and a private URL (through Rackspace's private network). Private URL's are beneficial because they have lower latency and incur no bandwidth charges; the only condition is that you are communicating to the API from the **same geographic region** (i.e. from a Cloud Serve in the same region).

The accepted options you may pass in are either `OpenCloud\Common\Constants\Service::INTERNAL_URL` or `OpenCloud\Common\Constants\Service::PUBLIC_URL`. - - -## Differences between OpenStack and Rackspace - -Not all of Rackspace's services are supported by OpenStack; examples include: -Cloud Databases, Auto Scale, Load Balancers, DNS, etc. - -For this reason, if you want to use or interact with these Rackspace-only -services, you must do so by using the methods of the `OpenCloud\Rackspace` -client object and **not** the `OpenCloud\OpenStack` client. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/index.html diff --git a/docs/userguide/accessip.md b/docs/userguide/accessip.md index 60c89b606..5002ef8de 100644 --- a/docs/userguide/accessip.md +++ b/docs/userguide/accessip.md @@ -1,51 +1,6 @@ About the Access IP Addresses ============================= -OpenStack deployments generally provide new [servers](servers.md) with one -or two network interfaces, each with its own address(es). Usually, one of -these will be a public interface, with its addresses available on the Internet. +Our docs have moved! Please visit the below link: -However, in some cases, the servers are created on an internal network -(this is especially common in a hybrid solution where physical and virtual -servers are intermixed). The servers may be behind a NAT device, firewall, -or other network device that prohibits direct access to the server itself. - -The `OpenCloud\Compute\Resource\Server` object provides two attributes that are -used to instruct applications what IP address to use. These are called the -*access IP* addresses, and they are, in essence, documentation strings used to -direct applications to the correct network address. They can be changed at will -by the server's owner, and OpenStack Nova does not perform any validation on -them: - -* `accessIPv4` holds the IPv4 access address, and -* `accessIPv6` holds the IPv6 access address. - -### Updating the access IP address(es) - -For example, you may have a private cloud with internal addresses in the -10.1.x range. However, you can access a server via a firewall device at -address 50.57.94.244. In this case, you can change the `accessIPv4` attribute -to point to the firewall: - -```php -$server->update(array('accessIPv4' => '50.57.94.244')); -``` - -When a client application retrieves the server's information, it will know -that it needs to use the `accessIPv4` address to connect to the server, and -*not* the IP address assigned to one of the network interfaces. - -### Retrieving the server's IP address - -The `Server::ip()` method is used to retrieve the server's IP address. -It has one optional parameter: the format (either IPv4 or IPv6) of the address -to return (by default, it returns the IPv4 address): - -```php -// IPv4 -echo $server->ip(); -echo $server->ip(4); - -// IPv6 -echo $server->ip(6); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/compute/servers.html diff --git a/docs/userguide/caching-credentials.md b/docs/userguide/caching-credentials.md index d38d69937..365e6997e 100644 --- a/docs/userguide/caching-credentials.md +++ b/docs/userguide/caching-credentials.md @@ -1,39 +1,5 @@ # Caching credentials -You can speed up your API operations by caching your credentials in a (semi-)permanent location, such as your -DB or local filesystem. This enable subsequent requests to access a shared resource, instead of repetitively having to -re-authenticate on every thread of execution. +Our docs have moved! Please visit the below link: -Tokens are valid for 24 hours, so you can effectively re-use the same cached value for that period. If you try to use -a cached version that has expired, an authentication request will be made. - -## Filesystem example - -In this example, credentials will be saved to a file in the local filesystem. Be sure to exclude it from your VCS. - -```php -use OpenCloud\Rackspace; - -$client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array( - 'username' => 'foo', - 'apiKey' => 'bar' -)); - -$cacheFile = __DIR__ . '/.opencloud_token'; - -// If the cache file exists, try importing it into the client -if (file_exists($cacheFile)) { - $data = unserialize(file_get_contents($cacheFile)); - $client->importCredentials($data); -} - -$token = $client->getTokenObject(); - -// If no token exists, or the current token is expired, re-authenticate and save the new token to disk -if (!$token || ($token && $token->hasExpired())) { - $client->authenticate(); - file_put_contents($cacheFile, serialize($client->exportCredentials())); -} -``` - -In tests, the above code shaved about 1-2s off the execution time. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/caching-creds.html diff --git a/docs/userguide/dbaas.md b/docs/userguide/dbaas.md index 8a8a05176..48d108014 100644 --- a/docs/userguide/dbaas.md +++ b/docs/userguide/dbaas.md @@ -1,319 +1,6 @@ Working with Cloud Databases ============================ -Cloud Databases is a "database-as-a-service" product offered by Rackspace. Since it is -not an official OpenStack project, it is only available via Rackspace connections, -and *not* through an OpenStack connection. +Our docs have moved! Please visit the below link: -## Setup - -```php -$service = $client->databaseService('cloudDatabases', 'ORD'); -``` - -For more information about setting up client objects, see the -[client documentation](Clients.md). For more information about service objects, -including a full list of expected arguments, see the -[service documentation](Services.md). - -## Instances - -A database instance is an isolated MySQL instance in a single tenant environment -on a shared physical host machine. Also referred to as instance. - -### Create a new Instance - -```php -// Create an empty OpenCloud\Database\Resource\Instance object -$instance = $service->instance(); - -// Send to the API -$instance->create(array( - // Pass in a name for your database instance - 'name' => '', - // Pass in a particular flavor object - 'flavor' => $service->flavor(''), - // Specify a 4GB volume - 'volume' => array('size' => 4) -)); -``` -[ [Get the executable PHP script for this example](/samples/Database/create-instance.php) ] - -### Retrieving an instance - -```php -$instance = $service->instance(''); -``` -[ [Get the executable PHP script for this example](/samples/Database/get-instance.php) ] - -### Updating an instance -An instance can be updated to use a specific [configuration](#configurations) as shown below. - -```php -$instance->update(array( - 'configuration' => '' -)); -``` - -**Note:** If any parameters in the associated configuration require a restart, then -you will need to [restart the instance](#restarting-an-instance) after the update. - -### Deleting an instance - -```php -$instance->delete(); -``` - -### Restarting an instance - -```php -$instance->restart(); -``` - -### Resizing an instance - -There are two methods for resizing an instance. The first, `resize()`, changes the amount -of RAM allocated to the instance: - -```php -$flavor = $service->flavor(''); -$instance->resize($flavor); -``` - -You can also independently change the volume size to increase the disk space: - -```php -// Increase to 8GB disk -$instance->resizeVolume(8); -``` - -## Databases - -Instances can have multiple databases; the `OpenCloud\Database\Resource\Database` -class corresponds to a single MySQL database. - -### Creating a new database - -To create a new database, you must supply it with a name; you can optionally -specify its character set and collating sequence: - -```php -// Create a new OpenCloud\Database\Resource\Database object -$database = $instance->database(); - -// Send to API -$database->create(array( - 'name' => 'production', - 'character_set' => 'utf8', - 'collate' => 'utf8_general_ci' -)); -``` - -You can find values for `character_set` and `collate` at -[the MySQL website](http://dev.mysql.com/doc/refman/5.0/en/charset-mysql.html). - -### Deleting a database - -```php -$database->delete(); -``` - -Note that this is destructive; all your data will be wiped away and will not be -retrievable. - -### Listing databases - -```php -$databases = $service->databaseList(); - -foreach ($databases as $database) { - /** @param $database OpenCloud\Database\Resource\Database */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](Iterators.md). - -### Creating users - -Database users exist at the `Instance` level, but can be associated with a specific -`Database`. They are represented by the `OpenCloud\Database\Resource\User` class. - -Users cannot be altered after they are created, so they must be assigned to -databases when they are created: - -```php -// New instance of OpenCloud\Database\Resource\User -$user = $instance->user(); - -// Send to API -$user->create(array( - 'name' => 'Alice', - 'password' => 'fooBar' - 'databases' => array('production') -)); -``` - -If you need to add a new database to a user after it's been created, you must -delete the user and then re-add it. - -### Deleting users - -```php -$user->delete(); -``` - -## The root user - -By default, Cloud Databases does not enable the root user. In most cases, the root -user is not needed, and having one can leave you open to security violations. However, -if you want to enable access to the root user, the `enableRootUser()` method is -available: - -```php -$rootUser = $instance->enableRootUser(); -``` - -This returns a regular `User` object with the `name` attribute set to `root` and the -`password` attribute set to an auto-generated password. - -To check if the root user is enabled, use the `isRootEnabled()` method. - -## Configurations - -Configurations are groups of settings that can be [applied to instances](#updating-an-instance). - -### Creating a configuration -You can create a new configuration as shown below: - -```php -$configuration = $service->configuration(); -$configuration->create(array( - 'name' => 'example-configuration-name', - 'description' => 'An example configuration', - 'values' => array( - 'collation_server' => 'latin1_swedish_ci', - 'connect_timeout' => 120 - ), - 'datastore' => array( - 'type' => '10000000-0000-0000-0000-000000000001', - 'version' => '1379cc8b-4bc5-4c4a-9e9d-7a9ad27c0866' - ) -)); -/** @var $configuration OpenCloud\Database\Resource\Configuration **/ -``` -[ [Get the executable PHP script for this example](/samples/Database/create-configuration.php) ] - -### Listing configurations -You can list out all the configurations you have created as shown below: - -```php -$configurations = $service->configurationList(); -foreach ($configurations as $configuration) { - /** @var $configuration OpenCloud\Database\Resource\Configuration **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Database/list-configurations.php) ] - -### Retrieving a configuration -You can retrieve a specific configuration, using its ID, as shown below: - -```php -$configuration = $service->configuration(getenv('OS_DB_CONFIGURATION_ID')); -/** @var OpenCloud\Database\Resource\Configuration **/ -``` -[ [Get the executable PHP script for this example](/samples/Database/get-configuration.php) ] - -### Updating a configuration -You have two choices when updating a configuration: -* You could [patch a configuration](#patching-a-configuration) to change only some configuration parameters, _or_ -* You could [entirely replace a configuration](#replacing-a-configuration) to replace all configuration parameters with new ones. - -#### Patching a configuration -You can patch a configuration as shown below: - -```php -$configuration->patch(array( - 'values' => array( - 'connect_timeout' => 30 - ) -)); -``` -[ [Get the executable PHP script for this example](/samples/Database/patch-configuration.php) ] - -#### Replacing a configuration -You can replace a configuration as shown below: - -```php -$configuration->update(array( - 'values' => array( - 'collation_server' => 'utf8_general_ci', - 'connect_timeout' => 60 - ) -)); -``` -[ [Get the executable PHP script for this example](/samples/Database/replace-configuration.php) ] - -### Deleting a configuration -You can delete a configuration as shown below: - -```php -$configuration->delete(); -``` -[ [Get the executable PHP script for this example](/samples/Database/delete-configuration.php) ] - -**Note:** You cannot delete a configuration if it is in use by a running instance. - -### Listing instances using a configuration -You can list all instances using a specific configuration, using its ID, as shown below: - -```php -$instances = $configuration->instanceList(); -foreach ($instances as $instance) { - /** @var $instance OpenCloud\Database\Resource\Instance **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Database/list-configuration-instances.php) ] - -## Datastores - -Datastores are technologies avaialable to persist data. - -### Listing datastores -You can list out all the datastores available as shown below: - -```php -$datastores = $service->datastoreList(); -foreach ($datastores as $datastore) { - /** @var $datastore OpenCloud\Database\Resource\Datastore **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Database/list-datastores.php) ] - -### Retrieving a datastore -You can retrieve a specific datastore's information, using its ID, as shown below: - -```php -$datastore = $service->datastore(''); -/** @var OpenCloud\Database\Resource\Datastore **/ -``` -[ [Get the executable PHP script for this example](/samples/Database/get-datastore.php) ] - -### Listing datastore versions -You can list out all the versions available for a specific datastore, as shown below: - -```php -$versions = $datastore->versionList(); -foreach ($versions as $version) { - /** @var $version OpenCloud\Database\Resource\DatastoreVersion **/ -} -``` -[ [Get the executable PHP script for this example](/samples/Database/list-datastore-versions.php) ] - -### Retrieving a datastore version -You a retrieve a specific datastore version, using its ID, as shown below: - -```php -$datastoreVersion = $datastore->version(''); -/** @var OpenCloud\Database\Resource\DatastoreVersion **/ -[ [Get the executable PHP script for this example](/samples/Database/get-datastore-version.php) ] +https://doc.php-opencloud.com/en/latest/services/database/index.html diff --git a/docs/userguide/flavors.md b/docs/userguide/flavors.md index 41e3fa8d4..dd7806be5 100644 --- a/docs/userguide/flavors.md +++ b/docs/userguide/flavors.md @@ -1,60 +1,6 @@ Working with Flavors ==================== -A *flavor* is a named definition of certain server parameters such as the -amount of RAM and disk space available. (There are other parameters set via -the flavor, such as the amount of disk space and the number of virtual CPUs, -but a discussion of those is too in-depth for a simple Getting Started Guide -like this one.) +Our docs have moved! Please visit the below link: -## Get a flavor - -A `Flavor` object is generated from the `flavor()` method on an -`OpenCloud\Compute\Service` object: - -```php -$flavor = $service->flavor(''); -``` - -## List flavors - -```php -$flavors = $service->flavorList(); - -foreach ($flavors as $flavor) { - /** @param $flavor OpenCloud\Common\Resource\FlavorInterface */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](Iterators.md). - -### Details - -By default, the `flavorList()` method returns full details on all flavors. -However, because of the overhead involved in retrieving all the details, -this function can be slower than expected. You can supply an optional -boolean parameter to the `flavorList()` method to determine whether or not -the flavor details are included: - -```php -// Name and ID only -$compute->flavorList(false); - -// All details -$compute->flavorList(true); -``` - -### Filters - -The optional second parameter to the `flavorList()` method is an -associative array of filter parameters. See the -[List Flavors operation](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/List_Flavors-d1e4188.html) - for a list of the available parameters. - -For example, you may be only interested in flavors that have at least 4GB of -memory: - -```php -$fourGbFlavors = $compute->FlavorList(true, array('minRam' => 4096)); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/compute/flavors.html diff --git a/docs/userguide/networks.md b/docs/userguide/networks.md index f24752fc4..d42b73964 100644 --- a/docs/userguide/networks.md +++ b/docs/userguide/networks.md @@ -1,103 +1,6 @@ Working with Cloud Networks =========================== -Rackspace Cloud Networks is a virtual "isolated network" product -based upon (though not strictly identical to) the [OpenStack -Quantum](http://quantum.openstack.org) project. With Cloud Networks, -you can create multiple isolated networks and associate them with -new Cloud Servers. (You cannot add an isolated network to an -existing Cloud Server at this time, although that feature may be -available in the future.) +Our docs have moved! Please visit the below link: -Since the network is a feature of the Cloud Servers product, you -use the `Compute::network()` method to create a new network, and -the `Compute::networkList()` method to retrieve information about -existing networks. - -### Pseudo-networks - -Rackspace has two *pseudo-networks* called `public` and `private`. -The `public` network represents the Internet, while the `private` -network represents the Rackspace internal ServiceNet (an infrastructure -network used to facilitate communication within a Rackspace data -center). These are called "pseudo-networks" because they are not -actually represented in the Quantum component, but have a special -representation that you must use if you want to associate your -server with them. - -The `public` network is represented by the special UUID -`00000000-0000-0000-0000-000000000000` and the `private` network -by `11111111-1111-1111-1111-111111111111`. php-opencloud -provides the special constants `RAX_PUBLIC` and `RAX_PRIVATE` to -make using these networks easier (see [Create a server with an -isolated network](#server) below). - - -### Create a network - -A Cloud Network is identified by a *label* and must be defined with -a network *CIDR* address range. For example, we can create a network -used by our backend servers on the 192.168.0.0 network like this: - -```php -// Create instance of OpenCloud\Compute\Resource\Network -$network = $compute->network(); - -// Send to API -$network->create(array( - 'label' => 'Backend Network', - 'cidr' => '192.168.0.0/16' -)); -``` - -### Delete a network - -```php -$network->delete(); -``` - -Note that you cannot delete a network if there are still servers attached to it. - -### Listing networks - -``` -$networks = $service->networkList(); - -foreach ($networks as $network) { - /** @param $network OpenCloud\Compute\Resource\Network */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](Iterators.md). - -## Create a server with an isolated network - -When you create a new server, you can specify the networks to which -it is attached via the `networks` attribute in the `Server::create()` -method: - -use OpenCloud\Compute\Constants\Network; - -// Create instance of OpenCloud\Compute\Resource\Server -$server = $compute->server(); - -// Send to API -$server->create(array( - 'name' => 'My Server', - 'flavor' => $compute->flavor(''), - 'image' => $compute->image(''), - 'networks' => array( - $network, - $compute->network(Network::RAX_PUBLIC) - ) -)); -``` - -In this example, the server `$server` is attached to the network that we -created in the previous example. It is also attached to the Rackspace `public` -network (the Internet). However, it is *not* attached to the Rackspace `private` -network (ServiceNet). - -Note that the `networks` attribute is an array of `OpenCloud\Compute\Resource\Network` -objects. \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/networking/index.html diff --git a/docs/userguide/servers.md b/docs/userguide/servers.md index 8f58adea0..127a5b6c5 100644 --- a/docs/userguide/servers.md +++ b/docs/userguide/servers.md @@ -1,188 +1,6 @@ Working with Servers ==================== -A server is a virtual machine instance that is managed by OpenStack Nova. It is -represented by the `OpenCloud\Compute\Resource\Server` class. - -## Setup - -In order to use a `Server` object, you must create the Compute service first: - -```php -$service = $client->computeService('cloudServersOpenStack', 'ORD'); -``` - -For more information about setting up client objects, see the -[client documentation](Clients.md). For more information about service objects, -including a full list of expected arguments, see the -[service documentation](Services.md). - -## Get an existing server - -To retrieve an existing server, all you need is its unique ID: - -```php -/** @param $server OpenCloud\Compute\Resource\Server */ -$server = $server->server(''); -``` - -## Create a new server - -A server requires both a [Flavor object](flavors.md) and an -[Image object](images.md) to be created. In addition, a server requires a name: - -```php -// New instance of OpenCloud\Compute\Resource\Server -$server = $service->server(); - -/** @param $server OpenCloud\Image\Resource\ImageInterface */ -$image = $service->image(''); - -/** @param $server OpenCloud\Compute\Resource\Flavor */ -$flavor = $service->flavor(''); - -// Send to API -$server->create(array( - 'name' => 'New server', - 'flavor' => $flavor, - 'image' => $image -)); -``` - -Server builds typically take under 5 minutes to complete (depending upon the size -of the server). However, the initial response will return the server's ID as -well as the assigned root password: - -```php -echo $server->adminPass; -``` - -(Note: it is not recommended that you print out the root password because of -security risks. This is only provided as an example.) - -When you create a new server on the Rackspace public cloud, you can also -associate it with one or more isolated networks. For more information, see -[Working with Cloud Networks](networks.md). - -### Rebuilding an existing server - -"Rebuilding" a server is nearly identical to creating one; you must supply -an Image object. You can also change the server's name as part of the rebuild. -The primary difference between a create and a rebuild is that, in the rebuild, -the server's IP address(es) are retained (when the server is created, new IP -addresses are assigned). - -To rebuild a server: - -```php -$server->rebuild(array( - 'adminPass' => 'rootPassword', - 'name' => 'A Bigger Server', - 'image' => $compute->image('') -)); -``` - -### Updating a server - -The `update()` method is very similar to `create()` except that the only -attributes of a server that you are permitted to update are its name and -the [access IP addresses](accessip.md). - -```php -$server->update(array('accessIPv4' => '50.57.94.244')); -``` - -### Deleting a server - -```php -$server->delete(); -``` - -## Server actions - -You can perform various actions on a server, such as rebooting it, resizing -it, or changing the root password. - -### Setting the root password - -Use the `setPassword()` method to change the root user's password: - -```php -$server->setPassword('new password'); -``` - -Note that it may take a few second for the new password to take effect. Also, -password restrictions (such as the minimum number of characters, numbers of -punctuation characters, and so forth) are enforced by the operating system and are -not always detectable by the Compute service. This means that, even though -the `setPassword()` method succeeds, the password may not be changed, and -there may not be any feedback to that effect. - -### To reboot the server - -You can perform either a *hard* reboot (this is like pulling the power cord -and then restarting) or a *soft* reboot (initiated by the operating system -and generally less disruptive than a hard reboot). A hard reboot is -performed by default: - -```php -$server->reboot(); // hard reboot -$server->reboot(ServerState::REBOOT_STATE_HARD); // also a hard reboot -$server->reboot(ServerState::REBOOT_STATE_SOFT); // a soft reboot -``` - -If the server is "hung," or unresponsive, a hard reboot may sometimes be -the only way to access the server. - -### To resize the server - -A server can be resized by providing a new [Flavor object](flavors.md): - -```php -$server->resize($compute->flavor(5)); -``` - -Once the resize completes (check the `$server->status`), you can either -confirm it: - -```php -$server->resizeConfirm(); -``` - -or revert it back to the original size: - -```php -$server->resizeRevert(); -``` - -### To rescue/unrescue a server - -In rescue mode, a server is rebuilt to a pristine state and the existing -filesystem is mounted so that you can edit files and diagnose issues. -See [this document](http://docs.rackspace.com/servers/api/v2/cs-devguide/content/rescue_mode.html) -for more details. - -Put server into rescue mode: - -```php -$password = $server->rescue(); -``` - -The `$password` is the assigned root password of the rescue server. - -Take server out of rescue mode: - -```php -$server->unrescue(); -``` - -This restores the server to its original state (plus any changes you may have -made while it was in rescue mode). - -## What next? - -* See also [Working with Networks](networks.md). -* To learn about dynamic - volume creation and assignment, see - [Working with Volumes](volumes.md). +Our docs have moved! Please visit the below link: +https://doc.php-opencloud.com/en/latest/services/compute/index.html diff --git a/docs/userguide/volumes.md b/docs/userguide/volumes.md index bd2f13a9d..8c891d4f2 100644 --- a/docs/userguide/volumes.md +++ b/docs/userguide/volumes.md @@ -1,173 +1,6 @@ Working with Volumes ---------------------------------------------- -Cloud Block Storage (CBS) is a dynamic volume creation and management service -built upon the OpenStack Cinder project. See http://cinder.openstack.org for -complete details about the available features and functionality. -## Setup +Our docs have moved! Please visit the below link: -```php -$service = $client->volumeService('cloudBlockStorage', 'DFW'); -``` - -For more information about setting up client objects, see the -[client documentation](Clients.md). For more information about service objects, -including a full list of expected arguments, see the -[service documentation](Services.md). - -## Volume Types - -Providers may support multiple types of volumes; at Rackspace, a volume can -either be `SSD` (solid state disk: expensive, high-performance) or -`SATA` (serial attached storage: regular disks, less expensive). - -### List volume types - -```php -$volumeTypes = $service->volumeTypeList(); - -foreach ($volumeTypes as $volumeType) { - /** @param $volumeType OpenCloud\Volume\Resource\VolumeType */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](Iterators.md). - -### Describe a volume type - -If you know the ID of a volume type, use the `volumeType` method to retrieve -information on it: - -```php -$volumeType = $service->volumeType(1); -``` - -A volume type has three attributes: - -* `$id` the volume type identifier -* `$name` its name -* `$extra_specs` additional information for the provider - -## Volumes - -A volume is a detachable block storage device. You can think of it as a USB -hard drive. It can only be attached to one instance at a time. - -A volume is represented by the `OpenCloud\Volume\Resource\Volume` class. - -### To create a volume - -To create a volume, you must specify its size (in gigabytes). All other -parameters are optional: - -```php -// Create instance of OpenCloud\Volume\Resource\Volume -$volume = $service->volume(); - -$volume->create(array( - 'size' => 200, - 'volume_type' => $service->volumeType(''), - 'display_name' => 'My Volume', - 'display_description' => 'Used for large object storage' -)); -``` - -### List volumes - -```php -$volumes = $service->volumeList(); - -foreach ($volumes as $volume) { - /** @param $volumeType OpenCloud\Volume\Resource\Volume */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](Iterators.md). - -### Get details on a single volume - -If you specify an ID on the `volume()` method, it retrieves information on -the specified volume: - -```php -$volume = $dallas->volume(''); -echo $volume->size; -``` - -### To delete a volume - -```php -$volume->delete(); -``` - -## Snapshots - -A snapshot is a point-in-time copy of the data contained in a volume. It is -represented by the `OpenCloud\Volume\Resource\Snapshot` class. - -### Create a snapshot - -A `Snapshot` object is created from the Cloud Block Storage service. However, -it is associated with a volume, and you must specify a volume to create one: - -```php -// New instance of OpenCloud\Volume\Resource\Snapshot -$snapshot = $service->snapshot(); - -// Send to API -$snapshot->create(array( - 'display_name' => 'Name that snapshot', - 'volume_id' => $volume->id -)); -``` - -### List snapshots - -```php -$snapshots = $service->snapshotList(); - -foreach ($snapshots as $snapshot) { - /** @param $snapshot OpenCloud\Volume\Resource\Snapshot */ -} -``` - -For more information about working with iterators, please see the -[iterators documentation](Iterators.md). - -### To get details on a single snapshot - -```php -$snapshot = $dallas->snapshot(''); -``` - -#### To delete a snapshot - -```php -$snapshot->delete(); -``` - -### Volumes and Servers - -A volume by itself is useful when it is attached to a server so that the -server can use the volume. - -### To attach a volume to a server - -```php -$server->attachVolume($volume, '') -``` - -The `` is the location on the server on which to -mount the volume (usually `/dev/xvhdd` or similar). You can also supply -`'auto'` as the mount point, in which case the mount point will be -automatically selected for you. `auto` is the default value for -`{mount-point}`, so you do not actually need to supply anything for that -parameter. - -### To detach a volume from a server - -```php -$server->detachVolume($volume); -``` \ No newline at end of file +https://doc.php-opencloud.com/en/latest/services/volume/index.html From 6655b4ad0c56059719fbe21d38dab02a50d4414f Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 11 Mar 2015 19:35:26 +0100 Subject: [PATCH 164/181] Add more information about configuring clients --- doc/auth.rst | 54 ++++++++++++++++++++++++++++++++++++++++++ doc/http-clients.rst | 56 ++++++++++++++++++++++++++++++++++++++++++++ doc/index.rst | 3 +++ doc/logging.rst | 33 ++++++++++++++++++++++++++ 4 files changed, 146 insertions(+) create mode 100644 doc/auth.rst create mode 100644 doc/http-clients.rst create mode 100644 doc/logging.rst diff --git a/doc/auth.rst b/doc/auth.rst new file mode 100644 index 000000000..ce5ba7233 --- /dev/null +++ b/doc/auth.rst @@ -0,0 +1,54 @@ +Authentication +============== + +The client does not automatically authenticate against the API when it is +instantiated - it waits for an API call. When this happens, it checks +whether the current “token” has expired, and (re-)authenticates if +necessary. + +You can force authentication, by calling: + +.. code-block:: php + + $client->authenticate(); + +If the credentials are incorrect, a ``401`` error will be returned. If +credentials are correct, a ``200`` status is returned with your Service +Catalog. + + +Service Catalog +--------------- + +The Service Catalog is returned on successful authentication, and is +composed of all the different API services available to the current +tenant. All of this functionality is encapsulated in the ``Catalog`` +object, which allows you greater control and interactivity. + +.. code-block:: php + + /** @var OpenCloud\Common\Service\Catalog */ + $catalog = $client->getCatalog(); + + // Return a list of OpenCloud\Common\Service\CatalogItem objects + foreach ($catalog->getItems() as $catalogItem) { + + $name = $catalogItem->getName(); + $type = $catalogItem->getType(); + + if ($name == 'cloudServersOpenStack' && $type == 'compute') { + break; + } + + // Array of OpenCloud\Common\Service\Endpoint objects + $endpoints = $catalogItem->getEndpoints(); + foreach ($endpoints as $endpoint) { + if ($endpoint->getRegion() == 'DFW') { + echo $endpoint->getPublicUrl(); + } + } + } + +As you can see, you have access to each Service’s name, type and list of +endpoints. Each endpoint provides access to the specific region, along +with its public and private endpoint URLs. diff --git a/doc/http-clients.rst b/doc/http-clients.rst new file mode 100644 index 000000000..49828509b --- /dev/null +++ b/doc/http-clients.rst @@ -0,0 +1,56 @@ +HTTP Clients +============ + +Default HTTP headers +-------------------- + +To set default HTTP headers: + +.. code-block:: php + + $client->setDefaultOption('headers/X-Custom-Header', 'FooBar'); + + +User agents +----------- + +php-opencloud will send a default ``User-Agent`` header for every HTTP +request, unless a custom value is provided by the end-user. The default +header will be in this format: + + User-Agent: OpenCloud/xxx cURL/yyy PHP/zzz + +where ``xxx`` is the current version of the SDK, ``yyy`` is the current +version of cURL, and ``zzz`` is the current PHP version. To override +this default, you must run: + +.. code-block:: php + + $client->setUserAgent('MyCustomUserAgent'); + +which will result in: + + User-Agent: MyCustomUserAgent + +If you want to set a *prefix* for the user agent, but retain the default +``User-Agent`` as a suffix, you must run: + +.. code-block:: php + + $client->setUserAgent('MyPrefix', true); + +which will result in: + + User-Agent: MyPrefix OpenCloud/xxx cURL/yyy PHP/zzz + +where ``$client`` is an instance of ``OpenCloud\OpenStack`` or +``OpenCloud\Rackspace``. + + +Other functionality +------------------- + +For a full list of functionality provided by Guzzle, please consult the +`official documentation`_. + +.. _official documentation: http://docs.guzzlephp.org/en/latest/http-client/client.html diff --git a/doc/index.rst b/doc/index.rst index fc7c280c3..4994f0efb 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -50,6 +50,9 @@ Usage tips iterators regions url-types + logging + http-clients + auth Help and support ---------------- diff --git a/doc/logging.rst b/doc/logging.rst new file mode 100644 index 000000000..bb2a3de09 --- /dev/null +++ b/doc/logging.rst @@ -0,0 +1,33 @@ +Logging +======= + +Logger injection +---------------- + +As the ``Rackspace`` client extends the ``OpenStack`` client, they both support +passing ``$options`` as an array via the constructor's third parameter. The +options are passed as a config to the `Guzzle` client, but also allow to inject +your own logger. + +Your logger should implement the ``Psr\Log\LoggerInterface`` `as defined in +PSR-3 `_. +One example of a compatible logger is `Monolog `_. +When the client does create a service, it will inject the logger if one is +available. + +To inject a ``LoggerInterface`` compatible logger into a new client: + +.. code-block:: php + + use Monolog\Logger; + use OpenCloud\OpenStack; + + // create a log channel + $logger = new Logger('name'); + + $client = new OpenStack('http://identity.my-openstack.com/v2.0', array( + 'username' => 'foo', + 'password' => 'bar' + ), array( + 'logger' => $logger, + )); From 9b9b3aa9b715b01c2d788a22e43dd227f6e3305d Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Mon, 16 Mar 2015 14:22:04 +0100 Subject: [PATCH 165/181] Use correct CNAME record --- docs/getting-started-openstack.md | 2 +- docs/getting-started.md | 2 +- docs/userguide/Autoscale/Config.md | 2 +- docs/userguide/Autoscale/Groups.md | 2 +- docs/userguide/Autoscale/Policies.md | 2 +- docs/userguide/Autoscale/Webhooks.md | 2 +- docs/userguide/Clients.md | 2 +- docs/userguide/CloudMonitoring/Agents.md | 2 +- docs/userguide/CloudMonitoring/Alarms.md | 2 +- docs/userguide/CloudMonitoring/Changelogs.md | 2 +- docs/userguide/CloudMonitoring/Checks.md | 2 +- docs/userguide/CloudMonitoring/Entities.md | 2 +- docs/userguide/CloudMonitoring/Metrics.md | 2 +- docs/userguide/CloudMonitoring/Notifications.md | 2 +- docs/userguide/CloudMonitoring/Service.md | 2 +- docs/userguide/CloudMonitoring/Views.md | 2 +- docs/userguide/CloudMonitoring/Zones.md | 2 +- docs/userguide/Compute/Images.md | 2 +- docs/userguide/Compute/Keypair.md | 2 +- docs/userguide/Compute/Server.md | 2 +- docs/userguide/Compute/Service.md | 2 +- docs/userguide/DNS/Domains.md | 2 +- docs/userguide/DNS/Limits.md | 2 +- docs/userguide/DNS/Records.md | 2 +- docs/userguide/DNS/Reverse-DNS.md | 2 +- docs/userguide/DNS/Service.md | 2 +- docs/userguide/Database/README.md | 2 +- docs/userguide/Debugging.md | 2 +- docs/userguide/Identity/Roles.md | 2 +- docs/userguide/Identity/Service.md | 2 +- docs/userguide/Identity/Tenants.md | 2 +- docs/userguide/Identity/Tokens.md | 2 +- docs/userguide/Identity/Users.md | 2 +- docs/userguide/Image/Images.md | 2 +- docs/userguide/Image/Schemas.md | 2 +- docs/userguide/Image/Sharing.md | 2 +- docs/userguide/Image/Tags.md | 2 +- docs/userguide/Iterators.md | 2 +- docs/userguide/LoadBalancer/README.md | 2 +- docs/userguide/LoadBalancer/USERGUIDE.md | 2 +- docs/userguide/Networking/README.md | 2 +- docs/userguide/Networking/USERGUIDE.md | 2 +- docs/userguide/ObjectStore/Access.md | 2 +- docs/userguide/ObjectStore/Account.md | 2 +- docs/userguide/ObjectStore/CDN/Container.md | 2 +- docs/userguide/ObjectStore/CDN/Object.md | 2 +- docs/userguide/ObjectStore/README.md | 2 +- docs/userguide/ObjectStore/Storage/Container.md | 2 +- docs/userguide/ObjectStore/Storage/Migrating.md | 2 +- docs/userguide/ObjectStore/Storage/Object.md | 2 +- docs/userguide/ObjectStore/USERGUIDE.md | 2 +- docs/userguide/Orchestration/README.md | 2 +- docs/userguide/Orchestration/USERGUIDE.md | 2 +- docs/userguide/Queues/Claim.md | 2 +- docs/userguide/Queues/Message.md | 2 +- docs/userguide/Queues/Queue.md | 2 +- docs/userguide/README.md | 2 +- docs/userguide/Services.md | 2 +- docs/userguide/accessip.md | 2 +- docs/userguide/caching-credentials.md | 2 +- docs/userguide/dbaas.md | 2 +- docs/userguide/flavors.md | 2 +- docs/userguide/networks.md | 2 +- docs/userguide/servers.md | 2 +- docs/userguide/volumes.md | 2 +- 65 files changed, 65 insertions(+), 65 deletions(-) diff --git a/docs/getting-started-openstack.md b/docs/getting-started-openstack.md index 24eda2779..1133b948d 100644 --- a/docs/getting-started-openstack.md +++ b/docs/getting-started-openstack.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/getting-started-with-openstack.html +http://docs.php-opencloud.com/en/latest/getting-started-with-openstack.html diff --git a/docs/getting-started.md b/docs/getting-started.md index af65271fe..c7d731a4c 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/getting-started-with-rackspace.html +http://docs.php-opencloud.com/en/latest/getting-started-with-rackspace.html diff --git a/docs/userguide/Autoscale/Config.md b/docs/userguide/Autoscale/Config.md index 02f2e891d..328fdcc93 100644 --- a/docs/userguide/Autoscale/Config.md +++ b/docs/userguide/Autoscale/Config.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/autoscale/group-config.html +http://docs.php-opencloud.com/en/latest/services/autoscale/group-config.html diff --git a/docs/userguide/Autoscale/Groups.md b/docs/userguide/Autoscale/Groups.md index 7ec7aa269..e0d8bfcdb 100644 --- a/docs/userguide/Autoscale/Groups.md +++ b/docs/userguide/Autoscale/Groups.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/autoscale/groups.html +http://docs.php-opencloud.com/en/latest/services/autoscale/groups.html diff --git a/docs/userguide/Autoscale/Policies.md b/docs/userguide/Autoscale/Policies.md index 7a312af50..1f890d7ad 100644 --- a/docs/userguide/Autoscale/Policies.md +++ b/docs/userguide/Autoscale/Policies.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/autoscale/policies.html +http://docs.php-opencloud.com/en/latest/services/autoscale/policies.html diff --git a/docs/userguide/Autoscale/Webhooks.md b/docs/userguide/Autoscale/Webhooks.md index c5e6453ed..783075508 100644 --- a/docs/userguide/Autoscale/Webhooks.md +++ b/docs/userguide/Autoscale/Webhooks.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/autoscale/webhooks.html +http://docs.php-opencloud.com/en/latest/services/autoscale/webhooks.html diff --git a/docs/userguide/Clients.md b/docs/userguide/Clients.md index 184b601f4..762a7ed70 100644 --- a/docs/userguide/Clients.md +++ b/docs/userguide/Clients.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/index.html +http://docs.php-opencloud.com/en/latest/index.html diff --git a/docs/userguide/CloudMonitoring/Agents.md b/docs/userguide/CloudMonitoring/Agents.md index b316d004c..f1b8cab5d 100644 --- a/docs/userguide/CloudMonitoring/Agents.md +++ b/docs/userguide/CloudMonitoring/Agents.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/agents.html +http://docs.php-opencloud.com/en/latest/services/monitoring/agents.html diff --git a/docs/userguide/CloudMonitoring/Alarms.md b/docs/userguide/CloudMonitoring/Alarms.md index b08caf4cd..b64c1e948 100644 --- a/docs/userguide/CloudMonitoring/Alarms.md +++ b/docs/userguide/CloudMonitoring/Alarms.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/alarms.html +http://docs.php-opencloud.com/en/latest/services/monitoring/alarms.html diff --git a/docs/userguide/CloudMonitoring/Changelogs.md b/docs/userguide/CloudMonitoring/Changelogs.md index ff943e592..a1d137c9f 100644 --- a/docs/userguide/CloudMonitoring/Changelogs.md +++ b/docs/userguide/CloudMonitoring/Changelogs.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/changelogs.html +http://docs.php-opencloud.com/en/latest/services/monitoring/changelogs.html diff --git a/docs/userguide/CloudMonitoring/Checks.md b/docs/userguide/CloudMonitoring/Checks.md index 5710aa465..37aefb644 100644 --- a/docs/userguide/CloudMonitoring/Checks.md +++ b/docs/userguide/CloudMonitoring/Checks.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/checks.html +http://docs.php-opencloud.com/en/latest/services/monitoring/checks.html diff --git a/docs/userguide/CloudMonitoring/Entities.md b/docs/userguide/CloudMonitoring/Entities.md index beed807a2..0f09a74a2 100644 --- a/docs/userguide/CloudMonitoring/Entities.md +++ b/docs/userguide/CloudMonitoring/Entities.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/entities.html +http://docs.php-opencloud.com/en/latest/services/monitoring/entities.html diff --git a/docs/userguide/CloudMonitoring/Metrics.md b/docs/userguide/CloudMonitoring/Metrics.md index 0b275c97e..86450bee9 100644 --- a/docs/userguide/CloudMonitoring/Metrics.md +++ b/docs/userguide/CloudMonitoring/Metrics.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/metrics.html +http://docs.php-opencloud.com/en/latest/services/monitoring/metrics.html diff --git a/docs/userguide/CloudMonitoring/Notifications.md b/docs/userguide/CloudMonitoring/Notifications.md index 129881fae..30a1cf97c 100644 --- a/docs/userguide/CloudMonitoring/Notifications.md +++ b/docs/userguide/CloudMonitoring/Notifications.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/notifications.html +http://docs.php-opencloud.com/en/latest/services/monitoring/notifications.html diff --git a/docs/userguide/CloudMonitoring/Service.md b/docs/userguide/CloudMonitoring/Service.md index 6445de039..be9f9435f 100644 --- a/docs/userguide/CloudMonitoring/Service.md +++ b/docs/userguide/CloudMonitoring/Service.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/index.html +http://docs.php-opencloud.com/en/latest/services/monitoring/index.html diff --git a/docs/userguide/CloudMonitoring/Views.md b/docs/userguide/CloudMonitoring/Views.md index ac0017db0..7672c2ea8 100644 --- a/docs/userguide/CloudMonitoring/Views.md +++ b/docs/userguide/CloudMonitoring/Views.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/views.html +http://docs.php-opencloud.com/en/latest/services/monitoring/views.html diff --git a/docs/userguide/CloudMonitoring/Zones.md b/docs/userguide/CloudMonitoring/Zones.md index fcad4b900..8257efa29 100644 --- a/docs/userguide/CloudMonitoring/Zones.md +++ b/docs/userguide/CloudMonitoring/Zones.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/monitoring/zones.html +http://docs.php-opencloud.com/en/latest/services/monitoring/zones.html diff --git a/docs/userguide/Compute/Images.md b/docs/userguide/Compute/Images.md index 6cc06d37f..b7a99025d 100644 --- a/docs/userguide/Compute/Images.md +++ b/docs/userguide/Compute/Images.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/compute/images.html +http://docs.php-opencloud.com/en/latest/services/compute/images.html diff --git a/docs/userguide/Compute/Keypair.md b/docs/userguide/Compute/Keypair.md index 37e5080fe..a3e0b4870 100644 --- a/docs/userguide/Compute/Keypair.md +++ b/docs/userguide/Compute/Keypair.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/compute/keypairs.html +http://docs.php-opencloud.com/en/latest/services/compute/keypairs.html diff --git a/docs/userguide/Compute/Server.md b/docs/userguide/Compute/Server.md index e43e1cc42..dedc1da77 100644 --- a/docs/userguide/Compute/Server.md +++ b/docs/userguide/Compute/Server.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/compute/servers.html +http://docs.php-opencloud.com/en/latest/services/compute/servers.html diff --git a/docs/userguide/Compute/Service.md b/docs/userguide/Compute/Service.md index ba49ff4e4..9bb8e996a 100644 --- a/docs/userguide/Compute/Service.md +++ b/docs/userguide/Compute/Service.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/compute/index.html +http://docs.php-opencloud.com/en/latest/services/compute/index.html diff --git a/docs/userguide/DNS/Domains.md b/docs/userguide/DNS/Domains.md index d8d3a12d3..53aa45c3b 100644 --- a/docs/userguide/DNS/Domains.md +++ b/docs/userguide/DNS/Domains.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/dns/domains.html +http://docs.php-opencloud.com/en/latest/services/dns/domains.html diff --git a/docs/userguide/DNS/Limits.md b/docs/userguide/DNS/Limits.md index 70fac6504..68e928594 100644 --- a/docs/userguide/DNS/Limits.md +++ b/docs/userguide/DNS/Limits.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/dns/limits.html +http://docs.php-opencloud.com/en/latest/services/dns/limits.html diff --git a/docs/userguide/DNS/Records.md b/docs/userguide/DNS/Records.md index 52998b955..fb428c60e 100644 --- a/docs/userguide/DNS/Records.md +++ b/docs/userguide/DNS/Records.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/dns/records.html +http://docs.php-opencloud.com/en/latest/services/dns/records.html diff --git a/docs/userguide/DNS/Reverse-DNS.md b/docs/userguide/DNS/Reverse-DNS.md index e930431c1..84a3a2d15 100644 --- a/docs/userguide/DNS/Reverse-DNS.md +++ b/docs/userguide/DNS/Reverse-DNS.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/dns/reverse-dns.html +http://docs.php-opencloud.com/en/latest/services/dns/reverse-dns.html diff --git a/docs/userguide/DNS/Service.md b/docs/userguide/DNS/Service.md index 3404ed7c7..993648cd9 100644 --- a/docs/userguide/DNS/Service.md +++ b/docs/userguide/DNS/Service.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/dns/index.html +http://docs.php-opencloud.com/en/latest/services/dns/index.html diff --git a/docs/userguide/Database/README.md b/docs/userguide/Database/README.md index 199d049e4..2fc712efd 100644 --- a/docs/userguide/Database/README.md +++ b/docs/userguide/Database/README.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/database/index.html +http://docs.php-opencloud.com/en/latest/services/database/index.html diff --git a/docs/userguide/Debugging.md b/docs/userguide/Debugging.md index 0c6afa4d6..8922df10d 100644 --- a/docs/userguide/Debugging.md +++ b/docs/userguide/Debugging.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/debugging.html +http://docs.php-opencloud.com/en/latest/debugging.html diff --git a/docs/userguide/Identity/Roles.md b/docs/userguide/Identity/Roles.md index 333d53c81..5d608bf51 100644 --- a/docs/userguide/Identity/Roles.md +++ b/docs/userguide/Identity/Roles.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/identity/roles.html +http://docs.php-opencloud.com/en/latest/services/identity/roles.html diff --git a/docs/userguide/Identity/Service.md b/docs/userguide/Identity/Service.md index 579cf2a9f..4195d4bcb 100644 --- a/docs/userguide/Identity/Service.md +++ b/docs/userguide/Identity/Service.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/identity/index.html +http://docs.php-opencloud.com/en/latest/services/identity/index.html diff --git a/docs/userguide/Identity/Tenants.md b/docs/userguide/Identity/Tenants.md index ae9bcdcb0..2129f9604 100644 --- a/docs/userguide/Identity/Tenants.md +++ b/docs/userguide/Identity/Tenants.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/identity/tenants.html +http://docs.php-opencloud.com/en/latest/services/identity/tenants.html diff --git a/docs/userguide/Identity/Tokens.md b/docs/userguide/Identity/Tokens.md index a60c57ab5..f59835ef4 100644 --- a/docs/userguide/Identity/Tokens.md +++ b/docs/userguide/Identity/Tokens.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/identity/tokens.html +http://docs.php-opencloud.com/en/latest/services/identity/tokens.html diff --git a/docs/userguide/Identity/Users.md b/docs/userguide/Identity/Users.md index e387cbee5..a69fbb7dc 100644 --- a/docs/userguide/Identity/Users.md +++ b/docs/userguide/Identity/Users.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/identity/users.html +http://docs.php-opencloud.com/en/latest/services/identity/users.html diff --git a/docs/userguide/Image/Images.md b/docs/userguide/Image/Images.md index 1f593f17a..95824b2a5 100644 --- a/docs/userguide/Image/Images.md +++ b/docs/userguide/Image/Images.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/image/images.html +http://docs.php-opencloud.com/en/latest/services/image/images.html diff --git a/docs/userguide/Image/Schemas.md b/docs/userguide/Image/Schemas.md index b37222b84..5efce8c59 100644 --- a/docs/userguide/Image/Schemas.md +++ b/docs/userguide/Image/Schemas.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/image/schemas.html +http://docs.php-opencloud.com/en/latest/services/image/schemas.html diff --git a/docs/userguide/Image/Sharing.md b/docs/userguide/Image/Sharing.md index 91515b9fa..3fbe0c1d1 100644 --- a/docs/userguide/Image/Sharing.md +++ b/docs/userguide/Image/Sharing.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/image/sharing.html +http://docs.php-opencloud.com/en/latest/services/image/sharing.html diff --git a/docs/userguide/Image/Tags.md b/docs/userguide/Image/Tags.md index fc8bcd8aa..2686391f4 100644 --- a/docs/userguide/Image/Tags.md +++ b/docs/userguide/Image/Tags.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/image/tags.html +http://docs.php-opencloud.com/en/latest/services/image/tags.html diff --git a/docs/userguide/Iterators.md b/docs/userguide/Iterators.md index 114982668..4c8c794ce 100644 --- a/docs/userguide/Iterators.md +++ b/docs/userguide/Iterators.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/iterators.html +http://docs.php-opencloud.com/en/latest/iterators.html diff --git a/docs/userguide/LoadBalancer/README.md b/docs/userguide/LoadBalancer/README.md index 34008ab6c..3531e3dc8 100644 --- a/docs/userguide/LoadBalancer/README.md +++ b/docs/userguide/LoadBalancer/README.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/load-balancer/index.html +http://docs.php-opencloud.com/en/latest/services/load-balancer/index.html diff --git a/docs/userguide/LoadBalancer/USERGUIDE.md b/docs/userguide/LoadBalancer/USERGUIDE.md index 0a5c3b15d..d29925da0 100644 --- a/docs/userguide/LoadBalancer/USERGUIDE.md +++ b/docs/userguide/LoadBalancer/USERGUIDE.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/load-balancer/index.html +http://docs.php-opencloud.com/en/latest/services/load-balancer/index.html diff --git a/docs/userguide/Networking/README.md b/docs/userguide/Networking/README.md index 1778646ad..9597c33a1 100644 --- a/docs/userguide/Networking/README.md +++ b/docs/userguide/Networking/README.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/networking/index.html +http://docs.php-opencloud.com/en/latest/services/networking/index.html diff --git a/docs/userguide/Networking/USERGUIDE.md b/docs/userguide/Networking/USERGUIDE.md index 376daa093..d3185c6f2 100644 --- a/docs/userguide/Networking/USERGUIDE.md +++ b/docs/userguide/Networking/USERGUIDE.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/networking/index.html +http://docs.php-opencloud.com/en/latest/services/networking/index.html diff --git a/docs/userguide/ObjectStore/Access.md b/docs/userguide/ObjectStore/Access.md index 8e224392a..53466362e 100644 --- a/docs/userguide/ObjectStore/Access.md +++ b/docs/userguide/ObjectStore/Access.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/access.html +http://docs.php-opencloud.com/en/latest/services/object-store/access.html diff --git a/docs/userguide/ObjectStore/Account.md b/docs/userguide/ObjectStore/Account.md index fc60751a8..286bb9ca1 100644 --- a/docs/userguide/ObjectStore/Account.md +++ b/docs/userguide/ObjectStore/Account.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/account.html +http://docs.php-opencloud.com/en/latest/services/object-store/account.html diff --git a/docs/userguide/ObjectStore/CDN/Container.md b/docs/userguide/ObjectStore/CDN/Container.md index 9f3b4a5ca..c854b31e5 100644 --- a/docs/userguide/ObjectStore/CDN/Container.md +++ b/docs/userguide/ObjectStore/CDN/Container.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/cdn.html +http://docs.php-opencloud.com/en/latest/services/object-store/cdn.html diff --git a/docs/userguide/ObjectStore/CDN/Object.md b/docs/userguide/ObjectStore/CDN/Object.md index 9f3b4a5ca..c854b31e5 100644 --- a/docs/userguide/ObjectStore/CDN/Object.md +++ b/docs/userguide/ObjectStore/CDN/Object.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/cdn.html +http://docs.php-opencloud.com/en/latest/services/object-store/cdn.html diff --git a/docs/userguide/ObjectStore/README.md b/docs/userguide/ObjectStore/README.md index ea43fcdf7..c66bbabdb 100644 --- a/docs/userguide/ObjectStore/README.md +++ b/docs/userguide/ObjectStore/README.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/index.html +http://docs.php-opencloud.com/en/latest/services/object-store/index.html diff --git a/docs/userguide/ObjectStore/Storage/Container.md b/docs/userguide/ObjectStore/Storage/Container.md index e9fd5af14..ab705fa15 100644 --- a/docs/userguide/ObjectStore/Storage/Container.md +++ b/docs/userguide/ObjectStore/Storage/Container.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/containers.html +http://docs.php-opencloud.com/en/latest/services/object-store/containers.html diff --git a/docs/userguide/ObjectStore/Storage/Migrating.md b/docs/userguide/ObjectStore/Storage/Migrating.md index 8d12c382a..550268f60 100644 --- a/docs/userguide/ObjectStore/Storage/Migrating.md +++ b/docs/userguide/ObjectStore/Storage/Migrating.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/migrating-containers.html +http://docs.php-opencloud.com/en/latest/services/object-store/migrating-containers.html diff --git a/docs/userguide/ObjectStore/Storage/Object.md b/docs/userguide/ObjectStore/Storage/Object.md index 0c58ca9fb..2ecca81e1 100644 --- a/docs/userguide/ObjectStore/Storage/Object.md +++ b/docs/userguide/ObjectStore/Storage/Object.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/objects.html +http://docs.php-opencloud.com/en/latest/services/object-store/objects.html diff --git a/docs/userguide/ObjectStore/USERGUIDE.md b/docs/userguide/ObjectStore/USERGUIDE.md index 6881ee3e6..3773b0078 100644 --- a/docs/userguide/ObjectStore/USERGUIDE.md +++ b/docs/userguide/ObjectStore/USERGUIDE.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/object-store/index.html +http://docs.php-opencloud.com/en/latest/services/object-store/index.html diff --git a/docs/userguide/Orchestration/README.md b/docs/userguide/Orchestration/README.md index 862a61ed7..3647da0c9 100644 --- a/docs/userguide/Orchestration/README.md +++ b/docs/userguide/Orchestration/README.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/orchestration/index.html +http://docs.php-opencloud.com/en/latest/services/orchestration/index.html diff --git a/docs/userguide/Orchestration/USERGUIDE.md b/docs/userguide/Orchestration/USERGUIDE.md index 902d7741b..4a5b9a135 100644 --- a/docs/userguide/Orchestration/USERGUIDE.md +++ b/docs/userguide/Orchestration/USERGUIDE.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/orchestration/index.html +http://docs.php-opencloud.com/en/latest/services/orchestration/index.html diff --git a/docs/userguide/Queues/Claim.md b/docs/userguide/Queues/Claim.md index 0e338956c..58b57d22f 100644 --- a/docs/userguide/Queues/Claim.md +++ b/docs/userguide/Queues/Claim.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/queues/claims.html +http://docs.php-opencloud.com/en/latest/services/queues/claims.html diff --git a/docs/userguide/Queues/Message.md b/docs/userguide/Queues/Message.md index ce0f54b07..767bb0b1d 100644 --- a/docs/userguide/Queues/Message.md +++ b/docs/userguide/Queues/Message.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/queues/messages.html +http://docs.php-opencloud.com/en/latest/services/queues/messages.html diff --git a/docs/userguide/Queues/Queue.md b/docs/userguide/Queues/Queue.md index 01bb95e74..2299a72e2 100644 --- a/docs/userguide/Queues/Queue.md +++ b/docs/userguide/Queues/Queue.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/queues/queues.html +http://docs.php-opencloud.com/en/latest/services/queues/queues.html diff --git a/docs/userguide/README.md b/docs/userguide/README.md index 0be239d94..b49b4e67c 100644 --- a/docs/userguide/README.md +++ b/docs/userguide/README.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/index.html +http://docs.php-opencloud.com/en/latest/index.html diff --git a/docs/userguide/Services.md b/docs/userguide/Services.md index 9c9946e34..6973130eb 100644 --- a/docs/userguide/Services.md +++ b/docs/userguide/Services.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/index.html +http://docs.php-opencloud.com/en/latest/index.html diff --git a/docs/userguide/accessip.md b/docs/userguide/accessip.md index 5002ef8de..9d343de11 100644 --- a/docs/userguide/accessip.md +++ b/docs/userguide/accessip.md @@ -3,4 +3,4 @@ About the Access IP Addresses Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/compute/servers.html +http://docs.php-opencloud.com/en/latest/services/compute/servers.html diff --git a/docs/userguide/caching-credentials.md b/docs/userguide/caching-credentials.md index 365e6997e..949dcad53 100644 --- a/docs/userguide/caching-credentials.md +++ b/docs/userguide/caching-credentials.md @@ -2,4 +2,4 @@ Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/caching-creds.html +http://docs.php-opencloud.com/en/latest/caching-creds.html diff --git a/docs/userguide/dbaas.md b/docs/userguide/dbaas.md index 48d108014..fe0327861 100644 --- a/docs/userguide/dbaas.md +++ b/docs/userguide/dbaas.md @@ -3,4 +3,4 @@ Working with Cloud Databases Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/database/index.html +http://docs.php-opencloud.com/en/latest/services/database/index.html diff --git a/docs/userguide/flavors.md b/docs/userguide/flavors.md index dd7806be5..4bf978b52 100644 --- a/docs/userguide/flavors.md +++ b/docs/userguide/flavors.md @@ -3,4 +3,4 @@ Working with Flavors Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/compute/flavors.html +http://docs.php-opencloud.com/en/latest/services/compute/flavors.html diff --git a/docs/userguide/networks.md b/docs/userguide/networks.md index d42b73964..f6a153508 100644 --- a/docs/userguide/networks.md +++ b/docs/userguide/networks.md @@ -3,4 +3,4 @@ Working with Cloud Networks Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/networking/index.html +http://docs.php-opencloud.com/en/latest/services/networking/index.html diff --git a/docs/userguide/servers.md b/docs/userguide/servers.md index 127a5b6c5..1ff28fd30 100644 --- a/docs/userguide/servers.md +++ b/docs/userguide/servers.md @@ -3,4 +3,4 @@ Working with Servers Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/compute/index.html +http://docs.php-opencloud.com/en/latest/services/compute/index.html diff --git a/docs/userguide/volumes.md b/docs/userguide/volumes.md index 8c891d4f2..bc161e5b3 100644 --- a/docs/userguide/volumes.md +++ b/docs/userguide/volumes.md @@ -3,4 +3,4 @@ Working with Volumes Our docs have moved! Please visit the below link: -https://doc.php-opencloud.com/en/latest/services/volume/index.html +http://docs.php-opencloud.com/en/latest/services/volume/index.html From 9cf735dd7764ad907991079f86c7e557c863a3df Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 08:21:50 -0700 Subject: [PATCH 166/181] Using TLSv1 cipher suite for Cloud Databases client. --- lib/OpenCloud/Database/Service.php | 22 +++++++++++++++++++ .../OpenCloud/Tests/Database/ServiceTest.php | 7 ++++++ 2 files changed, 29 insertions(+) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index dd63a60f1..50845ba24 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -17,6 +17,8 @@ namespace OpenCloud\Database; +use Guzzle\Http\ClientInterface; +use Psr\Log\LogLevel; use OpenCloud\Common\Service\NovaService; use OpenCloud\Database\Resource\Instance; use OpenCloud\Database\Resource\Configuration; @@ -104,4 +106,24 @@ public function datastoreList($params = array()) return $this->resourceList('Datastore', $url); } + + /** + * {@inheritDoc} + */ + public function setClient(ClientInterface $client) + { + // The Rackspace Cloud Databases service only supports the + // RC4 SSL cipher which is not supported by modern OpenSSL clients. + // Until the service can support additional, more modern and secure + // ciphers, this SDK has to ask curl to allow using the weaker + // cipher. For more information, see https://github.com/rackspace/php-opencloud/issues/560 + + $curlOptions = $client->getConfig()->get('curl.options'); + $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = CURL_SSLVERSION_TLSv1; + $client->getConfig()->set('curl.options', $curlOptions); + + $client->getLogger()->critical('The SDK is using the TLSv1 cipher suite when connecting to the Rackspace Cloud Databases service. This suite contains a weak cipher (RC4) so please use at your own risk. See https://github.com/rackspace/php-opencloud/issues/560 for details.'); + + $this->client = $client; + } } diff --git a/tests/OpenCloud/Tests/Database/ServiceTest.php b/tests/OpenCloud/Tests/Database/ServiceTest.php index 8212fb61a..4c690ae81 100644 --- a/tests/OpenCloud/Tests/Database/ServiceTest.php +++ b/tests/OpenCloud/Tests/Database/ServiceTest.php @@ -71,4 +71,11 @@ public function testDatastoreList() { $this->assertInstanceOf(self::COLLECTION_CLASS, $this->service->datastoreList()); } + + public function testClientUsesTLSv1CipherSuite() + { + $client = $this->service->getClient(); + $curlOptions = $client->getConfig('curl.options'); + $this->assertEquals(CURL_SSLVERSION_TLSv1, $curlOptions['CURLOPT_SSL_CIPHER_LIST']); + } } From ffd884be7bfefc521ec6b5103a9fd77c967d2abb Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 08:40:04 -0700 Subject: [PATCH 167/181] Check that critical message is being logged + suppress log output. --- .../Tests/Database/DatabaseTestCase.php | 25 ++++++++++++++++++- .../OpenCloud/Tests/Database/ServiceTest.php | 1 + 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/OpenCloud/Tests/Database/DatabaseTestCase.php b/tests/OpenCloud/Tests/Database/DatabaseTestCase.php index 0e8ad75cb..c0a0b38e0 100644 --- a/tests/OpenCloud/Tests/Database/DatabaseTestCase.php +++ b/tests/OpenCloud/Tests/Database/DatabaseTestCase.php @@ -18,6 +18,22 @@ namespace OpenCloud\Tests\Database; use OpenCloud\Tests\OpenCloudTestCase; +use OpenCloud\Common\Log\Logger; + +class UnitTestLogger extends Logger +{ + protected $criticalLogMessage; + + public function critical($message, array $context = array()) + { + ++$this->criticalLogMessage; + } + + public function getCriticalLogMessage() + { + return $this->criticalLogMessage; + } +} class DatabaseTestCase extends OpenCloudTestCase { @@ -28,7 +44,9 @@ class DatabaseTestCase extends OpenCloudTestCase public function setupObjects() { - $this->service = $this->getClient()->databaseService(); + $client = $this->getClient(); + $client->setLogger(new UnitTestLogger()); + $this->service = $client->databaseService(); $this->addMockSubscriber($this->getTestFilePath('Instance')); $this->instance = $this->service->instance('foo'); @@ -37,4 +55,9 @@ public function setupObjects() $this->datastore = $this->service->datastore('10000000-0000-0000-0000-000000000001'); $this->datastoreVersion = $this->datastore->version('b00000b0-00b0-0b00-00b0-000b000000bb'); } + + protected function assertCriticalMessageWasLogged() + { + $this->assertNotEmpty($this->getClient()->getLogger()->getCriticalLogMessage()); + } } diff --git a/tests/OpenCloud/Tests/Database/ServiceTest.php b/tests/OpenCloud/Tests/Database/ServiceTest.php index 4c690ae81..3dc5a11f1 100644 --- a/tests/OpenCloud/Tests/Database/ServiceTest.php +++ b/tests/OpenCloud/Tests/Database/ServiceTest.php @@ -77,5 +77,6 @@ public function testClientUsesTLSv1CipherSuite() $client = $this->service->getClient(); $curlOptions = $client->getConfig('curl.options'); $this->assertEquals(CURL_SSLVERSION_TLSv1, $curlOptions['CURLOPT_SSL_CIPHER_LIST']); + $this->assertCriticalMessageWasLogged(); } } From b212e21f04eea6c6e55c961024c628bf77c60fd9 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 08:49:39 -0700 Subject: [PATCH 168/181] Removing unnecessary import. --- lib/OpenCloud/Database/Service.php | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index 50845ba24..2e9d56093 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -18,7 +18,6 @@ namespace OpenCloud\Database; use Guzzle\Http\ClientInterface; -use Psr\Log\LogLevel; use OpenCloud\Common\Service\NovaService; use OpenCloud\Database\Resource\Instance; use OpenCloud\Database\Resource\Configuration; From 925d5a77fa89471706694523030b7e1ecb2b3158 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 08:49:46 -0700 Subject: [PATCH 169/181] Breaking up log message over several lines. --- lib/OpenCloud/Database/Service.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index 2e9d56093..00498ed28 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -121,7 +121,11 @@ public function setClient(ClientInterface $client) $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = CURL_SSLVERSION_TLSv1; $client->getConfig()->set('curl.options', $curlOptions); - $client->getLogger()->critical('The SDK is using the TLSv1 cipher suite when connecting to the Rackspace Cloud Databases service. This suite contains a weak cipher (RC4) so please use at your own risk. See https://github.com/rackspace/php-opencloud/issues/560 for details.'); + $logMessage = 'The SDK is using the TLSv1 cipher suite when connecting ' + . 'to the Rackspace Cloud Databases service. This suite contains ' + . 'a weak cipher (RC4) so please use at your own risk. See ' + . 'https://github.com/rackspace/php-opencloud/issues/560 for details.'; + $client->getLogger()->critical($logMessage); $this->client = $client; } From 8d2d1ac3678fa8f6fc950e7ea14af13077cd1b5d Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 08:54:37 -0700 Subject: [PATCH 170/181] Fixing option value - should be cipher name not integer (constant). --- lib/OpenCloud/Database/Service.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index 00498ed28..b73ee2f7c 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -118,7 +118,7 @@ public function setClient(ClientInterface $client) // cipher. For more information, see https://github.com/rackspace/php-opencloud/issues/560 $curlOptions = $client->getConfig()->get('curl.options'); - $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = CURL_SSLVERSION_TLSv1; + $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = 'TLSv1'; $client->getConfig()->set('curl.options', $curlOptions); $logMessage = 'The SDK is using the TLSv1 cipher suite when connecting ' From 75a492808c8277b1d61b865e68bcc3e6c612ad70 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 09:50:56 -0700 Subject: [PATCH 171/181] Use custom cipher suite stronger than TLSv1 (but still including RC4 for Cloud Databases). --- lib/OpenCloud/Database/Service.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index b73ee2f7c..065191095 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -118,7 +118,10 @@ public function setClient(ClientInterface $client) // cipher. For more information, see https://github.com/rackspace/php-opencloud/issues/560 $curlOptions = $client->getConfig()->get('curl.options'); - $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = 'TLSv1'; + $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:' + . 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:' + . 'DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:' + . 'ECDH+RC4:DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'; $client->getConfig()->set('curl.options', $curlOptions); $logMessage = 'The SDK is using the TLSv1 cipher suite when connecting ' From 528b7852fb410445f37fdcf6832a36a84f5d6dac Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 10:08:35 -0700 Subject: [PATCH 172/181] Refactoring SSL cipher list into constant; fixing test. --- lib/OpenCloud/Database/Service.php | 10 ++++++---- tests/OpenCloud/Tests/Database/ServiceTest.php | 4 +++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index 065191095..0828d47f1 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -31,6 +31,11 @@ class Service extends NovaService const DEFAULT_TYPE = 'rax:database'; const DEFAULT_NAME = 'cloudDatabases'; + const SSL_CIPHER_LIST = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:' + . 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:' + . 'DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:' + . 'ECDH+RC4:DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'; + /** * Returns an Instance * @@ -118,10 +123,7 @@ public function setClient(ClientInterface $client) // cipher. For more information, see https://github.com/rackspace/php-opencloud/issues/560 $curlOptions = $client->getConfig()->get('curl.options'); - $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:' - . 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:' - . 'DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:' - . 'ECDH+RC4:DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'; + $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = self::SSL_CIPHER_LIST; $client->getConfig()->set('curl.options', $curlOptions); $logMessage = 'The SDK is using the TLSv1 cipher suite when connecting ' diff --git a/tests/OpenCloud/Tests/Database/ServiceTest.php b/tests/OpenCloud/Tests/Database/ServiceTest.php index 3dc5a11f1..28636a363 100644 --- a/tests/OpenCloud/Tests/Database/ServiceTest.php +++ b/tests/OpenCloud/Tests/Database/ServiceTest.php @@ -27,6 +27,8 @@ namespace OpenCloud\Tests\Database; +use OpenCloud\Database\Service; + class ServiceTest extends DatabaseTestCase { public function test__construct() @@ -76,7 +78,7 @@ public function testClientUsesTLSv1CipherSuite() { $client = $this->service->getClient(); $curlOptions = $client->getConfig('curl.options'); - $this->assertEquals(CURL_SSLVERSION_TLSv1, $curlOptions['CURLOPT_SSL_CIPHER_LIST']); + $this->assertEquals(Service::SSL_CIPHER_LIST, $curlOptions['CURLOPT_SSL_CIPHER_LIST']); $this->assertCriticalMessageWasLogged(); } } From d559ffa12022966fd75025ca837c4b8df4c476b2 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 10:16:20 -0700 Subject: [PATCH 173/181] PHP < 5.6 does not like multi-line consts :| --- lib/OpenCloud/Database/Service.php | 15 +++++++++------ tests/OpenCloud/Tests/Database/ServiceTest.php | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index 0828d47f1..1098e6add 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -31,11 +31,6 @@ class Service extends NovaService const DEFAULT_TYPE = 'rax:database'; const DEFAULT_NAME = 'cloudDatabases'; - const SSL_CIPHER_LIST = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:' - . 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:' - . 'DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:' - . 'ECDH+RC4:DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'; - /** * Returns an Instance * @@ -123,7 +118,7 @@ public function setClient(ClientInterface $client) // cipher. For more information, see https://github.com/rackspace/php-opencloud/issues/560 $curlOptions = $client->getConfig()->get('curl.options'); - $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = self::SSL_CIPHER_LIST; + $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = static::getSslCipherList(); $client->getConfig()->set('curl.options', $curlOptions); $logMessage = 'The SDK is using the TLSv1 cipher suite when connecting ' @@ -134,4 +129,12 @@ public function setClient(ClientInterface $client) $this->client = $client; } + + public static function getSslCipherList() + { + return 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:' + . 'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:ECDH+3DES:' + . 'DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:' + . 'ECDH+RC4:DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5'; + } } diff --git a/tests/OpenCloud/Tests/Database/ServiceTest.php b/tests/OpenCloud/Tests/Database/ServiceTest.php index 28636a363..a3f5f4401 100644 --- a/tests/OpenCloud/Tests/Database/ServiceTest.php +++ b/tests/OpenCloud/Tests/Database/ServiceTest.php @@ -78,7 +78,7 @@ public function testClientUsesTLSv1CipherSuite() { $client = $this->service->getClient(); $curlOptions = $client->getConfig('curl.options'); - $this->assertEquals(Service::SSL_CIPHER_LIST, $curlOptions['CURLOPT_SSL_CIPHER_LIST']); + $this->assertEquals(Service::getSslCipherList(), $curlOptions['CURLOPT_SSL_CIPHER_LIST']); $this->assertCriticalMessageWasLogged(); } } From befe7ea516cc869d802bca870414ac6110e96e6d Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 10:18:45 -0700 Subject: [PATCH 174/181] Fixing log message to match reality. --- lib/OpenCloud/Database/Service.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index 1098e6add..58c5ba260 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -121,7 +121,7 @@ public function setClient(ClientInterface $client) $curlOptions['CURLOPT_SSL_CIPHER_LIST'] = static::getSslCipherList(); $client->getConfig()->set('curl.options', $curlOptions); - $logMessage = 'The SDK is using the TLSv1 cipher suite when connecting ' + $logMessage = 'The SDK is using a custom cipher suite when connecting ' . 'to the Rackspace Cloud Databases service. This suite contains ' . 'a weak cipher (RC4) so please use at your own risk. See ' . 'https://github.com/rackspace/php-opencloud/issues/560 for details.'; From 20e05f60afa80d727ec2d997a1fe26f00962ec3a Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 10:20:01 -0700 Subject: [PATCH 175/181] Fixing unit test method name to match reality. --- tests/OpenCloud/Tests/Database/ServiceTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/OpenCloud/Tests/Database/ServiceTest.php b/tests/OpenCloud/Tests/Database/ServiceTest.php index a3f5f4401..96a6be1c6 100644 --- a/tests/OpenCloud/Tests/Database/ServiceTest.php +++ b/tests/OpenCloud/Tests/Database/ServiceTest.php @@ -74,7 +74,7 @@ public function testDatastoreList() $this->assertInstanceOf(self::COLLECTION_CLASS, $this->service->datastoreList()); } - public function testClientUsesTLSv1CipherSuite() + public function testClientUsesCustomCipherSuite() { $client = $this->service->getClient(); $curlOptions = $client->getConfig('curl.options'); From 806002d66094a6312adf436d6473c8c83c41f963 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 10:29:50 -0700 Subject: [PATCH 176/181] Refactoring logger into common class to enable reuse. --- .../Tests/Database/DatabaseTestCase.php | 19 ++-------- tests/OpenCloud/Tests/MockLogger.php | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 17 deletions(-) create mode 100644 tests/OpenCloud/Tests/MockLogger.php diff --git a/tests/OpenCloud/Tests/Database/DatabaseTestCase.php b/tests/OpenCloud/Tests/Database/DatabaseTestCase.php index c0a0b38e0..403f6955f 100644 --- a/tests/OpenCloud/Tests/Database/DatabaseTestCase.php +++ b/tests/OpenCloud/Tests/Database/DatabaseTestCase.php @@ -18,22 +18,7 @@ namespace OpenCloud\Tests\Database; use OpenCloud\Tests\OpenCloudTestCase; -use OpenCloud\Common\Log\Logger; - -class UnitTestLogger extends Logger -{ - protected $criticalLogMessage; - - public function critical($message, array $context = array()) - { - ++$this->criticalLogMessage; - } - - public function getCriticalLogMessage() - { - return $this->criticalLogMessage; - } -} +use OpenCloud\Tests\MockLogger; class DatabaseTestCase extends OpenCloudTestCase { @@ -45,7 +30,7 @@ class DatabaseTestCase extends OpenCloudTestCase public function setupObjects() { $client = $this->getClient(); - $client->setLogger(new UnitTestLogger()); + $client->setLogger(new MockLogger()); $this->service = $client->databaseService(); $this->addMockSubscriber($this->getTestFilePath('Instance')); diff --git a/tests/OpenCloud/Tests/MockLogger.php b/tests/OpenCloud/Tests/MockLogger.php new file mode 100644 index 000000000..9aca3dd68 --- /dev/null +++ b/tests/OpenCloud/Tests/MockLogger.php @@ -0,0 +1,35 @@ +criticalLogMessage; + } + + public function getCriticalLogMessage() + { + return $this->criticalLogMessage; + } +} From 819e94a63ffc03f3b8bddb0176cb0f78300fb884 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 10:30:04 -0700 Subject: [PATCH 177/181] Use mock logger for database service test to supress log output. --- tests/OpenCloud/Tests/RackspaceTest.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/OpenCloud/Tests/RackspaceTest.php b/tests/OpenCloud/Tests/RackspaceTest.php index 790d54645..7cf37f183 100644 --- a/tests/OpenCloud/Tests/RackspaceTest.php +++ b/tests/OpenCloud/Tests/RackspaceTest.php @@ -17,6 +17,8 @@ namespace OpenCloud\Tests; +use OpenCloud\Tests\MockLogger; + class RackspaceTest extends OpenCloudTestCase { const CREDENTIALS = <<getClient()->getLogger(); + $this->getClient()->setLogger(new MockLogger()); + $this->assertInstanceOf( 'OpenCloud\Database\Service', $this->getClient()->databaseService('cloudDatabases', 'DFW') ); + + // Re-inject old logger + $this->getClient()->setLogger($oldLogger); + $this->assertInstanceOf( 'OpenCloud\LoadBalancer\Service', $this->getClient()->loadBalancerService('cloudLoadBalancers', 'DFW') From 078f2d180ce2530d9cb514fe0ec0e5f276391908 Mon Sep 17 00:00:00 2001 From: Shaunak Kashyap Date: Mon, 16 Mar 2015 12:06:59 -0700 Subject: [PATCH 178/181] Adding reference to cipher list comment in docblock. --- lib/OpenCloud/Database/Service.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/OpenCloud/Database/Service.php b/lib/OpenCloud/Database/Service.php index 58c5ba260..de20872b6 100644 --- a/lib/OpenCloud/Database/Service.php +++ b/lib/OpenCloud/Database/Service.php @@ -130,6 +130,9 @@ public function setClient(ClientInterface $client) $this->client = $client; } + /** + * @see https://github.com/rackspace/php-opencloud/issues/560#issuecomment-81790778 + */ public static function getSslCipherList() { return 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:' From 5b5766af47abff68f1278fdc0827ef16d8cee61b Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 20 Mar 2015 15:00:34 +0100 Subject: [PATCH 179/181] [ci skip] Add more links to our official docs --- README.md | 2 +- docs/README.md | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 docs/README.md diff --git a/README.md b/README.md index 6031cf4ac..8ddd9f1b5 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ PHP SDK for OpenStack/Rackspace APIs [![Latest Stable Version](https://poser.pugx.org/rackspace/php-opencloud/v/stable.png)](https://packagist.org/packages/rackspace/php-opencloud) [![Travis CI](https://secure.travis-ci.org/rackspace/php-opencloud.png)](https://travis-ci.org/rackspace/php-opencloud) [![Total Downloads](https://poser.pugx.org/rackspace/php-opencloud/downloads.png)](https://packagist.org/packages/rackspace/php-opencloud) -For SDKs in different languages, see http://developer.rackspace.com. +Our official documentation is now available on http://docs.php-opencloud.com. For SDKs in different languages, see http://developer.rackspace.com. The PHP SDK should work with most OpenStack-based cloud deployments, though it specifically targets the Rackspace public cloud. In diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..154fd158d --- /dev/null +++ b/docs/README.md @@ -0,0 +1,3 @@ +# Documentation + +Our official docs are hosted on http://docs.php-opencloud.com. From c3297ae26906bb82d53e6769fbf84046191d5bb6 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Fri, 20 Mar 2015 17:42:30 +0100 Subject: [PATCH 180/181] [ci skip] Fix incorrect method in docs --- doc/services/object-store/objects.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/services/object-store/objects.rst b/doc/services/object-store/objects.rst index 0eb0ea836..7d9b2120e 100644 --- a/doc/services/object-store/objects.rst +++ b/doc/services/object-store/objects.rst @@ -204,8 +204,8 @@ Get file name .. code-block:: php - /** @param $container OpenCloud\ObjectStore\Resource\Container */ - $container = $object->getContainer(); + /** @param $name string */ + $name = $object->getName(); Get file size From 20af47912171e4238b7e26e26cee12782856cd72 Mon Sep 17 00:00:00 2001 From: Jamie Hannaford Date: Wed, 29 Apr 2015 11:25:03 +0200 Subject: [PATCH 181/181] Bump apigen version --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index fe720466b..059a07e5d 100644 --- a/composer.json +++ b/composer.json @@ -26,7 +26,7 @@ } }, "require": { - "php" : ">=5.3.3", + "php" : ">=5.4", "guzzle/http" : "~3.8", "psr/log": "~1.0", "mikemccabe/json-patch-php": "~0.1" @@ -36,6 +36,6 @@ "satooshi/php-coveralls": "0.6.*@dev", "jakub-onderka/php-parallel-lint": "0.*", "fabpot/php-cs-fixer": "1.0.*@dev", - "apigen/apigen": "~2.8" + "apigen/apigen": "~4.0" } }