Ejemplo n.º 1
0
 protected function init()
 {
     if ($this->container) {
         return;
     }
     // the OpenCloud client library will default to 'cloudFiles' if $serviceName is null
     $serviceName = null;
     if (isset($this->params['serviceName'])) {
         $serviceName = $this->params['serviceName'];
     }
     // the OpenCloud client library will default to 'publicURL' if $urlType is null
     $urlType = null;
     if (isset($this->params['urlType'])) {
         $urlType = $this->params['urlType'];
     }
     $this->objectStoreService = $this->client->objectStoreService($serviceName, $this->params['region'], $urlType);
     try {
         $this->container = $this->objectStoreService->getContainer($this->params['container']);
     } catch (ClientErrorResponseException $ex) {
         // if the container does not exist and autocreate is true try to create the container on the fly
         if (isset($this->params['autocreate']) && $this->params['autocreate'] === true) {
             $this->container = $this->objectStoreService->createContainer($this->params['container']);
         } else {
             throw $ex;
         }
     }
 }
Ejemplo n.º 2
0
 public function test_Paths()
 {
     $this->assertStringEndsWith('os-networksv2', (string) $this->service->network()->getUrl());
     $client = new OpenStack('http://identity.example.com/v2', array('username' => 'foo', 'password' => 'bar'));
     $response = $this->getTestFilePath('Auth_OpenStack', '.');
     $client->addSubscriber(new MockSubscriber(array($response)));
     $service = $client->computeService('compute', 'RegionOne', 'publicURL');
     $this->assertStringEndsWith('os-networks', (string) $service->network()->getUrl());
 }
Ejemplo n.º 3
0
 /**
  * Returns the file system provider
  *
  * @return \League\Flysystem\FilesystemInterface File system provider
  */
 protected function getProvider()
 {
     if (!isset($this->fs)) {
         $config = $this->getConfig();
         if (!isset($config['container'])) {
             throw new Exception(sprintf('Configuration option "%1$s" missing', 'container'));
         }
         $client = new OpenStack(Rackspace::UK_IDENTITY_ENDPOINT, $config);
         $container = $client->objectStoreService('cloudFiles', 'LON')->getContainer($config['container']);
         $this->fs = new Filesystem(new RackspaceAdapter($container));
     }
     return $this->fs;
 }
 /**
  * @inheritdoc
  */
 public function doCreateService(ServiceLocatorInterface $serviceLocator)
 {
     if (!class_exists('League\\Flysystem\\Rackspace\\RackspaceAdapter') || !class_exists('ProxyManager\\Factory\\LazyLoadingValueHolderFactory')) {
         throw new RequirementsException(['league/flysystem-rackspace', 'ocramius/proxy-manager'], 'Rackspace');
     }
     $proxy = $this->getLazyFactory($serviceLocator)->createProxy('League\\Flysystem\\Rackspace\\RackspaceAdapter', function (&$wrappedObject, $proxy, $method, $parameters, &$initializer) {
         $client = new OpenStack($this->options['url'], $this->options['secret'], $this->options['options']);
         $store = $client->objectStoreService($this->options['objectstore']['name'], $this->options['objectstore']['region'], $this->options['objectstore']['url_type']);
         $container = $store->getContainer($this->options['objectstore']['container']);
         $wrappedObject = new Adapter($container, $this->options['prefix']);
         return true;
     });
     return $proxy;
 }
    /**
     * @param array $credentials
     * @param string $endPoint
     * @param string $region
     * @param string $urlType
     * @throws \Tvision\RackspaceCloudFilesStreamWrapper\Exception\InvalidArgumentException
     * @return \OpenCloud\ObjectStore\Service
     */
    public static function newObjectStore(array $credentials, $endPoint = Rackspace::UK_IDENTITY_ENDPOINT, $region = 'LON', $urlType = 'publicURL')
    {
        if (isset($credentials['apiKey']) && isset($credentials['username'])) {
            $openCloudConnection = new Rackspace($endPoint, $credentials);
        } elseif (isset($credentials['password']) && isset($credentials['username'])) {
            $openCloudConnection = new OpenStack($endPoint, $credentials);
        } else {
            throw new InvalidArgumentException(<<<MSG
                The credentials must always contain an 'username' and a 'password' or
                an 'apiKey' if you are using rackspace.
MSG
);
        }
        return $openCloudConnection->objectStoreService('cloudFiles', $region, $urlType);
    }
Ejemplo n.º 6
0
 /**
  * Returns the connection
  *
  * @return OpenCloud\ObjectStore\Service connected client
  * @throws \Exception if connection could not be made
  */
 public function getConnection()
 {
     if (!is_null($this->connection)) {
         return $this->connection;
     }
     $settings = array('username' => $this->params['user']);
     if (!empty($this->params['password'])) {
         $settings['password'] = $this->params['password'];
     } else {
         if (!empty($this->params['key'])) {
             $settings['apiKey'] = $this->params['key'];
         }
     }
     if (!empty($this->params['tenant'])) {
         $settings['tenantName'] = $this->params['tenant'];
     }
     if (!empty($this->params['timeout'])) {
         $settings['timeout'] = $this->params['timeout'];
     }
     if (isset($settings['apiKey'])) {
         $this->anchor = new Rackspace($this->params['url'], $settings);
     } else {
         $this->anchor = new OpenStack($this->params['url'], $settings);
     }
     $connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
     if (!empty($this->params['endpoint_url'])) {
         $endpoint = $connection->getEndpoint();
         $endpoint->setPublicUrl($this->params['endpoint_url']);
         $endpoint->setPrivateUrl($this->params['endpoint_url']);
         $connection->setEndpoint($endpoint);
     }
     $this->connection = $connection;
     return $this->connection;
 }
Ejemplo n.º 7
0
 /**
  * Check whether required secret keys are set and return OVH API credentials
  * {@inheritDoc}
  */
 public function getCredentials()
 {
     $secret = $this->getSecret();
     if (!isset($secret['username']) || !isset($secret['password'])) {
         throw new CredentialError('Unrecognized credential secret');
     }
     return parent::getCredentials();
 }
Ejemplo n.º 8
0
 public function __construct($url, $secret, $options = array())
 {
     $this->testDir = __DIR__;
     if (is_array($secret)) {
         return parent::__construct($url, $secret, $options);
     } else {
         return parent::__construct($url, array('username' => 'X', 'password' => 'Y'), $options);
     }
 }
Ejemplo n.º 9
0
 /**
  * Returns the connection
  *
  * @return OpenCloud\ObjectStore\Service connected client
  * @throws \Exception if connection could not be made
  */
 public function getConnection()
 {
     if (!is_null($this->connection)) {
         return $this->connection;
     }
     $this->anchor = new OpenStack(hubicAuth::HUBIC_URI_BASE, array());
     if (!isset($this->credentials)) {
         $this->retrieveCredentials();
     }
     $this->importCredentials();
     $this->connection = $this->anchor->objectStoreService('cloudFiles', 'NCE');
     return $this->connection;
 }
Ejemplo n.º 10
0
 /**
  * Returns the connection
  *
  * @return OpenCloud\ObjectStore\Service connected client
  * @throws \Exception if connection could not be made
  */
 public function getConnection()
 {
     if (!is_null($this->connection)) {
         return $this->connection;
     }
     $this->anchor = new OpenStack('https://api.hubic.com/');
     if ($this->params['swift_token'] == 'false') {
         $this->retreiveCredentials();
     }
     $this->importCredentials();
     $this->connection = $this->anchor->objectStoreService('cloudFiles', 'NCE');
     return $this->connection;
 }
Ejemplo n.º 11
0
 public function get_service($opts, $useservercerts = false, $disablesslverify = null)
 {
     # 'tenant', 'user', 'password', 'authurl', 'path', (optional) 'region'
     extract($opts);
     if (null === $disablesslverify) {
         $disablesslverify = UpdraftPlus_Options::get_updraft_option('updraft_ssl_disableverify');
     }
     if (empty($user) || empty($password) || empty($authurl)) {
         throw new Exception(__('Authorisation failed (check your credentials)', 'updraftplus'));
     }
     require_once UPDRAFTPLUS_DIR . '/oc/autoload.php';
     global $updraftplus;
     $updraftplus->log("OpenStack authentication URL: " . $authurl);
     $client = new OpenStack($authurl, array('username' => $user, 'password' => $password, 'tenantName' => $tenant));
     $this->client = $client;
     if ($disablesslverify) {
         $client->setSslVerification(false);
     } else {
         if ($useservercerts) {
             $client->setConfig(array($client::SSL_CERT_AUTHORITY => false));
         } else {
             $client->setSslVerification(UPDRAFTPLUS_DIR . '/includes/cacert.pem', true, 2);
         }
     }
     $client->authenticate();
     if (empty($region)) {
         $catalog = $client->getCatalog();
         if (!empty($catalog)) {
             $items = $catalog->getItems();
             if (is_array($items)) {
                 foreach ($items as $item) {
                     $name = $item->getName();
                     $type = $item->getType();
                     if ('swift' != $name || 'object-store' != $type) {
                         continue;
                     }
                     $eps = $item->getEndpoints();
                     if (!is_array($eps)) {
                         continue;
                     }
                     foreach ($eps as $ep) {
                         if (is_object($ep) && !empty($ep->region)) {
                             $region = $ep->region;
                         }
                     }
                 }
             }
         }
     }
     $this->region = $region;
     return $client->objectStoreService('swift', $region);
 }
Ejemplo n.º 12
0
 public function __construct($params)
 {
     if (empty($params['key']) and empty($params['password']) or empty($params['user']) or empty($params['bucket']) or empty($params['region'])) {
         throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
     }
     $this->id = 'swift::' . $params['user'] . md5($params['bucket']);
     $this->bucket = $params['bucket'];
     if (empty($params['url'])) {
         $params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
     }
     if (empty($params['service_name'])) {
         $params['service_name'] = 'cloudFiles';
     }
     $settings = array('username' => $params['user']);
     if (!empty($params['password'])) {
         $settings['password'] = $params['password'];
     } else {
         if (!empty($params['key'])) {
             $settings['apiKey'] = $params['key'];
         }
     }
     if (!empty($params['tenant'])) {
         $settings['tenantName'] = $params['tenant'];
     }
     if (!empty($params['timeout'])) {
         $settings['timeout'] = $params['timeout'];
     }
     if (isset($settings['apiKey'])) {
         $this->anchor = new Rackspace($params['url'], $settings);
     } else {
         $this->anchor = new OpenStack($params['url'], $settings);
     }
     $this->connection = $this->anchor->objectStoreService($params['service_name'], $params['region']);
     try {
         $this->container = $this->connection->getContainer($this->bucket);
     } catch (ClientErrorResponseException $e) {
         $this->container = $this->connection->createContainer($this->bucket);
     }
     if (!$this->file_exists('.')) {
         $this->mkdir('.');
     }
 }
Ejemplo n.º 13
0
 public function __construct($params)
 {
     if (!isset($params['key']) and !isset($params['password']) or !isset($params['user']) or !isset($params['bucket']) or !isset($params['region'])) {
         throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
     }
     $this->id = 'swift::' . $params['user'] . md5($params['bucket']);
     $this->bucket = $params['bucket'];
     if (!isset($params['url'])) {
         $params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
     }
     if (!isset($params['service_name'])) {
         $params['service_name'] = 'cloudFiles';
     }
     $settings = array('username' => $params['user']);
     if (isset($params['password'])) {
         $settings['password'] = $params['password'];
     } else {
         if (isset($params['key'])) {
             $settings['apiKey'] = $params['key'];
         }
     }
     if (isset($params['tenant'])) {
         $settings['tenantName'] = $params['tenant'];
     }
     $this->anchor = new \OpenCloud\OpenStack($params['url'], $settings);
     if (isset($params['timeout'])) {
         $this->anchor->setHttpTimeout($params['timeout']);
     }
     $this->connection = $this->anchor->ObjectStore($params['service_name'], $params['region'], 'publicURL');
     try {
         $this->container = $this->connection->Container($this->bucket);
     } catch (Exceptions\ContainerNotFoundError $e) {
         $this->container = $this->connection->Container();
         $this->container->Create(array('name' => $this->bucket));
     }
     if (!$this->file_exists('.')) {
         $this->mkdir('.');
     }
 }
Ejemplo n.º 14
0
 /**
  * Returns the connection
  *
  * @return OpenCloud\ObjectStore\Service connected client
  * @throws \Exception if connection could not be made
  */
 public function getConnection()
 {
     if (!is_null($this->connection)) {
         return $this->connection;
     }
     $settings = array('username' => $this->params['user']);
     if (!empty($this->params['password'])) {
         $settings['password'] = $this->params['password'];
     } else {
         if (!empty($this->params['key'])) {
             $settings['apiKey'] = $this->params['key'];
         }
     }
     if (!empty($this->params['tenant'])) {
         $settings['tenantName'] = $this->params['tenant'];
     }
     if (!empty($this->params['timeout'])) {
         $settings['timeout'] = $this->params['timeout'];
     }
     $this->anchor = new OpenStack($this->params['url'], $settings);
     $this->connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
     return $this->connection;
 }
Ejemplo n.º 15
0
 /**
  * Returns the endpoint URL with a version in it
  *
  * @param string $url Endpoint URL
  * @param string $supportedServiceVersion Service version supported by the SDK
  * @param OpenCloud\OpenStack $client OpenStack client
  * @return Guzzle/Http/Url Endpoint URL with version in it
  */
 private function getVersionedUrl($url, $supportedServiceVersion, OpenStack $client)
 {
     $versionRegex = '/\\/[vV][0-9][0-9\\.]*/';
     if (1 === preg_match($versionRegex, $url)) {
         // URL has version in it; use it as-is
         return Url::factory($url);
     }
     // If there is no version in $url but no $supportedServiceVersion
     // is specified, just return $url as-is but log a warning
     if (is_null($supportedServiceVersion)) {
         $client->getLogger()->warning('Service version supported by SDK not specified. Using versionless service URL as-is, without negotiating version.');
         return Url::factory($url);
     }
     // Make GET request to URL
     $response = Formatter::decode($client->get($url)->send());
     // Attempt to parse response and determine URL for given $version
     if (!isset($response->versions) || !is_array($response->versions)) {
         throw new UnsupportedVersionError('Could not negotiate version with service.');
     }
     foreach ($response->versions as $version) {
         if (($version->status == 'CURRENT' || $version->status == 'SUPPORTED') && $version->id == $supportedServiceVersion) {
             foreach ($version->links as $link) {
                 if ($link->rel == 'self') {
                     return Url::factory($link->href);
                 }
             }
         }
     }
     // If we've reached this point, we could not find a versioned
     // URL in the response; throw an error
     throw new UnsupportedVersionError(sprintf('SDK supports version %s which is not currently provided by service.', $supportedServiceVersion));
 }
<?php

/**
 * Copyright 2012-2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
require dirname(__DIR__) . '/../vendor/autoload.php';
use OpenCloud\OpenStack;
// 1. Instantiate an OpenStack client.
$client = new OpenStack('{authUrl}', array('username' => '{username}', 'password' => '{password}'));
// 2. Obtain an Orchestration service object from the client.
$orchestrationService = $client->orchestrationService(null, '{region}');
// 3. Get stack.
$stack = $orchestrationService->getStack('{stackName}');
// 4. Get resource in stack.
$resource = $stack->getResource('{stackResourceName}');
// 5. Get stack resource event.
/** @var $resourceEvent OpenCloud\Orchestration\Resource\Event **/
$resourceEvent = $resource->getEvent('{stackResourceEventId}');
Ejemplo n.º 17
0
 /**
  * @expectedException OpenCloud\Common\Exceptions\CredentialError
  */
 public function test_Credentials_Fail()
 {
     $client = new OpenStack(Rackspace::US_IDENTITY_ENDPOINT, array());
     $client->getCredentials();
 }
 /**
  * {@inheritdoc}
  */
 public function getObjectStore()
 {
     return $this->connection->objectStoreService('cloudFiles', $this->region, $this->urlType);
 }
Ejemplo n.º 19
0
 public function __construct($url, array $secret, $region, array $options = array())
 {
     parent::__construct($url, $secret, $options);
     $this->region = $region;
 }
Ejemplo n.º 20
0
 /**
  * @param array $config
  * @return Flysystem
  */
 public function get(array $config)
 {
     $client = new OpenStack($config['endpoint'], ['username' => $config['username'], 'password' => $config['key']]);
     $container = $client->objectStoreService('cloudFiles', $config['zone'])->getContainer($config['container']);
     return new Flysystem(new RackspaceAdapter($container, $config['root']));
 }
 /**
  * @param array $config
  *
  * @throws InvalidArgumentException
  * @throws DfException
  */
 public function __construct($config)
 {
     $storageType = strtolower(ArrayUtils::get($config, 'storage_type'));
     $credentials = $config;
     $this->container = ArrayUtils::get($config, 'container');
     Session::replaceLookups($credentials, true);
     switch ($storageType) {
         case 'rackspace cloudfiles':
             $authUrl = ArrayUtils::get($credentials, 'url', 'https://identity.api.rackspacecloud.com/');
             $region = ArrayUtils::get($credentials, 'region', 'DFW');
             break;
         default:
             $authUrl = ArrayUtils::get($credentials, 'url');
             $region = ArrayUtils::get($credentials, 'region');
             break;
     }
     $username = ArrayUtils::get($credentials, 'username');
     $password = ArrayUtils::get($credentials, 'password');
     $apiKey = ArrayUtils::get($credentials, 'api_key');
     $tenantName = ArrayUtils::get($credentials, 'tenant_name');
     if (empty($authUrl)) {
         throw new InvalidArgumentException('Object Store authentication URL can not be empty.');
     }
     if (empty($username)) {
         throw new InvalidArgumentException('Object Store username can not be empty.');
     }
     $secret = ['username' => $username];
     if (empty($apiKey)) {
         if (empty($password)) {
             throw new InvalidArgumentException('Object Store credentials must contain an API key or a password.');
         }
         $secret['password'] = $password;
     } else {
         $secret['apiKey'] = $apiKey;
     }
     if (!empty($tenantName)) {
         $secret['tenantName'] = $tenantName;
     }
     if (empty($region)) {
         throw new InvalidArgumentException('Object Store region can not be empty.');
     }
     try {
         switch ($storageType) {
             case 'rackspace cloudfiles':
                 $pos = stripos($authUrl, '/v');
                 if (false !== $pos) {
                     $authUrl = substr($authUrl, 0, $pos);
                 }
                 $authUrl = FileUtilities::fixFolderPath($authUrl) . 'v2.0';
                 $os = new Rackspace($authUrl, $secret);
                 break;
             default:
                 $os = new OpenStack($authUrl, $secret);
                 break;
         }
         $this->blobConn = $os->ObjectStore('cloudFiles', $region);
         if (!$this->containerExists($this->container)) {
             $this->createContainer(['name' => $this->container]);
         }
     } catch (\Exception $ex) {
         throw new DfException('Failed to launch OpenStack service: ' . $ex->getMessage());
     }
 }
Ejemplo n.º 22
0
 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()));
 }
 * Copyright 2014 Rackspace US, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
require dirname(__DIR__) . '/../vendor/autoload.php';
use OpenCloud\OpenStack;
use Guzzle\Http\Exception\BadResponseException;
// 1. Instantiate a OpenStack client. You can replace {authUrl} with
// OpenStack::US_IDENTITY_ENDPOINT or similar
$client = new OpenStack('{authUrl}', array('username' => '{username}', 'password' => '{password}'));
// 2. Create Compute service
$service = $client->computeService('nova', '{region}');
// 3. Get empty server
$server = $service->server();
// 4. Create the server. If you do not know what imageId or flavorId to use,
// please run the list_flavors.php and list_images.php scripts.
try {
    $response = $server->create(array('name' => '{serverName}', 'imageId' => '{imageId}', 'flavorId' => '{flavorId}', 'availabilityZone' => '{availabilityZone}'));
} catch (BadResponseException $e) {
    echo $e->getResponse();
}
Ejemplo n.º 24
0
 /**
  * Generates Rackspace API key credentials
  * {@inheritDoc}
  */
 public function getCredentials()
 {
     $secret = $this->getSecret();
     return !empty($secret['username']) && !empty($secret['apiKey']) ? sprintf(self::CREDS_TEMPLATE, $secret['username'], $secret['apiKey']) : parent::getCredentials();
 }
Ejemplo n.º 25
0
    exit(1);
}
$files = $parameters["files"];
$containerName = $parameters["container"];
$configFile = $parameters["config"];
if (!file_exists($configFile)) {
    echo "The configuration file '{$configFile}' does not exist.\n\n";
    exit(2);
}
$ocParameters = json_decode(file_get_contents($configFile));
if (!$ocParameters) {
    echo "The configuration file '{$configFile}' content is not valid JSON.\n\n";
    exit(3);
}
// Initialization
$client = new OpenStack($ocParameters->authUrl, array("username" => $ocParameters->username, "password" => $ocParameters->password, "tenantName" => $ocParameters->tenant));
$swiftUrl = $ocParameters->swiftUrl;
$serviceName = $ocParameters->serviceName;
$region = $ocParameters->region;
try {
    $client->authenticate();
    $service = $client->objectStoreService($serviceName, $region);
    $container = $service->createContainer($containerName);
    if ($container === false) {
        echo "The container '{$containerName}' already exists.\n";
    } else {
        echo "The container '{$containerName}' has been successfully created.\n";
    }
    $container = $service->getContainer($containerName);
    foreach (glob($files) as $filename) {
        echo "Sending {$filename} (" . number_format(filesize($filename) / 1024 / 1024, 2) . " MB)...\n";
Ejemplo n.º 26
0
 /**
  * {@inheritdoc}
  */
 public function getObjectStore()
 {
     return $this->connection->objectStoreService($this->objectStoreType, $this->region, $this->urlType);
 }