Completed
Pull Request — master (#4116)
by Robin
19:23
created
lib/private/Files/ObjectStore/Swift.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,6 @@
 block discarded – undo
28 28
 use OCP\Files\ObjectStore\IObjectStore;
29 29
 use OCP\Files\StorageAuthException;
30 30
 use OCP\Files\StorageNotAvailableException;
31
-use OpenCloud\Common\Exceptions\EndpointError;
32 31
 use OpenCloud\Common\Service\Catalog;
33 32
 use OpenCloud\Common\Service\CatalogItem;
34 33
 use OpenCloud\Identity\Resource\Token;
Please login to merge, or discard this patch.
Indentation   +244 added lines, -244 removed lines patch added patch discarded remove patch
@@ -38,249 +38,249 @@
 block discarded – undo
38 38
 
39 39
 class Swift implements IObjectStore {
40 40
 
41
-	/**
42
-	 * @var \OpenCloud\OpenStack
43
-	 */
44
-	private $client;
45
-
46
-	/**
47
-	 * @var array
48
-	 */
49
-	private $params;
50
-
51
-	/**
52
-	 * @var \OpenCloud\ObjectStore\Service
53
-	 */
54
-	private $objectStoreService;
55
-
56
-	/**
57
-	 * @var \OpenCloud\ObjectStore\Resource\Container
58
-	 */
59
-	private $container;
60
-
61
-	private $memcache;
62
-
63
-	public function __construct($params) {
64
-		if (isset($params['bucket'])) {
65
-			$params['container'] = $params['bucket'];
66
-		}
67
-		if (!isset($params['container'])) {
68
-			$params['container'] = 'owncloud';
69
-		}
70
-		if (!isset($params['autocreate'])) {
71
-			// should only be true for tests
72
-			$params['autocreate'] = false;
73
-		}
74
-
75
-		if (isset($params['apiKey'])) {
76
-			$this->client = new Rackspace($params['url'], $params);
77
-			$cacheKey = $this->params['username'] . '@' . $this->params['url'] . '/' . $this->params['bucket'];
78
-		} else {
79
-			$this->client = new OpenStack($params['url'], $params);
80
-			$cacheKey = $this->params['username'] . '@' . $this->params['url'] . '/' . $this->params['bucket'];
81
-		}
82
-
83
-		$cacheFactory = \OC::$server->getMemCacheFactory();
84
-		$this->memcache = $cacheFactory->create('swift::' . $cacheKey);
85
-
86
-		$this->params = $params;
87
-	}
88
-
89
-	protected function init() {
90
-		if ($this->container) {
91
-			return;
92
-		}
93
-
94
-		$this->importToken();
95
-
96
-		/** @var Token $token */
97
-		$token = $this->client->getTokenObject();
98
-
99
-		if (!$token || $token->hasExpired()) {
100
-			try {
101
-				$this->client->authenticate();
102
-				$this->exportToken();
103
-			} catch (ClientErrorResponseException $e) {
104
-				$statusCode = $e->getResponse()->getStatusCode();
105
-				if ($statusCode == 412) {
106
-					throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
107
-				} else if ($statusCode === 401) {
108
-					throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
109
-				} else {
110
-					throw new StorageAuthException('Unknown error', $e);
111
-				}
112
-			}
113
-		}
114
-
115
-
116
-		/** @var Catalog $catalog */
117
-		$catalog = $this->client->getCatalog();
118
-
119
-		if (isset($this->params['serviceName'])) {
120
-			$serviceName = $this->params['serviceName'];
121
-		} else {
122
-			$serviceName = Service::DEFAULT_NAME;
123
-		}
124
-
125
-		if (isset($this->params['urlType'])) {
126
-			$urlType = $this->params['urlType'];
127
-			if ($urlType !== 'internalURL' && $urlType !== 'publicURL') {
128
-				throw new StorageNotAvailableException('Invalid url type');
129
-			}
130
-		} else {
131
-			$urlType = Service::DEFAULT_URL_TYPE;
132
-		}
133
-
134
-		$catalogItem = $this->getCatalogForService($catalog, $serviceName);
135
-		if (!$catalogItem) {
136
-			$available = implode(', ', $this->getAvailableServiceNames($catalog));
137
-			throw new StorageNotAvailableException(
138
-				"Service $serviceName not found in service catalog, available services: $available"
139
-			);
140
-		} else if (isset($this->params['region'])) {
141
-			$this->validateRegion($catalogItem, $this->params['region']);
142
-		}
143
-
144
-		$this->objectStoreService = $this->client->objectStoreService($serviceName, $this->params['region'], $urlType);
145
-
146
-		try {
147
-			$this->container = $this->objectStoreService->getContainer($this->params['container']);
148
-		} catch (ClientErrorResponseException $ex) {
149
-			// if the container does not exist and autocreate is true try to create the container on the fly
150
-			if (isset($this->params['autocreate']) && $this->params['autocreate'] === true) {
151
-				$this->container = $this->objectStoreService->createContainer($this->params['container']);
152
-			} else {
153
-				throw $ex;
154
-			}
155
-		}
156
-	}
157
-
158
-	private function exportToken() {
159
-		$export = $this->client->exportCredentials();
160
-		$export['catalog'] = array_map(function (CatalogItem $item) {
161
-			return [
162
-				'name' => $item->getName(),
163
-				'endpoints' => $item->getEndpoints(),
164
-				'type' => $item->getType()
165
-			];
166
-		}, $export['catalog']->getItems());
167
-		$this->memcache->set('token', json_encode($export));
168
-	}
169
-
170
-	private function importToken() {
171
-		$cachedTokenString = $this->memcache->get('token');
172
-		if ($cachedTokenString) {
173
-			$cachedToken = json_decode($cachedTokenString, true);
174
-			$cachedToken['catalog'] = array_map(function (array $item) {
175
-				$itemClass = new \stdClass();
176
-				$itemClass->name = $item['name'];
177
-				$itemClass->endpoints = array_map(function (array $endpoint) {
178
-					return (object) $endpoint;
179
-				}, $item['endpoints']);
180
-				$itemClass->type = $item['type'];
181
-
182
-				return $itemClass;
183
-			}, $cachedToken['catalog']);
184
-			try {
185
-				$this->client->importCredentials($cachedToken);
186
-			} catch (\Exception $e) {
187
-				$this->client->setTokenObject(new Token());
188
-			}
189
-		}
190
-	}
191
-
192
-	/**
193
-	 * @param Catalog $catalog
194
-	 * @param $name
195
-	 * @return null|CatalogItem
196
-	 */
197
-	private function getCatalogForService(Catalog $catalog, $name) {
198
-		foreach ($catalog->getItems() as $item) {
199
-			/** @var CatalogItem $item */
200
-			if ($item->hasType(Service::DEFAULT_TYPE) && $item->hasName($name)) {
201
-				return $item;
202
-			}
203
-		}
204
-
205
-		return null;
206
-	}
207
-
208
-	private function validateRegion(CatalogItem $item, $region) {
209
-		$endPoints = $item->getEndpoints();
210
-		foreach ($endPoints as $endPoint) {
211
-			if ($endPoint->region === $region) {
212
-				return;
213
-			}
214
-		}
215
-
216
-		$availableRegions = implode(', ', array_map(function ($endpoint) {
217
-			return $endpoint->region;
218
-		}, $endPoints));
219
-
220
-		throw new StorageNotAvailableException("Invalid region '$region', available regions: $availableRegions");
221
-	}
222
-
223
-	private function getAvailableServiceNames(Catalog $catalog) {
224
-		return array_map(function (CatalogItem $item) {
225
-			return $item->getName();
226
-		}, array_filter($catalog->getItems(), function (CatalogItem $item) {
227
-			return $item->hasType(Service::DEFAULT_TYPE);
228
-		}));
229
-	}
230
-
231
-	/**
232
-	 * @return string the container name where objects are stored
233
-	 */
234
-	public function getStorageId() {
235
-		return $this->params['container'];
236
-	}
237
-
238
-	/**
239
-	 * @param string $urn the unified resource name used to identify the object
240
-	 * @param resource $stream stream with the data to write
241
-	 * @throws Exception from openstack lib when something goes wrong
242
-	 */
243
-	public function writeObject($urn, $stream) {
244
-		$this->init();
245
-		$this->container->uploadObject($urn, $stream);
246
-	}
247
-
248
-	/**
249
-	 * @param string $urn the unified resource name used to identify the object
250
-	 * @return resource stream with the read data
251
-	 * @throws Exception from openstack lib when something goes wrong
252
-	 */
253
-	public function readObject($urn) {
254
-		$this->init();
255
-		$object = $this->container->getObject($urn);
256
-
257
-		// we need to keep a reference to objectContent or
258
-		// the stream will be closed before we can do anything with it
259
-		/** @var $objectContent \Guzzle\Http\EntityBody * */
260
-		$objectContent = $object->getContent();
261
-		$objectContent->rewind();
262
-
263
-		$stream = $objectContent->getStream();
264
-		// save the object content in the context of the stream to prevent it being gc'd until the stream is closed
265
-		stream_context_set_option($stream, 'swift', 'content', $objectContent);
266
-
267
-		return $stream;
268
-	}
269
-
270
-	/**
271
-	 * @param string $urn Unified Resource Name
272
-	 * @return void
273
-	 * @throws Exception from openstack lib when something goes wrong
274
-	 */
275
-	public function deleteObject($urn) {
276
-		$this->init();
277
-		// see https://github.com/rackspace/php-opencloud/issues/243#issuecomment-30032242
278
-		$this->container->dataObject()->setName($urn)->delete();
279
-	}
280
-
281
-	public function deleteContainer($recursive = false) {
282
-		$this->init();
283
-		$this->container->delete($recursive);
284
-	}
41
+    /**
42
+     * @var \OpenCloud\OpenStack
43
+     */
44
+    private $client;
45
+
46
+    /**
47
+     * @var array
48
+     */
49
+    private $params;
50
+
51
+    /**
52
+     * @var \OpenCloud\ObjectStore\Service
53
+     */
54
+    private $objectStoreService;
55
+
56
+    /**
57
+     * @var \OpenCloud\ObjectStore\Resource\Container
58
+     */
59
+    private $container;
60
+
61
+    private $memcache;
62
+
63
+    public function __construct($params) {
64
+        if (isset($params['bucket'])) {
65
+            $params['container'] = $params['bucket'];
66
+        }
67
+        if (!isset($params['container'])) {
68
+            $params['container'] = 'owncloud';
69
+        }
70
+        if (!isset($params['autocreate'])) {
71
+            // should only be true for tests
72
+            $params['autocreate'] = false;
73
+        }
74
+
75
+        if (isset($params['apiKey'])) {
76
+            $this->client = new Rackspace($params['url'], $params);
77
+            $cacheKey = $this->params['username'] . '@' . $this->params['url'] . '/' . $this->params['bucket'];
78
+        } else {
79
+            $this->client = new OpenStack($params['url'], $params);
80
+            $cacheKey = $this->params['username'] . '@' . $this->params['url'] . '/' . $this->params['bucket'];
81
+        }
82
+
83
+        $cacheFactory = \OC::$server->getMemCacheFactory();
84
+        $this->memcache = $cacheFactory->create('swift::' . $cacheKey);
85
+
86
+        $this->params = $params;
87
+    }
88
+
89
+    protected function init() {
90
+        if ($this->container) {
91
+            return;
92
+        }
93
+
94
+        $this->importToken();
95
+
96
+        /** @var Token $token */
97
+        $token = $this->client->getTokenObject();
98
+
99
+        if (!$token || $token->hasExpired()) {
100
+            try {
101
+                $this->client->authenticate();
102
+                $this->exportToken();
103
+            } catch (ClientErrorResponseException $e) {
104
+                $statusCode = $e->getResponse()->getStatusCode();
105
+                if ($statusCode == 412) {
106
+                    throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
107
+                } else if ($statusCode === 401) {
108
+                    throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
109
+                } else {
110
+                    throw new StorageAuthException('Unknown error', $e);
111
+                }
112
+            }
113
+        }
114
+
115
+
116
+        /** @var Catalog $catalog */
117
+        $catalog = $this->client->getCatalog();
118
+
119
+        if (isset($this->params['serviceName'])) {
120
+            $serviceName = $this->params['serviceName'];
121
+        } else {
122
+            $serviceName = Service::DEFAULT_NAME;
123
+        }
124
+
125
+        if (isset($this->params['urlType'])) {
126
+            $urlType = $this->params['urlType'];
127
+            if ($urlType !== 'internalURL' && $urlType !== 'publicURL') {
128
+                throw new StorageNotAvailableException('Invalid url type');
129
+            }
130
+        } else {
131
+            $urlType = Service::DEFAULT_URL_TYPE;
132
+        }
133
+
134
+        $catalogItem = $this->getCatalogForService($catalog, $serviceName);
135
+        if (!$catalogItem) {
136
+            $available = implode(', ', $this->getAvailableServiceNames($catalog));
137
+            throw new StorageNotAvailableException(
138
+                "Service $serviceName not found in service catalog, available services: $available"
139
+            );
140
+        } else if (isset($this->params['region'])) {
141
+            $this->validateRegion($catalogItem, $this->params['region']);
142
+        }
143
+
144
+        $this->objectStoreService = $this->client->objectStoreService($serviceName, $this->params['region'], $urlType);
145
+
146
+        try {
147
+            $this->container = $this->objectStoreService->getContainer($this->params['container']);
148
+        } catch (ClientErrorResponseException $ex) {
149
+            // if the container does not exist and autocreate is true try to create the container on the fly
150
+            if (isset($this->params['autocreate']) && $this->params['autocreate'] === true) {
151
+                $this->container = $this->objectStoreService->createContainer($this->params['container']);
152
+            } else {
153
+                throw $ex;
154
+            }
155
+        }
156
+    }
157
+
158
+    private function exportToken() {
159
+        $export = $this->client->exportCredentials();
160
+        $export['catalog'] = array_map(function (CatalogItem $item) {
161
+            return [
162
+                'name' => $item->getName(),
163
+                'endpoints' => $item->getEndpoints(),
164
+                'type' => $item->getType()
165
+            ];
166
+        }, $export['catalog']->getItems());
167
+        $this->memcache->set('token', json_encode($export));
168
+    }
169
+
170
+    private function importToken() {
171
+        $cachedTokenString = $this->memcache->get('token');
172
+        if ($cachedTokenString) {
173
+            $cachedToken = json_decode($cachedTokenString, true);
174
+            $cachedToken['catalog'] = array_map(function (array $item) {
175
+                $itemClass = new \stdClass();
176
+                $itemClass->name = $item['name'];
177
+                $itemClass->endpoints = array_map(function (array $endpoint) {
178
+                    return (object) $endpoint;
179
+                }, $item['endpoints']);
180
+                $itemClass->type = $item['type'];
181
+
182
+                return $itemClass;
183
+            }, $cachedToken['catalog']);
184
+            try {
185
+                $this->client->importCredentials($cachedToken);
186
+            } catch (\Exception $e) {
187
+                $this->client->setTokenObject(new Token());
188
+            }
189
+        }
190
+    }
191
+
192
+    /**
193
+     * @param Catalog $catalog
194
+     * @param $name
195
+     * @return null|CatalogItem
196
+     */
197
+    private function getCatalogForService(Catalog $catalog, $name) {
198
+        foreach ($catalog->getItems() as $item) {
199
+            /** @var CatalogItem $item */
200
+            if ($item->hasType(Service::DEFAULT_TYPE) && $item->hasName($name)) {
201
+                return $item;
202
+            }
203
+        }
204
+
205
+        return null;
206
+    }
207
+
208
+    private function validateRegion(CatalogItem $item, $region) {
209
+        $endPoints = $item->getEndpoints();
210
+        foreach ($endPoints as $endPoint) {
211
+            if ($endPoint->region === $region) {
212
+                return;
213
+            }
214
+        }
215
+
216
+        $availableRegions = implode(', ', array_map(function ($endpoint) {
217
+            return $endpoint->region;
218
+        }, $endPoints));
219
+
220
+        throw new StorageNotAvailableException("Invalid region '$region', available regions: $availableRegions");
221
+    }
222
+
223
+    private function getAvailableServiceNames(Catalog $catalog) {
224
+        return array_map(function (CatalogItem $item) {
225
+            return $item->getName();
226
+        }, array_filter($catalog->getItems(), function (CatalogItem $item) {
227
+            return $item->hasType(Service::DEFAULT_TYPE);
228
+        }));
229
+    }
230
+
231
+    /**
232
+     * @return string the container name where objects are stored
233
+     */
234
+    public function getStorageId() {
235
+        return $this->params['container'];
236
+    }
237
+
238
+    /**
239
+     * @param string $urn the unified resource name used to identify the object
240
+     * @param resource $stream stream with the data to write
241
+     * @throws Exception from openstack lib when something goes wrong
242
+     */
243
+    public function writeObject($urn, $stream) {
244
+        $this->init();
245
+        $this->container->uploadObject($urn, $stream);
246
+    }
247
+
248
+    /**
249
+     * @param string $urn the unified resource name used to identify the object
250
+     * @return resource stream with the read data
251
+     * @throws Exception from openstack lib when something goes wrong
252
+     */
253
+    public function readObject($urn) {
254
+        $this->init();
255
+        $object = $this->container->getObject($urn);
256
+
257
+        // we need to keep a reference to objectContent or
258
+        // the stream will be closed before we can do anything with it
259
+        /** @var $objectContent \Guzzle\Http\EntityBody * */
260
+        $objectContent = $object->getContent();
261
+        $objectContent->rewind();
262
+
263
+        $stream = $objectContent->getStream();
264
+        // save the object content in the context of the stream to prevent it being gc'd until the stream is closed
265
+        stream_context_set_option($stream, 'swift', 'content', $objectContent);
266
+
267
+        return $stream;
268
+    }
269
+
270
+    /**
271
+     * @param string $urn Unified Resource Name
272
+     * @return void
273
+     * @throws Exception from openstack lib when something goes wrong
274
+     */
275
+    public function deleteObject($urn) {
276
+        $this->init();
277
+        // see https://github.com/rackspace/php-opencloud/issues/243#issuecomment-30032242
278
+        $this->container->dataObject()->setName($urn)->delete();
279
+    }
280
+
281
+    public function deleteContainer($recursive = false) {
282
+        $this->init();
283
+        $this->container->delete($recursive);
284
+    }
285 285
 
286 286
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -74,14 +74,14 @@  discard block
 block discarded – undo
74 74
 
75 75
 		if (isset($params['apiKey'])) {
76 76
 			$this->client = new Rackspace($params['url'], $params);
77
-			$cacheKey = $this->params['username'] . '@' . $this->params['url'] . '/' . $this->params['bucket'];
77
+			$cacheKey = $this->params['username'].'@'.$this->params['url'].'/'.$this->params['bucket'];
78 78
 		} else {
79 79
 			$this->client = new OpenStack($params['url'], $params);
80
-			$cacheKey = $this->params['username'] . '@' . $this->params['url'] . '/' . $this->params['bucket'];
80
+			$cacheKey = $this->params['username'].'@'.$this->params['url'].'/'.$this->params['bucket'];
81 81
 		}
82 82
 
83 83
 		$cacheFactory = \OC::$server->getMemCacheFactory();
84
-		$this->memcache = $cacheFactory->create('swift::' . $cacheKey);
84
+		$this->memcache = $cacheFactory->create('swift::'.$cacheKey);
85 85
 
86 86
 		$this->params = $params;
87 87
 	}
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 
158 158
 	private function exportToken() {
159 159
 		$export = $this->client->exportCredentials();
160
-		$export['catalog'] = array_map(function (CatalogItem $item) {
160
+		$export['catalog'] = array_map(function(CatalogItem $item) {
161 161
 			return [
162 162
 				'name' => $item->getName(),
163 163
 				'endpoints' => $item->getEndpoints(),
@@ -171,10 +171,10 @@  discard block
 block discarded – undo
171 171
 		$cachedTokenString = $this->memcache->get('token');
172 172
 		if ($cachedTokenString) {
173 173
 			$cachedToken = json_decode($cachedTokenString, true);
174
-			$cachedToken['catalog'] = array_map(function (array $item) {
174
+			$cachedToken['catalog'] = array_map(function(array $item) {
175 175
 				$itemClass = new \stdClass();
176 176
 				$itemClass->name = $item['name'];
177
-				$itemClass->endpoints = array_map(function (array $endpoint) {
177
+				$itemClass->endpoints = array_map(function(array $endpoint) {
178 178
 					return (object) $endpoint;
179 179
 				}, $item['endpoints']);
180 180
 				$itemClass->type = $item['type'];
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 			}
214 214
 		}
215 215
 
216
-		$availableRegions = implode(', ', array_map(function ($endpoint) {
216
+		$availableRegions = implode(', ', array_map(function($endpoint) {
217 217
 			return $endpoint->region;
218 218
 		}, $endPoints));
219 219
 
@@ -221,9 +221,9 @@  discard block
 block discarded – undo
221 221
 	}
222 222
 
223 223
 	private function getAvailableServiceNames(Catalog $catalog) {
224
-		return array_map(function (CatalogItem $item) {
224
+		return array_map(function(CatalogItem $item) {
225 225
 			return $item->getName();
226
-		}, array_filter($catalog->getItems(), function (CatalogItem $item) {
226
+		}, array_filter($catalog->getItems(), function(CatalogItem $item) {
227 227
 			return $item->hasType(Service::DEFAULT_TYPE);
228 228
 		}));
229 229
 	}
Please login to merge, or discard this patch.