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