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