[FileBackend] Added Content-Disposition support to Swift.
[lhc/web/wiklou.git] / includes / filebackend / SwiftFileBackend.php
1 <?php
2 /**
3 * OpenStack Swift based file backend.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup FileBackend
22 * @author Russ Nelson
23 * @author Aaron Schulz
24 */
25
26 /**
27 * @brief Class for an OpenStack Swift based file backend.
28 *
29 * This requires the SwiftCloudFiles MediaWiki extension, which includes
30 * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
31 * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
32 *
33 * Status messages should avoid mentioning the Swift account name.
34 * Likewise, error suppression should be used to avoid path disclosure.
35 *
36 * @ingroup FileBackend
37 * @since 1.19
38 */
39 class SwiftFileBackend extends FileBackendStore {
40 /** @var CF_Authentication */
41 protected $auth; // Swift authentication handler
42 protected $authTTL; // integer seconds
43 protected $swiftAnonUser; // string; username to handle unauthenticated requests
44 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
45 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
46 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
47
48 /** @var CF_Connection */
49 protected $conn; // Swift connection handle
50 protected $sessionStarted = 0; // integer UNIX timestamp
51
52 /** @var CloudFilesException */
53 protected $connException;
54 protected $connErrorTime = 0; // UNIX timestamp
55
56 /** @var BagOStuff */
57 protected $srvCache;
58
59 /** @var ProcessCacheLRU */
60 protected $connContainerCache; // container object cache
61
62 /**
63 * @see FileBackendStore::__construct()
64 * Additional $config params include:
65 * - swiftAuthUrl : Swift authentication server URL
66 * - swiftUser : Swift user used by MediaWiki (account:username)
67 * - swiftKey : Swift authentication key for the above user
68 * - swiftAuthTTL : Swift authentication TTL (seconds)
69 * - swiftAnonUser : Swift user used for end-user requests (account:username).
70 * If set, then views of public containers are assumed to go
71 * through this user. If not set, then public containers are
72 * accessible to unauthenticated requests via ".r:*" in the ACL.
73 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
74 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
75 * If files may likely change, this should probably not exceed
76 * a few days. For example, deletions may take this long to apply.
77 * If object purging is enabled, however, this is not an issue.
78 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
79 * - shardViaHashLevels : Map of container names to sharding config with:
80 * - base : base of hash characters, 16 or 36
81 * - levels : the number of hash levels (and digits)
82 * - repeat : hash subdirectories are prefixed with all the
83 * parent hash directory names (e.g. "a/ab/abc")
84 * - cacheAuthInfo : Whether to cache authentication tokens in APC/XCache.
85 * This is probably insecure in shared hosting environments.
86 */
87 public function __construct( array $config ) {
88 parent::__construct( $config );
89 if ( !MWInit::classExists( 'CF_Constants' ) ) {
90 throw new MWException( 'SwiftCloudFiles extension not installed.' );
91 }
92 // Required settings
93 $this->auth = new CF_Authentication(
94 $config['swiftUser'],
95 $config['swiftKey'],
96 null, // account; unused
97 $config['swiftAuthUrl']
98 );
99 // Optional settings
100 $this->authTTL = isset( $config['swiftAuthTTL'] )
101 ? $config['swiftAuthTTL']
102 : 5 * 60; // some sane number
103 $this->swiftAnonUser = isset( $config['swiftAnonUser'] )
104 ? $config['swiftAnonUser']
105 : '';
106 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
107 ? $config['shardViaHashLevels']
108 : '';
109 $this->swiftUseCDN = isset( $config['swiftUseCDN'] )
110 ? $config['swiftUseCDN']
111 : false;
112 $this->swiftCDNExpiry = isset( $config['swiftCDNExpiry'] )
113 ? $config['swiftCDNExpiry']
114 : 12*3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
115 $this->swiftCDNPurgable = isset( $config['swiftCDNPurgable'] )
116 ? $config['swiftCDNPurgable']
117 : true;
118 // Cache container information to mask latency
119 $this->memCache = wfGetMainCache();
120 // Process cache for container info
121 $this->connContainerCache = new ProcessCacheLRU( 300 );
122 // Cache auth token information to avoid RTTs
123 if ( !empty( $config['cacheAuthInfo'] ) ) {
124 try { // look for APC, XCache, WinCache, ect...
125 $this->srvCache = ObjectCache::newAccelerator( array() );
126 } catch ( Exception $e ) {}
127 }
128 $this->srvCache = $this->srvCache ? $this->srvCache : new EmptyBagOStuff();
129 }
130
131 /**
132 * @see FileBackendStore::resolveContainerPath()
133 * @return null
134 */
135 protected function resolveContainerPath( $container, $relStoragePath ) {
136 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
137 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
138 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
139 return null; // too long for Swift
140 }
141 return $relStoragePath;
142 }
143
144 /**
145 * @see FileBackendStore::isPathUsableInternal()
146 * @return bool
147 */
148 public function isPathUsableInternal( $storagePath ) {
149 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
150 if ( $rel === null ) {
151 return false; // invalid
152 }
153
154 try {
155 $this->getContainer( $container );
156 return true; // container exists
157 } catch ( NoSuchContainerException $e ) {
158 } catch ( CloudFilesException $e ) { // some other exception?
159 $this->handleException( $e, null, __METHOD__, array( 'path' => $storagePath ) );
160 }
161
162 return false;
163 }
164
165 /**
166 * @see FileBackendStore::doCreateInternal()
167 * @return Status
168 */
169 protected function doCreateInternal( array $params ) {
170 $status = Status::newGood();
171
172 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
173 if ( $dstRel === null ) {
174 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
175 return $status;
176 }
177
178 // (a) Check the destination container and object
179 try {
180 $dContObj = $this->getContainer( $dstCont );
181 if ( empty( $params['overwrite'] ) &&
182 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
183 {
184 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
185 return $status;
186 }
187 } catch ( NoSuchContainerException $e ) {
188 $status->fatal( 'backend-fail-create', $params['dst'] );
189 return $status;
190 } catch ( CloudFilesException $e ) { // some other exception?
191 $this->handleException( $e, $status, __METHOD__, $params );
192 return $status;
193 }
194
195 // (b) Get a SHA-1 hash of the object
196 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
197
198 // (c) Actually create the object
199 try {
200 // Create a fresh CF_Object with no fields preloaded.
201 // We don't want to preserve headers, metadata, and such.
202 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
203 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
204 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
205 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
206 // The MD5 here will be checked within Swift against its own MD5.
207 $obj->set_etag( md5( $params['content'] ) );
208 // Use the same content type as StreamFile for security
209 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
210 if ( !strlen( $obj->content_type ) ) { // special case
211 $obj->content_type = 'unknown/unknown';
212 }
213 // Set the Content-Disposition header if requested
214 if ( isset( $params['disposition'] ) ) {
215 $obj->headers['Content-Disposition'] = $params['disposition'];
216 }
217 if ( !empty( $params['async'] ) ) { // deferred
218 $op = $obj->write_async( $params['content'] );
219 $status->value = new SwiftFileOpHandle( $this, $params, 'Create', $op );
220 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
221 $status->value->affectedObjects[] = $obj;
222 }
223 } else { // actually write the object in Swift
224 $obj->write( $params['content'] );
225 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
226 $this->purgeCDNCache( array( $obj ) );
227 }
228 }
229 } catch ( CDNNotEnabledException $e ) {
230 // CDN not enabled; nothing to see here
231 } catch ( BadContentTypeException $e ) {
232 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
233 } catch ( CloudFilesException $e ) { // some other exception?
234 $this->handleException( $e, $status, __METHOD__, $params );
235 }
236
237 return $status;
238 }
239
240 /**
241 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
242 */
243 protected function _getResponseCreate( CF_Async_Op $cfOp, Status $status, array $params ) {
244 try {
245 $cfOp->getLastResponse();
246 } catch ( BadContentTypeException $e ) {
247 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
248 }
249 }
250
251 /**
252 * @see FileBackendStore::doStoreInternal()
253 * @return Status
254 */
255 protected function doStoreInternal( array $params ) {
256 $status = Status::newGood();
257
258 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
259 if ( $dstRel === null ) {
260 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
261 return $status;
262 }
263
264 // (a) Check the destination container and object
265 try {
266 $dContObj = $this->getContainer( $dstCont );
267 if ( empty( $params['overwrite'] ) &&
268 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
269 {
270 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
271 return $status;
272 }
273 } catch ( NoSuchContainerException $e ) {
274 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
275 return $status;
276 } catch ( CloudFilesException $e ) { // some other exception?
277 $this->handleException( $e, $status, __METHOD__, $params );
278 return $status;
279 }
280
281 // (b) Get a SHA-1 hash of the object
282 $sha1Hash = sha1_file( $params['src'] );
283 if ( $sha1Hash === false ) { // source doesn't exist?
284 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
285 return $status;
286 }
287 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
288
289 // (c) Actually store the object
290 try {
291 // Create a fresh CF_Object with no fields preloaded.
292 // We don't want to preserve headers, metadata, and such.
293 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
294 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
295 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
296 // The MD5 here will be checked within Swift against its own MD5.
297 $obj->set_etag( md5_file( $params['src'] ) );
298 // Use the same content type as StreamFile for security
299 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
300 if ( !strlen( $obj->content_type ) ) { // special case
301 $obj->content_type = 'unknown/unknown';
302 }
303 // Set the Content-Disposition header if requested
304 if ( isset( $params['disposition'] ) ) {
305 $obj->headers['Content-Disposition'] = $params['disposition'];
306 }
307 if ( !empty( $params['async'] ) ) { // deferred
308 wfSuppressWarnings();
309 $fp = fopen( $params['src'], 'rb' );
310 wfRestoreWarnings();
311 if ( !$fp ) {
312 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
313 } else {
314 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
315 $status->value = new SwiftFileOpHandle( $this, $params, 'Store', $op );
316 $status->value->resourcesToClose[] = $fp;
317 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
318 $status->value->affectedObjects[] = $obj;
319 }
320 }
321 } else { // actually write the object in Swift
322 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
323 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
324 $this->purgeCDNCache( array( $obj ) );
325 }
326 }
327 } catch ( CDNNotEnabledException $e ) {
328 // CDN not enabled; nothing to see here
329 } catch ( BadContentTypeException $e ) {
330 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
331 } catch ( IOException $e ) {
332 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
333 } catch ( CloudFilesException $e ) { // some other exception?
334 $this->handleException( $e, $status, __METHOD__, $params );
335 }
336
337 return $status;
338 }
339
340 /**
341 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
342 */
343 protected function _getResponseStore( CF_Async_Op $cfOp, Status $status, array $params ) {
344 try {
345 $cfOp->getLastResponse();
346 } catch ( BadContentTypeException $e ) {
347 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
348 } catch ( IOException $e ) {
349 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
350 }
351 }
352
353 /**
354 * @see FileBackendStore::doCopyInternal()
355 * @return Status
356 */
357 protected function doCopyInternal( array $params ) {
358 $status = Status::newGood();
359
360 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
361 if ( $srcRel === null ) {
362 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
363 return $status;
364 }
365
366 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
367 if ( $dstRel === null ) {
368 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
369 return $status;
370 }
371
372 // (a) Check the source/destination containers and destination object
373 try {
374 $sContObj = $this->getContainer( $srcCont );
375 $dContObj = $this->getContainer( $dstCont );
376 if ( empty( $params['overwrite'] ) &&
377 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
378 {
379 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
380 return $status;
381 }
382 } catch ( NoSuchContainerException $e ) {
383 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
384 return $status;
385 } catch ( CloudFilesException $e ) { // some other exception?
386 $this->handleException( $e, $status, __METHOD__, $params );
387 return $status;
388 }
389
390 // (b) Actually copy the file to the destination
391 try {
392 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
393 $hdrs = array(); // source file headers to override with new values
394 if ( isset( $params['disposition'] ) ) {
395 $hdrs['Content-Disposition'] = $params['disposition'];
396 }
397 if ( !empty( $params['async'] ) ) { // deferred
398 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
399 $status->value = new SwiftFileOpHandle( $this, $params, 'Copy', $op );
400 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
401 $status->value->affectedObjects[] = $dstObj;
402 }
403 } else { // actually write the object in Swift
404 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
405 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
406 $this->purgeCDNCache( array( $dstObj ) );
407 }
408 }
409 } catch ( CDNNotEnabledException $e ) {
410 // CDN not enabled; nothing to see here
411 } catch ( NoSuchObjectException $e ) { // source object does not exist
412 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
413 } catch ( CloudFilesException $e ) { // some other exception?
414 $this->handleException( $e, $status, __METHOD__, $params );
415 }
416
417 return $status;
418 }
419
420 /**
421 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
422 */
423 protected function _getResponseCopy( CF_Async_Op $cfOp, Status $status, array $params ) {
424 try {
425 $cfOp->getLastResponse();
426 } catch ( NoSuchObjectException $e ) { // source object does not exist
427 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
428 }
429 }
430
431 /**
432 * @see FileBackendStore::doMoveInternal()
433 * @return Status
434 */
435 protected function doMoveInternal( array $params ) {
436 $status = Status::newGood();
437
438 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
439 if ( $srcRel === null ) {
440 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
441 return $status;
442 }
443
444 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
445 if ( $dstRel === null ) {
446 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
447 return $status;
448 }
449
450 // (a) Check the source/destination containers and destination object
451 try {
452 $sContObj = $this->getContainer( $srcCont );
453 $dContObj = $this->getContainer( $dstCont );
454 if ( empty( $params['overwrite'] ) &&
455 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
456 {
457 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
458 return $status;
459 }
460 } catch ( NoSuchContainerException $e ) {
461 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
462 return $status;
463 } catch ( CloudFilesException $e ) { // some other exception?
464 $this->handleException( $e, $status, __METHOD__, $params );
465 return $status;
466 }
467
468 // (b) Actually move the file to the destination
469 try {
470 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
471 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
472 $hdrs = array(); // source file headers to override with new values
473 if ( isset( $params['disposition'] ) ) {
474 $hdrs['Content-Disposition'] = $params['disposition'];
475 }
476 if ( !empty( $params['async'] ) ) { // deferred
477 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
478 $status->value = new SwiftFileOpHandle( $this, $params, 'Move', $op );
479 $status->value->affectedObjects[] = $srcObj;
480 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
481 $status->value->affectedObjects[] = $dstObj;
482 }
483 } else { // actually write the object in Swift
484 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
485 $this->purgeCDNCache( array( $srcObj ) );
486 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
487 $this->purgeCDNCache( array( $dstObj ) );
488 }
489 }
490 } catch ( CDNNotEnabledException $e ) {
491 // CDN not enabled; nothing to see here
492 } catch ( NoSuchObjectException $e ) { // source object does not exist
493 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
494 } catch ( CloudFilesException $e ) { // some other exception?
495 $this->handleException( $e, $status, __METHOD__, $params );
496 }
497
498 return $status;
499 }
500
501 /**
502 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
503 */
504 protected function _getResponseMove( CF_Async_Op $cfOp, Status $status, array $params ) {
505 try {
506 $cfOp->getLastResponse();
507 } catch ( NoSuchObjectException $e ) { // source object does not exist
508 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
509 }
510 }
511
512 /**
513 * @see FileBackendStore::doDeleteInternal()
514 * @return Status
515 */
516 protected function doDeleteInternal( array $params ) {
517 $status = Status::newGood();
518
519 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
520 if ( $srcRel === null ) {
521 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
522 return $status;
523 }
524
525 try {
526 $sContObj = $this->getContainer( $srcCont );
527 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
528 if ( !empty( $params['async'] ) ) { // deferred
529 $op = $sContObj->delete_object_async( $srcRel );
530 $status->value = new SwiftFileOpHandle( $this, $params, 'Delete', $op );
531 $status->value->affectedObjects[] = $srcObj;
532 } else { // actually write the object in Swift
533 $sContObj->delete_object( $srcRel );
534 $this->purgeCDNCache( array( $srcObj ) );
535 }
536 } catch ( CDNNotEnabledException $e ) {
537 // CDN not enabled; nothing to see here
538 } catch ( NoSuchContainerException $e ) {
539 $status->fatal( 'backend-fail-delete', $params['src'] );
540 } catch ( NoSuchObjectException $e ) {
541 if ( empty( $params['ignoreMissingSource'] ) ) {
542 $status->fatal( 'backend-fail-delete', $params['src'] );
543 }
544 } catch ( CloudFilesException $e ) { // some other exception?
545 $this->handleException( $e, $status, __METHOD__, $params );
546 }
547
548 return $status;
549 }
550
551 /**
552 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
553 */
554 protected function _getResponseDelete( CF_Async_Op $cfOp, Status $status, array $params ) {
555 try {
556 $cfOp->getLastResponse();
557 } catch ( NoSuchContainerException $e ) {
558 $status->fatal( 'backend-fail-delete', $params['src'] );
559 } catch ( NoSuchObjectException $e ) {
560 if ( empty( $params['ignoreMissingSource'] ) ) {
561 $status->fatal( 'backend-fail-delete', $params['src'] );
562 }
563 }
564 }
565
566 /**
567 * @see FileBackendStore::doPrepareInternal()
568 * @return Status
569 */
570 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
571 $status = Status::newGood();
572
573 // (a) Check if container already exists
574 try {
575 $contObj = $this->getContainer( $fullCont );
576 // NoSuchContainerException not thrown: container must exist
577 return $status; // already exists
578 } catch ( NoSuchContainerException $e ) {
579 // NoSuchContainerException thrown: container does not exist
580 } catch ( CloudFilesException $e ) { // some other exception?
581 $this->handleException( $e, $status, __METHOD__, $params );
582 return $status;
583 }
584
585 // (b) Create container as needed
586 try {
587 $contObj = $this->createContainer( $fullCont );
588 if ( !empty( $params['noAccess'] ) ) {
589 // Make container private to end-users...
590 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
591 } else {
592 // Make container public to end-users...
593 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
594 }
595 if ( $this->swiftUseCDN ) { // Rackspace style CDN
596 $contObj->make_public( $this->swiftCDNExpiry );
597 }
598 } catch ( CDNNotEnabledException $e ) {
599 // CDN not enabled; nothing to see here
600 } catch ( CloudFilesException $e ) { // some other exception?
601 $this->handleException( $e, $status, __METHOD__, $params );
602 return $status;
603 }
604
605 return $status;
606 }
607
608 /**
609 * @see FileBackendStore::doSecureInternal()
610 * @return Status
611 */
612 protected function doSecureInternal( $fullCont, $dir, array $params ) {
613 $status = Status::newGood();
614 if ( empty( $params['noAccess'] ) ) {
615 return $status; // nothing to do
616 }
617
618 // Restrict container from end-users...
619 try {
620 // doPrepareInternal() should have been called,
621 // so the Swift container should already exist...
622 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
623 // NoSuchContainerException not thrown: container must exist
624
625 // Make container private to end-users...
626 $status->merge( $this->setContainerAccess(
627 $contObj,
628 array( $this->auth->username ), // read
629 array( $this->auth->username ) // write
630 ) );
631 if ( $this->swiftUseCDN && $contObj->is_public() ) { // Rackspace style CDN
632 $contObj->make_private();
633 }
634 } catch ( CDNNotEnabledException $e ) {
635 // CDN not enabled; nothing to see here
636 } catch ( CloudFilesException $e ) { // some other exception?
637 $this->handleException( $e, $status, __METHOD__, $params );
638 }
639
640 return $status;
641 }
642
643 /**
644 * @see FileBackendStore::doPublishInternal()
645 * @return Status
646 */
647 protected function doPublishInternal( $fullCont, $dir, array $params ) {
648 $status = Status::newGood();
649
650 // Unrestrict container from end-users...
651 try {
652 // doPrepareInternal() should have been called,
653 // so the Swift container should already exist...
654 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
655 // NoSuchContainerException not thrown: container must exist
656
657 // Make container public to end-users...
658 if ( $this->swiftAnonUser != '' ) {
659 $status->merge( $this->setContainerAccess(
660 $contObj,
661 array( $this->auth->username, $this->swiftAnonUser ), // read
662 array( $this->auth->username, $this->swiftAnonUser ) // write
663 ) );
664 } else {
665 $status->merge( $this->setContainerAccess(
666 $contObj,
667 array( $this->auth->username, '.r:*' ), // read
668 array( $this->auth->username ) // write
669 ) );
670 }
671 if ( $this->swiftUseCDN && !$contObj->is_public() ) { // Rackspace style CDN
672 $contObj->make_public();
673 }
674 } catch ( CDNNotEnabledException $e ) {
675 // CDN not enabled; nothing to see here
676 } catch ( CloudFilesException $e ) { // some other exception?
677 $this->handleException( $e, $status, __METHOD__, $params );
678 }
679
680 return $status;
681 }
682
683 /**
684 * @see FileBackendStore::doCleanInternal()
685 * @return Status
686 */
687 protected function doCleanInternal( $fullCont, $dir, array $params ) {
688 $status = Status::newGood();
689
690 // Only containers themselves can be removed, all else is virtual
691 if ( $dir != '' ) {
692 return $status; // nothing to do
693 }
694
695 // (a) Check the container
696 try {
697 $contObj = $this->getContainer( $fullCont, true );
698 } catch ( NoSuchContainerException $e ) {
699 return $status; // ok, nothing to do
700 } catch ( CloudFilesException $e ) { // some other exception?
701 $this->handleException( $e, $status, __METHOD__, $params );
702 return $status;
703 }
704
705 // (b) Delete the container if empty
706 if ( $contObj->object_count == 0 ) {
707 try {
708 $this->deleteContainer( $fullCont );
709 } catch ( NoSuchContainerException $e ) {
710 return $status; // race?
711 } catch ( NonEmptyContainerException $e ) {
712 return $status; // race? consistency delay?
713 } catch ( CloudFilesException $e ) { // some other exception?
714 $this->handleException( $e, $status, __METHOD__, $params );
715 return $status;
716 }
717 }
718
719 return $status;
720 }
721
722 /**
723 * @see FileBackendStore::doFileExists()
724 * @return array|bool|null
725 */
726 protected function doGetFileStat( array $params ) {
727 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
728 if ( $srcRel === null ) {
729 return false; // invalid storage path
730 }
731
732 $stat = false;
733 try {
734 $contObj = $this->getContainer( $srcCont );
735 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
736 $this->addMissingMetadata( $srcObj, $params['src'] );
737 $stat = array(
738 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
739 'mtime' => wfTimestamp( TS_MW, $srcObj->last_modified ),
740 'size' => (int)$srcObj->content_length,
741 'sha1' => $srcObj->metadata['Sha1base36']
742 );
743 } catch ( NoSuchContainerException $e ) {
744 } catch ( NoSuchObjectException $e ) {
745 } catch ( CloudFilesException $e ) { // some other exception?
746 $stat = null;
747 $this->handleException( $e, null, __METHOD__, $params );
748 }
749
750 return $stat;
751 }
752
753 /**
754 * Fill in any missing object metadata and save it to Swift
755 *
756 * @param $obj CF_Object
757 * @param $path string Storage path to object
758 * @return bool Success
759 * @throws Exception cloudfiles exceptions
760 */
761 protected function addMissingMetadata( CF_Object $obj, $path ) {
762 if ( isset( $obj->metadata['Sha1base36'] ) ) {
763 return true; // nothing to do
764 }
765 wfProfileIn( __METHOD__ );
766 $status = Status::newGood();
767 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
768 if ( $status->isOK() ) {
769 # Do not stat the file in getLocalCopy() to avoid infinite loops
770 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
771 if ( $tmpFile ) {
772 $hash = $tmpFile->getSha1Base36();
773 if ( $hash !== false ) {
774 $obj->metadata['Sha1base36'] = $hash;
775 $obj->sync_metadata(); // save to Swift
776 wfProfileOut( __METHOD__ );
777 return true; // success
778 }
779 }
780 }
781 $obj->metadata['Sha1base36'] = false;
782 wfProfileOut( __METHOD__ );
783 return false; // failed
784 }
785
786 /**
787 * @see FileBackend::getFileContents()
788 * @return bool|null|string
789 */
790 public function getFileContents( array $params ) {
791 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
792 if ( $srcRel === null ) {
793 return false; // invalid storage path
794 }
795
796 if ( !$this->fileExists( $params ) ) {
797 return null;
798 }
799
800 $data = false;
801 try {
802 $sContObj = $this->getContainer( $srcCont );
803 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
804 $data = $obj->read( $this->headersFromParams( $params ) );
805 } catch ( NoSuchContainerException $e ) {
806 } catch ( CloudFilesException $e ) { // some other exception?
807 $this->handleException( $e, null, __METHOD__, $params );
808 }
809
810 return $data;
811 }
812
813 /**
814 * @see FileBackendStore::doDirectoryExists()
815 * @return bool|null
816 */
817 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
818 try {
819 $container = $this->getContainer( $fullCont );
820 $prefix = ( $dir == '' ) ? null : "{$dir}/";
821 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
822 } catch ( NoSuchContainerException $e ) {
823 return false;
824 } catch ( CloudFilesException $e ) { // some other exception?
825 $this->handleException( $e, null, __METHOD__,
826 array( 'cont' => $fullCont, 'dir' => $dir ) );
827 }
828
829 return null; // error
830 }
831
832 /**
833 * @see FileBackendStore::getDirectoryListInternal()
834 * @return SwiftFileBackendDirList
835 */
836 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
837 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
838 }
839
840 /**
841 * @see FileBackendStore::getFileListInternal()
842 * @return SwiftFileBackendFileList
843 */
844 public function getFileListInternal( $fullCont, $dir, array $params ) {
845 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
846 }
847
848 /**
849 * Do not call this function outside of SwiftFileBackendFileList
850 *
851 * @param $fullCont string Resolved container name
852 * @param $dir string Resolved storage directory with no trailing slash
853 * @param $after string|null Storage path of file to list items after
854 * @param $limit integer Max number of items to list
855 * @param $params Array Includes flag for 'topOnly'
856 * @return Array List of relative paths of dirs directly under $dir
857 */
858 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
859 $dirs = array();
860 if ( $after === INF ) {
861 return $dirs; // nothing more
862 }
863 wfProfileIn( __METHOD__ . '-' . $this->name );
864
865 try {
866 $container = $this->getContainer( $fullCont );
867 $prefix = ( $dir == '' ) ? null : "{$dir}/";
868 // Non-recursive: only list dirs right under $dir
869 if ( !empty( $params['topOnly'] ) ) {
870 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
871 foreach ( $objects as $object ) { // files and dirs
872 if ( substr( $object, -1 ) === '/' ) {
873 $dirs[] = $object; // directories end in '/'
874 }
875 }
876 // Recursive: list all dirs under $dir and its subdirs
877 } else {
878 // Get directory from last item of prior page
879 $lastDir = $this->getParentDir( $after ); // must be first page
880 $objects = $container->list_objects( $limit, $after, $prefix );
881 foreach ( $objects as $object ) { // files
882 $objectDir = $this->getParentDir( $object ); // directory of object
883 if ( $objectDir !== false ) { // file has a parent dir
884 // Swift stores paths in UTF-8, using binary sorting.
885 // See function "create_container_table" in common/db.py.
886 // If a directory is not "greater" than the last one,
887 // then it was already listed by the calling iterator.
888 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
889 $pDir = $objectDir;
890 do { // add dir and all its parent dirs
891 $dirs[] = "{$pDir}/";
892 $pDir = $this->getParentDir( $pDir );
893 } while ( $pDir !== false // sanity
894 && strcmp( $pDir, $lastDir ) > 0 // not done already
895 && strlen( $pDir ) > strlen( $dir ) // within $dir
896 );
897 }
898 $lastDir = $objectDir;
899 }
900 }
901 }
902 if ( count( $objects ) < $limit ) {
903 $after = INF; // avoid a second RTT
904 } else {
905 $after = end( $objects ); // update last item
906 }
907 } catch ( NoSuchContainerException $e ) {
908 } catch ( CloudFilesException $e ) { // some other exception?
909 $this->handleException( $e, null, __METHOD__,
910 array( 'cont' => $fullCont, 'dir' => $dir ) );
911 }
912
913 wfProfileOut( __METHOD__ . '-' . $this->name );
914 return $dirs;
915 }
916
917 protected function getParentDir( $path ) {
918 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
919 }
920
921 /**
922 * Do not call this function outside of SwiftFileBackendFileList
923 *
924 * @param $fullCont string Resolved container name
925 * @param $dir string Resolved storage directory with no trailing slash
926 * @param $after string|null Storage path of file to list items after
927 * @param $limit integer Max number of items to list
928 * @param $params Array Includes flag for 'topOnly'
929 * @return Array List of relative paths of files under $dir
930 */
931 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
932 $files = array();
933 if ( $after === INF ) {
934 return $files; // nothing more
935 }
936 wfProfileIn( __METHOD__ . '-' . $this->name );
937
938 try {
939 $container = $this->getContainer( $fullCont );
940 $prefix = ( $dir == '' ) ? null : "{$dir}/";
941 // Non-recursive: only list files right under $dir
942 if ( !empty( $params['topOnly'] ) ) { // files and dirs
943 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
944 foreach ( $objects as $object ) {
945 if ( substr( $object, -1 ) !== '/' ) {
946 $files[] = $object; // directories end in '/'
947 }
948 }
949 // Recursive: list all files under $dir and its subdirs
950 } else { // files
951 $objects = $container->list_objects( $limit, $after, $prefix );
952 $files = $objects;
953 }
954 if ( count( $objects ) < $limit ) {
955 $after = INF; // avoid a second RTT
956 } else {
957 $after = end( $objects ); // update last item
958 }
959 } catch ( NoSuchContainerException $e ) {
960 } catch ( CloudFilesException $e ) { // some other exception?
961 $this->handleException( $e, null, __METHOD__,
962 array( 'cont' => $fullCont, 'dir' => $dir ) );
963 }
964
965 wfProfileOut( __METHOD__ . '-' . $this->name );
966 return $files;
967 }
968
969 /**
970 * @see FileBackendStore::doGetFileSha1base36()
971 * @return bool
972 */
973 protected function doGetFileSha1base36( array $params ) {
974 $stat = $this->getFileStat( $params );
975 if ( $stat ) {
976 return $stat['sha1'];
977 } else {
978 return false;
979 }
980 }
981
982 /**
983 * @see FileBackendStore::doStreamFile()
984 * @return Status
985 */
986 protected function doStreamFile( array $params ) {
987 $status = Status::newGood();
988
989 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
990 if ( $srcRel === null ) {
991 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
992 }
993
994 try {
995 $cont = $this->getContainer( $srcCont );
996 } catch ( NoSuchContainerException $e ) {
997 $status->fatal( 'backend-fail-stream', $params['src'] );
998 return $status;
999 } catch ( CloudFilesException $e ) { // some other exception?
1000 $this->handleException( $e, $status, __METHOD__, $params );
1001 return $status;
1002 }
1003
1004 try {
1005 $output = fopen( 'php://output', 'wb' );
1006 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1007 $obj->stream( $output, $this->headersFromParams( $params ) );
1008 } catch ( CloudFilesException $e ) { // some other exception?
1009 $this->handleException( $e, $status, __METHOD__, $params );
1010 }
1011
1012 return $status;
1013 }
1014
1015 /**
1016 * @see FileBackendStore::getLocalCopy()
1017 * @return null|TempFSFile
1018 */
1019 public function getLocalCopy( array $params ) {
1020 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1021 if ( $srcRel === null ) {
1022 return null;
1023 }
1024
1025 // Blindly create a tmp file and stream to it, catching any exception if the file does
1026 // not exist. Also, doing a stat here will cause infinite loops when filling metadata.
1027 $tmpFile = null;
1028 try {
1029 $sContObj = $this->getContainer( $srcCont );
1030 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1031 // Get source file extension
1032 $ext = FileBackend::extensionFromPath( $srcRel );
1033 // Create a new temporary file...
1034 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1035 if ( $tmpFile ) {
1036 $handle = fopen( $tmpFile->getPath(), 'wb' );
1037 if ( $handle ) {
1038 $obj->stream( $handle, $this->headersFromParams( $params ) );
1039 fclose( $handle );
1040 } else {
1041 $tmpFile = null; // couldn't open temp file
1042 }
1043 }
1044 } catch ( NoSuchContainerException $e ) {
1045 $tmpFile = null;
1046 } catch ( NoSuchObjectException $e ) {
1047 $tmpFile = null;
1048 } catch ( CloudFilesException $e ) { // some other exception?
1049 $tmpFile = null;
1050 $this->handleException( $e, null, __METHOD__, $params );
1051 }
1052
1053 return $tmpFile;
1054 }
1055
1056 /**
1057 * @see FileBackendStore::directoriesAreVirtual()
1058 * @return bool
1059 */
1060 protected function directoriesAreVirtual() {
1061 return true;
1062 }
1063
1064 /**
1065 * Get headers to send to Swift when reading a file based
1066 * on a FileBackend params array, e.g. that of getLocalCopy().
1067 * $params is currently only checked for a 'latest' flag.
1068 *
1069 * @param $params Array
1070 * @return Array
1071 */
1072 protected function headersFromParams( array $params ) {
1073 $hdrs = array();
1074 if ( !empty( $params['latest'] ) ) {
1075 $hdrs[] = 'X-Newest: true';
1076 }
1077 return $hdrs;
1078 }
1079
1080 /**
1081 * @see FileBackendStore::doExecuteOpHandlesInternal()
1082 * @return Array List of corresponding Status objects
1083 */
1084 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1085 $statuses = array();
1086
1087 $cfOps = array(); // list of CF_Async_Op objects
1088 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1089 $cfOps[$index] = $fileOpHandle->cfOp;
1090 }
1091 $batch = new CF_Async_Op_Batch( $cfOps );
1092
1093 $cfOps = $batch->execute();
1094 foreach ( $cfOps as $index => $cfOp ) {
1095 $status = Status::newGood();
1096 try { // catch exceptions; update status
1097 $function = '_getResponse' . $fileOpHandles[$index]->call;
1098 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1099 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1100 } catch ( CloudFilesException $e ) { // some other exception?
1101 $this->handleException( $e, $status,
1102 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1103 }
1104 $statuses[$index] = $status;
1105 }
1106
1107 return $statuses;
1108 }
1109
1110 /**
1111 * Set read/write permissions for a Swift container.
1112 *
1113 * $readGrps is a list of the possible criteria for a request to have
1114 * access to read a container. Each item is one of the following formats:
1115 * - account:user : Grants access if the request is by the given user
1116 * - .r:<regex> : Grants access if the request is from a referrer host that
1117 * matches the expression and the request is not for a listing.
1118 * Setting this to '*' effectively makes a container public.
1119 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1120 * matches the expression and the request for a listing.
1121 *
1122 * $writeGrps is a list of the possible criteria for a request to have
1123 * access to write to a container. Each item is of the following format:
1124 * - account:user : Grants access if the request is by the given user
1125 *
1126 * @see http://swift.openstack.org/misc.html#acls
1127 *
1128 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1129 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1130 *
1131 * @param $contObj CF_Container Swift container
1132 * @param $readGrps Array List of read access routes
1133 * @param $writeGrps Array List of write access routes
1134 * @return Status
1135 */
1136 protected function setContainerAccess(
1137 CF_Container $contObj, array $readGrps, array $writeGrps
1138 ) {
1139 $creds = $contObj->cfs_auth->export_credentials();
1140
1141 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1142
1143 // Note: 10 second timeout consistent with php-cloudfiles
1144 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1145 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1146 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1147 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1148
1149 return $req->execute(); // should return 204
1150 }
1151
1152 /**
1153 * Purge the CDN cache of affected objects if CDN caching is enabled.
1154 * This is for Rackspace/Akamai CDNs.
1155 *
1156 * @param $objects Array List of CF_Object items
1157 * @return void
1158 */
1159 public function purgeCDNCache( array $objects ) {
1160 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1161 foreach ( $objects as $object ) {
1162 try {
1163 $object->purge_from_cdn();
1164 } catch ( CDNNotEnabledException $e ) {
1165 // CDN not enabled; nothing to see here
1166 } catch ( CloudFilesException $e ) {
1167 $this->handleException( $e, null, __METHOD__,
1168 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1169 }
1170 }
1171 }
1172 }
1173
1174 /**
1175 * Get an authenticated connection handle to the Swift proxy
1176 *
1177 * @return CF_Connection|bool False on failure
1178 * @throws CloudFilesException
1179 */
1180 protected function getConnection() {
1181 if ( $this->connException instanceof CloudFilesException ) {
1182 if ( ( time() - $this->connErrorTime ) < 60 ) {
1183 throw $this->connException; // failed last attempt; don't bother
1184 } else { // actually retry this time
1185 $this->connException = null;
1186 $this->connErrorTime = 0;
1187 }
1188 }
1189 // Session keys expire after a while, so we renew them periodically
1190 $reAuth = ( ( time() - $this->sessionStarted ) > $this->authTTL );
1191 // Authenticate with proxy and get a session key...
1192 if ( !$this->conn || $reAuth ) {
1193 $this->sessionStarted = 0;
1194 $this->connContainerCache->clear();
1195 $cacheKey = $this->getCredsCacheKey( $this->auth->username );
1196 $creds = $this->srvCache->get( $cacheKey ); // credentials
1197 if ( is_array( $creds ) ) { // cache hit
1198 $this->auth->load_cached_credentials(
1199 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1200 $this->sessionStarted = time() - ceil( $this->authTTL/2 ); // skew for worst case
1201 } else { // cache miss
1202 try {
1203 $this->auth->authenticate();
1204 $creds = $this->auth->export_credentials();
1205 $this->srvCache->add( $cacheKey, $creds, ceil( $this->authTTL/2 ) ); // cache
1206 $this->sessionStarted = time();
1207 } catch ( CloudFilesException $e ) {
1208 $this->connException = $e; // don't keep re-trying
1209 $this->connErrorTime = time();
1210 throw $e; // throw it back
1211 }
1212 }
1213 if ( $this->conn ) { // re-authorizing?
1214 $this->conn->close(); // close active cURL handles in CF_Http object
1215 }
1216 $this->conn = new CF_Connection( $this->auth );
1217 }
1218 return $this->conn;
1219 }
1220
1221 /**
1222 * Get the cache key for a container
1223 *
1224 * @param $username string
1225 * @return string
1226 */
1227 private function getCredsCacheKey( $username ) {
1228 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1229 }
1230
1231 /**
1232 * @see FileBackendStore::doClearCache()
1233 */
1234 protected function doClearCache( array $paths = null ) {
1235 $this->connContainerCache->clear(); // clear container object cache
1236 }
1237
1238 /**
1239 * Get a Swift container object, possibly from process cache.
1240 * Use $reCache if the file count or byte count is needed.
1241 *
1242 * @param $container string Container name
1243 * @param $bypassCache bool Bypass all caches and load from Swift
1244 * @return CF_Container
1245 * @throws CloudFilesException
1246 */
1247 protected function getContainer( $container, $bypassCache = false ) {
1248 $conn = $this->getConnection(); // Swift proxy connection
1249 if ( $bypassCache ) { // purge cache
1250 $this->connContainerCache->clear( $container );
1251 } elseif ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1252 $this->primeContainerCache( array( $container ) ); // check persistent cache
1253 }
1254 if ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1255 $contObj = $conn->get_container( $container );
1256 // NoSuchContainerException not thrown: container must exist
1257 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache it
1258 if ( !$bypassCache ) {
1259 $this->setContainerCache( $container, // update persistent cache
1260 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1261 );
1262 }
1263 }
1264 return $this->connContainerCache->get( $container, 'obj' );
1265 }
1266
1267 /**
1268 * Create a Swift container
1269 *
1270 * @param $container string Container name
1271 * @return CF_Container
1272 * @throws CloudFilesException
1273 */
1274 protected function createContainer( $container ) {
1275 $conn = $this->getConnection(); // Swift proxy connection
1276 $contObj = $conn->create_container( $container );
1277 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache
1278 return $contObj;
1279 }
1280
1281 /**
1282 * Delete a Swift container
1283 *
1284 * @param $container string Container name
1285 * @return void
1286 * @throws CloudFilesException
1287 */
1288 protected function deleteContainer( $container ) {
1289 $conn = $this->getConnection(); // Swift proxy connection
1290 $this->connContainerCache->clear( $container ); // purge
1291 $conn->delete_container( $container );
1292 }
1293
1294 /**
1295 * @see FileBackendStore::doPrimeContainerCache()
1296 * @return void
1297 */
1298 protected function doPrimeContainerCache( array $containerInfo ) {
1299 try {
1300 $conn = $this->getConnection(); // Swift proxy connection
1301 foreach ( $containerInfo as $container => $info ) {
1302 $contObj = new CF_Container( $conn->cfs_auth, $conn->cfs_http,
1303 $container, $info['count'], $info['bytes'] );
1304 $this->connContainerCache->set( $container, 'obj', $contObj );
1305 }
1306 } catch ( CloudFilesException $e ) { // some other exception?
1307 $this->handleException( $e, null, __METHOD__, array() );
1308 }
1309 }
1310
1311 /**
1312 * Log an unexpected exception for this backend.
1313 * This also sets the Status object to have a fatal error.
1314 *
1315 * @param $e Exception
1316 * @param $status Status|null
1317 * @param $func string
1318 * @param $params Array
1319 * @return void
1320 */
1321 protected function handleException( Exception $e, $status, $func, array $params ) {
1322 if ( $status instanceof Status ) {
1323 if ( $e instanceof AuthenticationException ) {
1324 $status->fatal( 'backend-fail-connect', $this->name );
1325 } else {
1326 $status->fatal( 'backend-fail-internal', $this->name );
1327 }
1328 }
1329 if ( $e->getMessage() ) {
1330 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1331 }
1332 if ( $e instanceof InvalidResponseException ) { // possibly a stale token
1333 $this->srvCache->delete( $this->getCredsCacheKey( $this->auth->username ) );
1334 }
1335 wfDebugLog( 'SwiftBackend',
1336 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1337 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1338 );
1339 }
1340 }
1341
1342 /**
1343 * @see FileBackendStoreOpHandle
1344 */
1345 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1346 /** @var CF_Async_Op */
1347 public $cfOp;
1348 /** @var Array */
1349 public $affectedObjects = array();
1350
1351 public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
1352 $this->backend = $backend;
1353 $this->params = $params;
1354 $this->call = $call;
1355 $this->cfOp = $cfOp;
1356 }
1357 }
1358
1359 /**
1360 * SwiftFileBackend helper class to page through listings.
1361 * Swift also has a listing limit of 10,000 objects for sanity.
1362 * Do not use this class from places outside SwiftFileBackend.
1363 *
1364 * @ingroup FileBackend
1365 */
1366 abstract class SwiftFileBackendList implements Iterator {
1367 /** @var Array */
1368 protected $bufferIter = array();
1369 protected $bufferAfter = null; // string; list items *after* this path
1370 protected $pos = 0; // integer
1371 /** @var Array */
1372 protected $params = array();
1373
1374 /** @var SwiftFileBackend */
1375 protected $backend;
1376 protected $container; // string; container name
1377 protected $dir; // string; storage directory
1378 protected $suffixStart; // integer
1379
1380 const PAGE_SIZE = 9000; // file listing buffer size
1381
1382 /**
1383 * @param $backend SwiftFileBackend
1384 * @param $fullCont string Resolved container name
1385 * @param $dir string Resolved directory relative to container
1386 * @param $params Array
1387 */
1388 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1389 $this->backend = $backend;
1390 $this->container = $fullCont;
1391 $this->dir = $dir;
1392 if ( substr( $this->dir, -1 ) === '/' ) {
1393 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1394 }
1395 if ( $this->dir == '' ) { // whole container
1396 $this->suffixStart = 0;
1397 } else { // dir within container
1398 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1399 }
1400 $this->params = $params;
1401 }
1402
1403 /**
1404 * @see Iterator::key()
1405 * @return integer
1406 */
1407 public function key() {
1408 return $this->pos;
1409 }
1410
1411 /**
1412 * @see Iterator::next()
1413 * @return void
1414 */
1415 public function next() {
1416 // Advance to the next file in the page
1417 next( $this->bufferIter );
1418 ++$this->pos;
1419 // Check if there are no files left in this page and
1420 // advance to the next page if this page was not empty.
1421 if ( !$this->valid() && count( $this->bufferIter ) ) {
1422 $this->bufferIter = $this->pageFromList(
1423 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1424 ); // updates $this->bufferAfter
1425 }
1426 }
1427
1428 /**
1429 * @see Iterator::rewind()
1430 * @return void
1431 */
1432 public function rewind() {
1433 $this->pos = 0;
1434 $this->bufferAfter = null;
1435 $this->bufferIter = $this->pageFromList(
1436 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1437 ); // updates $this->bufferAfter
1438 }
1439
1440 /**
1441 * @see Iterator::valid()
1442 * @return bool
1443 */
1444 public function valid() {
1445 if ( $this->bufferIter === null ) {
1446 return false; // some failure?
1447 } else {
1448 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1449 }
1450 }
1451
1452 /**
1453 * Get the given list portion (page)
1454 *
1455 * @param $container string Resolved container name
1456 * @param $dir string Resolved path relative to container
1457 * @param $after string|null
1458 * @param $limit integer
1459 * @param $params Array
1460 * @return Traversable|Array|null Returns null on failure
1461 */
1462 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1463 }
1464
1465 /**
1466 * Iterator for listing directories
1467 */
1468 class SwiftFileBackendDirList extends SwiftFileBackendList {
1469 /**
1470 * @see Iterator::current()
1471 * @return string|bool String (relative path) or false
1472 */
1473 public function current() {
1474 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1475 }
1476
1477 /**
1478 * @see SwiftFileBackendList::pageFromList()
1479 * @return Array|null
1480 */
1481 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1482 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1483 }
1484 }
1485
1486 /**
1487 * Iterator for listing regular files
1488 */
1489 class SwiftFileBackendFileList extends SwiftFileBackendList {
1490 /**
1491 * @see Iterator::current()
1492 * @return string|bool String (relative path) or false
1493 */
1494 public function current() {
1495 return substr( current( $this->bufferIter ), $this->suffixStart );
1496 }
1497
1498 /**
1499 * @see SwiftFileBackendList::pageFromList()
1500 * @return Array|null
1501 */
1502 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1503 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1504 }
1505 }