Completed
Pull Request — master (#4116)
by Robin
17:09
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   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -38,223 +38,223 @@
 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
-		$cachedTokenString = $this->memcache->get('token');
95
-		if ($cachedTokenString) {
96
-			$cachedToken = unserialize($cachedTokenString);
97
-			try {
98
-				$this->client->importCredentials($cachedToken);
99
-			} catch (\Exception $e) {
100
-				$this->client->setTokenObject(new Token());
101
-			}
102
-		}
103
-
104
-		/** @var Token $token */
105
-		$token = $this->client->getTokenObject();
106
-
107
-		if (!$token || $token->hasExpired()) {
108
-			try {
109
-				$this->client->authenticate();
110
-				$this->memcache->set('token', serialize($this->client->exportCredentials()));
111
-			} catch (ClientErrorResponseException $e) {
112
-				$statusCode = $e->getResponse()->getStatusCode();
113
-				if ($statusCode == 412) {
114
-					throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
115
-				} else if ($statusCode === 401) {
116
-					throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
117
-				} else {
118
-					throw new StorageAuthException('Unknown error', $e);
119
-				}
120
-			}
121
-		}
122
-
123
-
124
-		/** @var Catalog $catalog */
125
-		$catalog = $this->client->getCatalog();
126
-
127
-		if (isset($this->params['serviceName'])) {
128
-			$serviceName = $this->params['serviceName'];
129
-		} else {
130
-			$serviceName = Service::DEFAULT_NAME;
131
-		}
132
-
133
-		if (isset($this->params['urlType'])) {
134
-			$urlType = $this->params['urlType'];
135
-			if ($urlType !== 'internalURL' && $urlType !== 'publicURL') {
136
-				throw new StorageNotAvailableException('Invalid url type');
137
-			}
138
-		} else {
139
-			$urlType = Service::DEFAULT_URL_TYPE;
140
-		}
141
-
142
-		$catalogItem = $this->getCatalogForService($catalog, $serviceName);
143
-		if (!$catalogItem) {
144
-			$available = implode(', ', $this->getAvailableServiceNames($catalog));
145
-			throw new StorageNotAvailableException(
146
-				"Service $serviceName not found in service catalog, available services: $available"
147
-			);
148
-		} else if (isset($this->params['region'])) {
149
-			$this->validateRegion($catalogItem, $this->params['region']);
150
-		}
151
-
152
-		$this->objectStoreService = $this->client->objectStoreService($serviceName, $this->params['region'], $urlType);
153
-
154
-		try {
155
-			$this->container = $this->objectStoreService->getContainer($this->params['container']);
156
-		} catch (ClientErrorResponseException $ex) {
157
-			// if the container does not exist and autocreate is true try to create the container on the fly
158
-			if (isset($this->params['autocreate']) && $this->params['autocreate'] === true) {
159
-				$this->container = $this->objectStoreService->createContainer($this->params['container']);
160
-			} else {
161
-				throw $ex;
162
-			}
163
-		}
164
-	}
165
-
166
-	/**
167
-	 * @param Catalog $catalog
168
-	 * @param $name
169
-	 * @return null|CatalogItem
170
-	 */
171
-	private function getCatalogForService(Catalog $catalog, $name) {
172
-		foreach ($catalog->getItems() as $item) {
173
-			/** @var CatalogItem $item */
174
-			if ($item->hasType(Service::DEFAULT_TYPE) && $item->hasName($name)) {
175
-				return $item;
176
-			}
177
-		}
178
-
179
-		return null;
180
-	}
181
-
182
-	private function validateRegion(CatalogItem $item, $region) {
183
-		$endPoints = $item->getEndpoints();
184
-		foreach ($endPoints as $endPoint) {
185
-			if ($endPoint->region === $region) {
186
-				return;
187
-			}
188
-		}
189
-
190
-		$availableRegions = implode(', ', array_map(function ($endpoint) {
191
-			return $endpoint->region;
192
-		}, $endPoints));
193
-
194
-		throw new StorageNotAvailableException("Invalid region '$region', available regions: $availableRegions");
195
-	}
196
-
197
-	private function getAvailableServiceNames(Catalog $catalog) {
198
-		return array_map(function (CatalogItem $item) {
199
-			return $item->getName();
200
-		}, array_filter($catalog->getItems(), function (CatalogItem $item) {
201
-			return $item->hasType(Service::DEFAULT_TYPE);
202
-		}));
203
-	}
204
-
205
-	/**
206
-	 * @return string the container name where objects are stored
207
-	 */
208
-	public function getStorageId() {
209
-		return $this->params['container'];
210
-	}
211
-
212
-	/**
213
-	 * @param string $urn the unified resource name used to identify the object
214
-	 * @param resource $stream stream with the data to write
215
-	 * @throws Exception from openstack lib when something goes wrong
216
-	 */
217
-	public function writeObject($urn, $stream) {
218
-		$this->init();
219
-		$this->container->uploadObject($urn, $stream);
220
-	}
221
-
222
-	/**
223
-	 * @param string $urn the unified resource name used to identify the object
224
-	 * @return resource stream with the read data
225
-	 * @throws Exception from openstack lib when something goes wrong
226
-	 */
227
-	public function readObject($urn) {
228
-		$this->init();
229
-		$object = $this->container->getObject($urn);
230
-
231
-		// we need to keep a reference to objectContent or
232
-		// the stream will be closed before we can do anything with it
233
-		/** @var $objectContent \Guzzle\Http\EntityBody * */
234
-		$objectContent = $object->getContent();
235
-		$objectContent->rewind();
236
-
237
-		$stream = $objectContent->getStream();
238
-		// save the object content in the context of the stream to prevent it being gc'd until the stream is closed
239
-		stream_context_set_option($stream, 'swift', 'content', $objectContent);
240
-
241
-		return $stream;
242
-	}
243
-
244
-	/**
245
-	 * @param string $urn Unified Resource Name
246
-	 * @return void
247
-	 * @throws Exception from openstack lib when something goes wrong
248
-	 */
249
-	public function deleteObject($urn) {
250
-		$this->init();
251
-		// see https://github.com/rackspace/php-opencloud/issues/243#issuecomment-30032242
252
-		$this->container->dataObject()->setName($urn)->delete();
253
-	}
254
-
255
-	public function deleteContainer($recursive = false) {
256
-		$this->init();
257
-		$this->container->delete($recursive);
258
-	}
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
+        $cachedTokenString = $this->memcache->get('token');
95
+        if ($cachedTokenString) {
96
+            $cachedToken = unserialize($cachedTokenString);
97
+            try {
98
+                $this->client->importCredentials($cachedToken);
99
+            } catch (\Exception $e) {
100
+                $this->client->setTokenObject(new Token());
101
+            }
102
+        }
103
+
104
+        /** @var Token $token */
105
+        $token = $this->client->getTokenObject();
106
+
107
+        if (!$token || $token->hasExpired()) {
108
+            try {
109
+                $this->client->authenticate();
110
+                $this->memcache->set('token', serialize($this->client->exportCredentials()));
111
+            } catch (ClientErrorResponseException $e) {
112
+                $statusCode = $e->getResponse()->getStatusCode();
113
+                if ($statusCode == 412) {
114
+                    throw new StorageAuthException('Precondition failed, verify the keystone url', $e);
115
+                } else if ($statusCode === 401) {
116
+                    throw new StorageAuthException('Authentication failed, verify the username, password and possibly tenant', $e);
117
+                } else {
118
+                    throw new StorageAuthException('Unknown error', $e);
119
+                }
120
+            }
121
+        }
122
+
123
+
124
+        /** @var Catalog $catalog */
125
+        $catalog = $this->client->getCatalog();
126
+
127
+        if (isset($this->params['serviceName'])) {
128
+            $serviceName = $this->params['serviceName'];
129
+        } else {
130
+            $serviceName = Service::DEFAULT_NAME;
131
+        }
132
+
133
+        if (isset($this->params['urlType'])) {
134
+            $urlType = $this->params['urlType'];
135
+            if ($urlType !== 'internalURL' && $urlType !== 'publicURL') {
136
+                throw new StorageNotAvailableException('Invalid url type');
137
+            }
138
+        } else {
139
+            $urlType = Service::DEFAULT_URL_TYPE;
140
+        }
141
+
142
+        $catalogItem = $this->getCatalogForService($catalog, $serviceName);
143
+        if (!$catalogItem) {
144
+            $available = implode(', ', $this->getAvailableServiceNames($catalog));
145
+            throw new StorageNotAvailableException(
146
+                "Service $serviceName not found in service catalog, available services: $available"
147
+            );
148
+        } else if (isset($this->params['region'])) {
149
+            $this->validateRegion($catalogItem, $this->params['region']);
150
+        }
151
+
152
+        $this->objectStoreService = $this->client->objectStoreService($serviceName, $this->params['region'], $urlType);
153
+
154
+        try {
155
+            $this->container = $this->objectStoreService->getContainer($this->params['container']);
156
+        } catch (ClientErrorResponseException $ex) {
157
+            // if the container does not exist and autocreate is true try to create the container on the fly
158
+            if (isset($this->params['autocreate']) && $this->params['autocreate'] === true) {
159
+                $this->container = $this->objectStoreService->createContainer($this->params['container']);
160
+            } else {
161
+                throw $ex;
162
+            }
163
+        }
164
+    }
165
+
166
+    /**
167
+     * @param Catalog $catalog
168
+     * @param $name
169
+     * @return null|CatalogItem
170
+     */
171
+    private function getCatalogForService(Catalog $catalog, $name) {
172
+        foreach ($catalog->getItems() as $item) {
173
+            /** @var CatalogItem $item */
174
+            if ($item->hasType(Service::DEFAULT_TYPE) && $item->hasName($name)) {
175
+                return $item;
176
+            }
177
+        }
178
+
179
+        return null;
180
+    }
181
+
182
+    private function validateRegion(CatalogItem $item, $region) {
183
+        $endPoints = $item->getEndpoints();
184
+        foreach ($endPoints as $endPoint) {
185
+            if ($endPoint->region === $region) {
186
+                return;
187
+            }
188
+        }
189
+
190
+        $availableRegions = implode(', ', array_map(function ($endpoint) {
191
+            return $endpoint->region;
192
+        }, $endPoints));
193
+
194
+        throw new StorageNotAvailableException("Invalid region '$region', available regions: $availableRegions");
195
+    }
196
+
197
+    private function getAvailableServiceNames(Catalog $catalog) {
198
+        return array_map(function (CatalogItem $item) {
199
+            return $item->getName();
200
+        }, array_filter($catalog->getItems(), function (CatalogItem $item) {
201
+            return $item->hasType(Service::DEFAULT_TYPE);
202
+        }));
203
+    }
204
+
205
+    /**
206
+     * @return string the container name where objects are stored
207
+     */
208
+    public function getStorageId() {
209
+        return $this->params['container'];
210
+    }
211
+
212
+    /**
213
+     * @param string $urn the unified resource name used to identify the object
214
+     * @param resource $stream stream with the data to write
215
+     * @throws Exception from openstack lib when something goes wrong
216
+     */
217
+    public function writeObject($urn, $stream) {
218
+        $this->init();
219
+        $this->container->uploadObject($urn, $stream);
220
+    }
221
+
222
+    /**
223
+     * @param string $urn the unified resource name used to identify the object
224
+     * @return resource stream with the read data
225
+     * @throws Exception from openstack lib when something goes wrong
226
+     */
227
+    public function readObject($urn) {
228
+        $this->init();
229
+        $object = $this->container->getObject($urn);
230
+
231
+        // we need to keep a reference to objectContent or
232
+        // the stream will be closed before we can do anything with it
233
+        /** @var $objectContent \Guzzle\Http\EntityBody * */
234
+        $objectContent = $object->getContent();
235
+        $objectContent->rewind();
236
+
237
+        $stream = $objectContent->getStream();
238
+        // save the object content in the context of the stream to prevent it being gc'd until the stream is closed
239
+        stream_context_set_option($stream, 'swift', 'content', $objectContent);
240
+
241
+        return $stream;
242
+    }
243
+
244
+    /**
245
+     * @param string $urn Unified Resource Name
246
+     * @return void
247
+     * @throws Exception from openstack lib when something goes wrong
248
+     */
249
+    public function deleteObject($urn) {
250
+        $this->init();
251
+        // see https://github.com/rackspace/php-opencloud/issues/243#issuecomment-30032242
252
+        $this->container->dataObject()->setName($urn)->delete();
253
+    }
254
+
255
+    public function deleteContainer($recursive = false) {
256
+        $this->init();
257
+        $this->container->delete($recursive);
258
+    }
259 259
 
260 260
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 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
 	}
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 			}
188 188
 		}
189 189
 
190
-		$availableRegions = implode(', ', array_map(function ($endpoint) {
190
+		$availableRegions = implode(', ', array_map(function($endpoint) {
191 191
 			return $endpoint->region;
192 192
 		}, $endPoints));
193 193
 
@@ -195,9 +195,9 @@  discard block
 block discarded – undo
195 195
 	}
196 196
 
197 197
 	private function getAvailableServiceNames(Catalog $catalog) {
198
-		return array_map(function (CatalogItem $item) {
198
+		return array_map(function(CatalogItem $item) {
199 199
 			return $item->getName();
200
-		}, array_filter($catalog->getItems(), function (CatalogItem $item) {
200
+		}, array_filter($catalog->getItems(), function(CatalogItem $item) {
201 201
 			return $item->hasType(Service::DEFAULT_TYPE);
202 202
 		}));
203 203
 	}
Please login to merge, or discard this patch.