Completed
Push — master ( a82716...45895d )
by Morris
92:02 queued 48:20
created

SwiftFactory   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 158
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 158
rs 8.8
c 0
b 0
f 0
wmc 36
lcom 1
cbo 6

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getCachedToken() 0 8 2
A cacheToken() 0 8 2
F getClient() 0 41 14
C auth() 0 29 8
A getContainer() 0 7 2
C createContainer() 0 28 7
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2018 Robin Appelman <[email protected]>
5
 *
6
 * @license GNU AGPL version 3 or any later version
7
 *
8
 * This program is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License as
10
 * published by the Free Software Foundation, either version 3 of the
11
 * License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
 *
21
 */
22
23
namespace OC\Files\ObjectStore;
24
25
use GuzzleHttp\Client;
26
use GuzzleHttp\Exception\ClientException;
27
use GuzzleHttp\Exception\ConnectException;
28
use GuzzleHttp\Exception\RequestException;
29
use GuzzleHttp\HandlerStack;
30
use OCP\Files\StorageAuthException;
31
use OCP\Files\StorageNotAvailableException;
32
use OCP\ICache;
33
use OpenStack\Common\Error\BadResponseError;
34
use OpenStack\Common\Auth\Token;
35
use OpenStack\Identity\v2\Service as IdentityV2Service;
36
use OpenStack\Identity\v3\Service as IdentityV3Service;
37
use OpenStack\OpenStack;
38
use OpenStack\Common\Transport\Utils as TransportUtils;
39
use Psr\Http\Message\RequestInterface;
40
use OpenStack\ObjectStore\v1\Models\Container;
41
42
class SwiftFactory {
43
	private $cache;
44
	private $params;
45
	/** @var Container|null */
46
	private $container = null;
47
48
	public function __construct(ICache $cache, array $params) {
49
		$this->cache = $cache;
50
		$this->params = $params;
51
	}
52
53
	private function getCachedToken(string $cacheKey) {
54
		$cachedTokenString = $this->cache->get($cacheKey . '/token');
55
		if ($cachedTokenString) {
56
			return json_decode($cachedTokenString);
57
		} else {
58
			return null;
59
		}
60
	}
61
62
	private function cacheToken(Token $token, string $cacheKey) {
63
		if ($token instanceof \OpenStack\Identity\v3\Models\Token) {
0 ignored issues
show
Bug introduced by
The class OpenStack\Identity\v3\Models\Token does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
64
			$value = json_encode($token->export());
65
		} else {
66
			$value = json_encode($token);
67
		}
68
		$this->cache->set($cacheKey . '/token', $value);
69
	}
70
71
	/**
72
	 * @return OpenStack
73
	 * @throws StorageAuthException
74
	 */
75
	private function getClient() {
76
		if (isset($this->params['bucket'])) {
77
			$this->params['container'] = $this->params['bucket'];
78
		}
79
		if (!isset($this->params['container'])) {
80
			$this->params['container'] = 'owncloud';
81
		}
82
		if (!isset($this->params['autocreate'])) {
83
			// should only be true for tests
84
			$this->params['autocreate'] = false;
85
		}
86
		if (isset($this->params['user']) && is_array($this->params['user'])) {
87
			$userName = $this->params['user']['name'];
88
		} else {
89
			if (!isset($this->params['username']) && isset($this->params['user'])) {
90
				$this->params['username'] = $this->params['user'];
91
			}
92
			$userName = $this->params['username'];
93
		}
94
		if (!isset($this->params['tenantName']) && isset($this->params['tenant'])) {
95
			$this->params['tenantName'] = $this->params['tenant'];
96
		}
97
98
		$cacheKey = $userName . '@' . $this->params['url'] . '/' . $this->params['bucket'];
99
		$token = $this->getCachedToken($cacheKey);
100
		$hasToken = is_array($token) && (new \DateTimeImmutable($token['expires_at'])) > (new \DateTimeImmutable('now'));
101
		if ($hasToken) {
102
			$this->params['cachedToken'] = $token;
103
		}
104
105
		$httpClient = new Client([
106
			'base_uri' => TransportUtils::normalizeUrl($this->params['url']),
107
			'handler' => HandlerStack::create()
108
		]);
109
110
		if (isset($this->params['user']) && isset($this->params['user']['name'])) {
111
			return $this->auth(IdentityV3Service::factory($httpClient), $cacheKey);
112
		} else {
113
			return $this->auth(IdentityV2Service::factory($httpClient), $cacheKey);
114
		}
115
	}
116
117
	/**
118
	 * @param IdentityV2Service|IdentityV3Service $authService
119
	 * @param string $cacheKey
120
	 * @return OpenStack
121
	 * @throws StorageAuthException
122
	 */
123
	private function auth($authService, string $cacheKey) {
124
		$this->params['identityService'] = $authService;
125
		$this->params['authUrl'] = $this->params['url'];
126
		$client = new OpenStack($this->params);
127
128
		if (!isset($this->params['cachedToken'])) {
129
			try {
130
				$token = $authService->generateToken($this->params);
131
				$this->cacheToken($token, $cacheKey);
132
			} catch (ConnectException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ConnectException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
133
				throw new StorageAuthException('Failed to connect to keystone, verify the keystone url', $e);
134
			} catch (ClientException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ClientException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
135
				$statusCode = $e->getResponse()->getStatusCode();
136
				if ($statusCode === 404) {
137
					throw new StorageAuthException('Keystone not found, verify the keystone url', $e);
138
				} else if ($statusCode === 412) {
139
					throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
140
				} else if ($statusCode === 401) {
141
					throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
142
				} else {
143
					throw new StorageAuthException('Unknown error', $e);
144
				}
145
			} catch (RequestException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\RequestException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
146
				throw new StorageAuthException('Connection reset while connecting to keystone, verify the keystone url', $e);
147
			}
148
		}
149
150
		return $client;
151
	}
152
153
	/**
154
	 * @return \OpenStack\ObjectStore\v1\Models\Container
155
	 * @throws StorageAuthException
156
	 * @throws StorageNotAvailableException
157
	 */
158
	public function getContainer() {
159
		if (is_null($this->container)) {
160
			$this->container = $this->createContainer();
161
		}
162
163
		return $this->container;
164
	}
165
166
	/**
167
	 * @return \OpenStack\ObjectStore\v1\Models\Container
168
	 * @throws StorageAuthException
169
	 * @throws StorageNotAvailableException
170
	 */
171
	private function createContainer() {
172
		$client = $this->getClient();
173
		$objectStoreService = $client->objectStoreV1();
174
175
		$autoCreate = isset($this->params['autocreate']) && $this->params['autocreate'] === true;
176
		try {
177
			$container = $objectStoreService->getContainer($this->params['container']);
178
			if ($autoCreate) {
179
				$container->getMetadata();
180
			}
181
			return $container;
182
		} catch (BadResponseError $ex) {
0 ignored issues
show
Bug introduced by
The class OpenStack\Common\Error\BadResponseError does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
183
			// if the container does not exist and autocreate is true try to create the container on the fly
184
			if ($ex->getResponse()->getStatusCode() === 404 && $autoCreate) {
185
				return $objectStoreService->createContainer([
186
					'name' => $this->params['container']
187
				]);
188
			} else {
189
				throw new StorageNotAvailableException('Invalid response while trying to get container info', StorageNotAvailableException::STATUS_ERROR, $e);
190
			}
191
		} catch (ConnectException $e) {
0 ignored issues
show
Bug introduced by
The class GuzzleHttp\Exception\ConnectException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
192
			/** @var RequestInterface $request */
193
			$request = $e->getRequest();
194
			$host = $request->getUri()->getHost() . ':' . $request->getUri()->getPort();
195
			\OC::$server->getLogger()->error("Can't connect to object storage server at $host");
196
			throw new StorageNotAvailableException("Can't connect to object storage server at $host", StorageNotAvailableException::STATUS_ERROR, $e);
197
		}
198
	}
199
}
200