Merge "[FileRepo] Use the backend sha1 function for getting sha1s."
[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 $status = Status::newGood();
733 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
734 if ( $status->isOK() ) {
735 # Do not stat the file in getLocalCopy() to avoid infinite loops
736 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
737 if ( $tmpFile ) {
738 $hash = $tmpFile->getSha1Base36();
739 if ( $hash !== false ) {
740 $obj->metadata['Sha1base36'] = $hash;
741 $obj->sync_metadata(); // save to Swift
742 return true; // success
743 }
744 }
745 }
746 $obj->metadata['Sha1base36'] = false;
747 return false; // failed
748 }
749
750 /**
751 * @see FileBackend::getFileContents()
752 * @return bool|null|string
753 */
754 public function getFileContents( array $params ) {
755 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
756 if ( $srcRel === null ) {
757 return false; // invalid storage path
758 }
759
760 if ( !$this->fileExists( $params ) ) {
761 return null;
762 }
763
764 $data = false;
765 try {
766 $sContObj = $this->getContainer( $srcCont );
767 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
768 $data = $obj->read( $this->headersFromParams( $params ) );
769 } catch ( NoSuchContainerException $e ) {
770 } catch ( CloudFilesException $e ) { // some other exception?
771 $this->handleException( $e, null, __METHOD__, $params );
772 }
773
774 return $data;
775 }
776
777 /**
778 * @see FileBackendStore::doDirectoryExists()
779 * @return bool|null
780 */
781 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
782 try {
783 $container = $this->getContainer( $fullCont );
784 $prefix = ( $dir == '' ) ? null : "{$dir}/";
785 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
786 } catch ( NoSuchContainerException $e ) {
787 return false;
788 } catch ( CloudFilesException $e ) { // some other exception?
789 $this->handleException( $e, null, __METHOD__,
790 array( 'cont' => $fullCont, 'dir' => $dir ) );
791 }
792
793 return null; // error
794 }
795
796 /**
797 * @see FileBackendStore::getDirectoryListInternal()
798 * @return SwiftFileBackendDirList
799 */
800 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
801 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
802 }
803
804 /**
805 * @see FileBackendStore::getFileListInternal()
806 * @return SwiftFileBackendFileList
807 */
808 public function getFileListInternal( $fullCont, $dir, array $params ) {
809 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
810 }
811
812 /**
813 * Do not call this function outside of SwiftFileBackendFileList
814 *
815 * @param $fullCont string Resolved container name
816 * @param $dir string Resolved storage directory with no trailing slash
817 * @param $after string|null Storage path of file to list items after
818 * @param $limit integer Max number of items to list
819 * @param $params Array Includes flag for 'topOnly'
820 * @return Array List of relative paths of dirs directly under $dir
821 */
822 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
823 $dirs = array();
824 if ( $after === INF ) {
825 return $dirs; // nothing more
826 }
827 wfProfileIn( __METHOD__ . '-' . $this->name );
828
829 try {
830 $container = $this->getContainer( $fullCont );
831 $prefix = ( $dir == '' ) ? null : "{$dir}/";
832 // Non-recursive: only list dirs right under $dir
833 if ( !empty( $params['topOnly'] ) ) {
834 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
835 foreach ( $objects as $object ) { // files and dirs
836 if ( substr( $object, -1 ) === '/' ) {
837 $dirs[] = $object; // directories end in '/'
838 }
839 }
840 // Recursive: list all dirs under $dir and its subdirs
841 } else {
842 // Get directory from last item of prior page
843 $lastDir = $this->getParentDir( $after ); // must be first page
844 $objects = $container->list_objects( $limit, $after, $prefix );
845 foreach ( $objects as $object ) { // files
846 $objectDir = $this->getParentDir( $object ); // directory of object
847 if ( $objectDir !== false ) { // file has a parent dir
848 // Swift stores paths in UTF-8, using binary sorting.
849 // See function "create_container_table" in common/db.py.
850 // If a directory is not "greater" than the last one,
851 // then it was already listed by the calling iterator.
852 if ( $objectDir > $lastDir ) {
853 $pDir = $objectDir;
854 do { // add dir and all its parent dirs
855 $dirs[] = "{$pDir}/";
856 $pDir = $this->getParentDir( $pDir );
857 } while ( $pDir !== false // sanity
858 && $pDir > $lastDir // not done already
859 && strlen( $pDir ) > strlen( $dir ) // within $dir
860 );
861 }
862 $lastDir = $objectDir;
863 }
864 }
865 }
866 if ( count( $objects ) < $limit ) {
867 $after = INF; // avoid a second RTT
868 } else {
869 $after = end( $objects ); // update last item
870 }
871 } catch ( NoSuchContainerException $e ) {
872 } catch ( CloudFilesException $e ) { // some other exception?
873 $this->handleException( $e, null, __METHOD__,
874 array( 'cont' => $fullCont, 'dir' => $dir ) );
875 }
876
877 wfProfileOut( __METHOD__ . '-' . $this->name );
878 return $dirs;
879 }
880
881 protected function getParentDir( $path ) {
882 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
883 }
884
885 /**
886 * Do not call this function outside of SwiftFileBackendFileList
887 *
888 * @param $fullCont string Resolved container name
889 * @param $dir string Resolved storage directory with no trailing slash
890 * @param $after string|null Storage path of file to list items after
891 * @param $limit integer Max number of items to list
892 * @param $params Array Includes flag for 'topOnly'
893 * @return Array List of relative paths of files under $dir
894 */
895 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
896 $files = array();
897 if ( $after === INF ) {
898 return $files; // nothing more
899 }
900 wfProfileIn( __METHOD__ . '-' . $this->name );
901
902 try {
903 $container = $this->getContainer( $fullCont );
904 $prefix = ( $dir == '' ) ? null : "{$dir}/";
905 // Non-recursive: only list files right under $dir
906 if ( !empty( $params['topOnly'] ) ) { // files and dirs
907 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
908 foreach ( $objects as $object ) {
909 if ( substr( $object, -1 ) !== '/' ) {
910 $files[] = $object; // directories end in '/'
911 }
912 }
913 // Recursive: list all files under $dir and its subdirs
914 } else { // files
915 $objects = $container->list_objects( $limit, $after, $prefix );
916 $files = $objects;
917 }
918 if ( count( $objects ) < $limit ) {
919 $after = INF; // avoid a second RTT
920 } else {
921 $after = end( $objects ); // update last item
922 }
923 } catch ( NoSuchContainerException $e ) {
924 } catch ( CloudFilesException $e ) { // some other exception?
925 $this->handleException( $e, null, __METHOD__,
926 array( 'cont' => $fullCont, 'dir' => $dir ) );
927 }
928
929 wfProfileOut( __METHOD__ . '-' . $this->name );
930 return $files;
931 }
932
933 /**
934 * @see FileBackendStore::doGetFileSha1base36()
935 * @return bool
936 */
937 protected function doGetFileSha1base36( array $params ) {
938 $stat = $this->getFileStat( $params );
939 if ( $stat ) {
940 return $stat['sha1'];
941 } else {
942 return false;
943 }
944 }
945
946 /**
947 * @see FileBackendStore::doStreamFile()
948 * @return Status
949 */
950 protected function doStreamFile( array $params ) {
951 $status = Status::newGood();
952
953 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
954 if ( $srcRel === null ) {
955 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
956 }
957
958 try {
959 $cont = $this->getContainer( $srcCont );
960 } catch ( NoSuchContainerException $e ) {
961 $status->fatal( 'backend-fail-stream', $params['src'] );
962 return $status;
963 } catch ( CloudFilesException $e ) { // some other exception?
964 $this->handleException( $e, $status, __METHOD__, $params );
965 return $status;
966 }
967
968 try {
969 $output = fopen( 'php://output', 'wb' );
970 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
971 $obj->stream( $output, $this->headersFromParams( $params ) );
972 } catch ( CloudFilesException $e ) { // some other exception?
973 $this->handleException( $e, $status, __METHOD__, $params );
974 }
975
976 return $status;
977 }
978
979 /**
980 * @see FileBackendStore::getLocalCopy()
981 * @return null|TempFSFile
982 */
983 public function getLocalCopy( array $params ) {
984 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
985 if ( $srcRel === null ) {
986 return null;
987 }
988
989 # Check the recursion guard to avoid loops when filling metadata
990 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
991 return null;
992 }
993
994 $tmpFile = null;
995 try {
996 $sContObj = $this->getContainer( $srcCont );
997 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
998 // Get source file extension
999 $ext = FileBackend::extensionFromPath( $srcRel );
1000 // Create a new temporary file...
1001 $tmpFile = TempFSFile::factory( wfBaseName( $srcRel ) . '_', $ext );
1002 if ( $tmpFile ) {
1003 $handle = fopen( $tmpFile->getPath(), 'wb' );
1004 if ( $handle ) {
1005 $obj->stream( $handle, $this->headersFromParams( $params ) );
1006 fclose( $handle );
1007 } else {
1008 $tmpFile = null; // couldn't open temp file
1009 }
1010 }
1011 } catch ( NoSuchContainerException $e ) {
1012 $tmpFile = null;
1013 } catch ( CloudFilesException $e ) { // some other exception?
1014 $tmpFile = null;
1015 $this->handleException( $e, null, __METHOD__, $params );
1016 }
1017
1018 return $tmpFile;
1019 }
1020
1021 /**
1022 * @see FileBackendStore::directoriesAreVirtual()
1023 * @return bool
1024 */
1025 protected function directoriesAreVirtual() {
1026 return true;
1027 }
1028
1029 /**
1030 * Get headers to send to Swift when reading a file based
1031 * on a FileBackend params array, e.g. that of getLocalCopy().
1032 * $params is currently only checked for a 'latest' flag.
1033 *
1034 * @param $params Array
1035 * @return Array
1036 */
1037 protected function headersFromParams( array $params ) {
1038 $hdrs = array();
1039 if ( !empty( $params['latest'] ) ) {
1040 $hdrs[] = 'X-Newest: true';
1041 }
1042 return $hdrs;
1043 }
1044
1045 /**
1046 * @see FileBackendStore::doExecuteOpHandlesInternal()
1047 * @return Array List of corresponding Status objects
1048 */
1049 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1050 $statuses = array();
1051
1052 $cfOps = array(); // list of CF_Async_Op objects
1053 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1054 $cfOps[$index] = $fileOpHandle->cfOp;
1055 }
1056 $batch = new CF_Async_Op_Batch( $cfOps );
1057
1058 $cfOps = $batch->execute();
1059 foreach ( $cfOps as $index => $cfOp ) {
1060 $status = Status::newGood();
1061 try { // catch exceptions; update status
1062 $function = '_getResponse' . $fileOpHandles[$index]->call;
1063 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1064 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1065 } catch ( CloudFilesException $e ) { // some other exception?
1066 $this->handleException( $e, $status,
1067 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1068 }
1069 $statuses[$index] = $status;
1070 }
1071
1072 return $statuses;
1073 }
1074
1075 /**
1076 * Set read/write permissions for a Swift container.
1077 *
1078 * $readGrps is a list of the possible criteria for a request to have
1079 * access to read a container. Each item is one of the following formats:
1080 * - account:user : Grants access if the request is by the given user
1081 * - .r:<regex> : Grants access if the request is from a referrer host that
1082 * matches the expression and the request is not for a listing.
1083 * Setting this to '*' effectively makes a container public.
1084 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1085 * matches the expression and the request for a listing.
1086 *
1087 * $writeGrps is a list of the possible criteria for a request to have
1088 * access to write to a container. Each item is of the following format:
1089 * - account:user : Grants access if the request is by the given user
1090 *
1091 * @see http://swift.openstack.org/misc.html#acls
1092 *
1093 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1094 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1095 *
1096 * @param $contObj CF_Container Swift container
1097 * @param $readGrps Array List of read access routes
1098 * @param $writeGrps Array List of write access routes
1099 * @return Status
1100 */
1101 protected function setContainerAccess(
1102 CF_Container $contObj, array $readGrps, array $writeGrps
1103 ) {
1104 $creds = $contObj->cfs_auth->export_credentials();
1105
1106 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1107
1108 // Note: 10 second timeout consistent with php-cloudfiles
1109 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1110 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1111 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1112 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1113
1114 return $req->execute(); // should return 204
1115 }
1116
1117 /**
1118 * Purge the CDN cache of affected objects if CDN caching is enabled.
1119 * This is for Rackspace/Akamai CDNs.
1120 *
1121 * @param $objects Array List of CF_Object items
1122 * @return void
1123 */
1124 public function purgeCDNCache( array $objects ) {
1125 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1126 foreach ( $objects as $object ) {
1127 try {
1128 $object->purge_from_cdn();
1129 } catch ( CDNNotEnabledException $e ) {
1130 // CDN not enabled; nothing to see here
1131 } catch ( CloudFilesException $e ) {
1132 $this->handleException( $e, null, __METHOD__,
1133 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1134 }
1135 }
1136 }
1137 }
1138
1139 /**
1140 * Get an authenticated connection handle to the Swift proxy
1141 *
1142 * @return CF_Connection|bool False on failure
1143 * @throws CloudFilesException
1144 */
1145 protected function getConnection() {
1146 if ( $this->connException instanceof CloudFilesException ) {
1147 if ( ( time() - $this->connErrorTime ) < 60 ) {
1148 throw $this->connException; // failed last attempt; don't bother
1149 } else { // actually retry this time
1150 $this->connException = null;
1151 $this->connErrorTime = 0;
1152 }
1153 }
1154 // Session keys expire after a while, so we renew them periodically
1155 $reAuth = ( ( time() - $this->sessionStarted ) > $this->authTTL );
1156 // Authenticate with proxy and get a session key...
1157 if ( !$this->conn || $reAuth ) {
1158 $this->sessionStarted = 0;
1159 $this->connContainerCache->clear();
1160 $cacheKey = $this->getCredsCacheKey( $this->auth->username );
1161 $creds = $this->srvCache->get( $cacheKey ); // credentials
1162 if ( is_array( $creds ) ) { // cache hit
1163 $this->auth->load_cached_credentials(
1164 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1165 $this->sessionStarted = time() - ceil( $this->authTTL/2 ); // skew for worst case
1166 } else { // cache miss
1167 try {
1168 $this->auth->authenticate();
1169 $creds = $this->auth->export_credentials();
1170 $this->srvCache->add( $cacheKey, $creds, ceil( $this->authTTL/2 ) ); // cache
1171 $this->sessionStarted = time();
1172 } catch ( CloudFilesException $e ) {
1173 $this->connException = $e; // don't keep re-trying
1174 $this->connErrorTime = time();
1175 throw $e; // throw it back
1176 }
1177 }
1178 if ( $this->conn ) { // re-authorizing?
1179 $this->conn->close(); // close active cURL handles in CF_Http object
1180 }
1181 $this->conn = new CF_Connection( $this->auth );
1182 }
1183 return $this->conn;
1184 }
1185
1186 /**
1187 * Get the cache key for a container
1188 *
1189 * @param $username string
1190 * @return string
1191 */
1192 private function getCredsCacheKey( $username ) {
1193 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1194 }
1195
1196 /**
1197 * @see FileBackendStore::doClearCache()
1198 */
1199 protected function doClearCache( array $paths = null ) {
1200 $this->connContainerCache->clear(); // clear container object cache
1201 }
1202
1203 /**
1204 * Get a Swift container object, possibly from process cache.
1205 * Use $reCache if the file count or byte count is needed.
1206 *
1207 * @param $container string Container name
1208 * @param $bypassCache bool Bypass all caches and load from Swift
1209 * @return CF_Container
1210 * @throws CloudFilesException
1211 */
1212 protected function getContainer( $container, $bypassCache = false ) {
1213 $conn = $this->getConnection(); // Swift proxy connection
1214 if ( $bypassCache ) { // purge cache
1215 $this->connContainerCache->clear( $container );
1216 } elseif ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1217 $this->primeContainerCache( array( $container ) ); // check persistent cache
1218 }
1219 if ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1220 $contObj = $conn->get_container( $container );
1221 // NoSuchContainerException not thrown: container must exist
1222 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache it
1223 if ( !$bypassCache ) {
1224 $this->setContainerCache( $container, // update persistent cache
1225 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1226 );
1227 }
1228 }
1229 return $this->connContainerCache->get( $container, 'obj' );
1230 }
1231
1232 /**
1233 * Create a Swift container
1234 *
1235 * @param $container string Container name
1236 * @return CF_Container
1237 * @throws CloudFilesException
1238 */
1239 protected function createContainer( $container ) {
1240 $conn = $this->getConnection(); // Swift proxy connection
1241 $contObj = $conn->create_container( $container );
1242 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache
1243 return $contObj;
1244 }
1245
1246 /**
1247 * Delete a Swift container
1248 *
1249 * @param $container string Container name
1250 * @return void
1251 * @throws CloudFilesException
1252 */
1253 protected function deleteContainer( $container ) {
1254 $conn = $this->getConnection(); // Swift proxy connection
1255 $this->connContainerCache->clear( $container ); // purge
1256 $conn->delete_container( $container );
1257 }
1258
1259 /**
1260 * @see FileBackendStore::doPrimeContainerCache()
1261 * @return void
1262 */
1263 protected function doPrimeContainerCache( array $containerInfo ) {
1264 try {
1265 $conn = $this->getConnection(); // Swift proxy connection
1266 foreach ( $containerInfo as $container => $info ) {
1267 $contObj = new CF_Container( $conn->cfs_auth, $conn->cfs_http,
1268 $container, $info['count'], $info['bytes'] );
1269 $this->connContainerCache->set( $container, 'obj', $contObj );
1270 }
1271 } catch ( CloudFilesException $e ) { // some other exception?
1272 $this->handleException( $e, null, __METHOD__, array() );
1273 }
1274 }
1275
1276 /**
1277 * Log an unexpected exception for this backend.
1278 * This also sets the Status object to have a fatal error.
1279 *
1280 * @param $e Exception
1281 * @param $status Status|null
1282 * @param $func string
1283 * @param $params Array
1284 * @return void
1285 */
1286 protected function handleException( Exception $e, $status, $func, array $params ) {
1287 if ( $status instanceof Status ) {
1288 if ( $e instanceof AuthenticationException ) {
1289 $status->fatal( 'backend-fail-connect', $this->name );
1290 } else {
1291 $status->fatal( 'backend-fail-internal', $this->name );
1292 }
1293 }
1294 if ( $e->getMessage() ) {
1295 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1296 }
1297 wfDebugLog( 'SwiftBackend',
1298 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1299 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1300 );
1301 }
1302 }
1303
1304 /**
1305 * @see FileBackendStoreOpHandle
1306 */
1307 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1308 /** @var CF_Async_Op */
1309 public $cfOp;
1310 /** @var Array */
1311 public $affectedObjects = array();
1312
1313 public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
1314 $this->backend = $backend;
1315 $this->params = $params;
1316 $this->call = $call;
1317 $this->cfOp = $cfOp;
1318 }
1319 }
1320
1321 /**
1322 * SwiftFileBackend helper class to page through listings.
1323 * Swift also has a listing limit of 10,000 objects for sanity.
1324 * Do not use this class from places outside SwiftFileBackend.
1325 *
1326 * @ingroup FileBackend
1327 */
1328 abstract class SwiftFileBackendList implements Iterator {
1329 /** @var Array */
1330 protected $bufferIter = array();
1331 protected $bufferAfter = null; // string; list items *after* this path
1332 protected $pos = 0; // integer
1333 /** @var Array */
1334 protected $params = array();
1335
1336 /** @var SwiftFileBackend */
1337 protected $backend;
1338 protected $container; // string; container name
1339 protected $dir; // string; storage directory
1340 protected $suffixStart; // integer
1341
1342 const PAGE_SIZE = 9000; // file listing buffer size
1343
1344 /**
1345 * @param $backend SwiftFileBackend
1346 * @param $fullCont string Resolved container name
1347 * @param $dir string Resolved directory relative to container
1348 * @param $params Array
1349 */
1350 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1351 $this->backend = $backend;
1352 $this->container = $fullCont;
1353 $this->dir = $dir;
1354 if ( substr( $this->dir, -1 ) === '/' ) {
1355 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1356 }
1357 if ( $this->dir == '' ) { // whole container
1358 $this->suffixStart = 0;
1359 } else { // dir within container
1360 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1361 }
1362 $this->params = $params;
1363 }
1364
1365 /**
1366 * @see Iterator::key()
1367 * @return integer
1368 */
1369 public function key() {
1370 return $this->pos;
1371 }
1372
1373 /**
1374 * @see Iterator::next()
1375 * @return void
1376 */
1377 public function next() {
1378 // Advance to the next file in the page
1379 next( $this->bufferIter );
1380 ++$this->pos;
1381 // Check if there are no files left in this page and
1382 // advance to the next page if this page was not empty.
1383 if ( !$this->valid() && count( $this->bufferIter ) ) {
1384 $this->bufferIter = $this->pageFromList(
1385 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1386 ); // updates $this->bufferAfter
1387 }
1388 }
1389
1390 /**
1391 * @see Iterator::rewind()
1392 * @return void
1393 */
1394 public function rewind() {
1395 $this->pos = 0;
1396 $this->bufferAfter = null;
1397 $this->bufferIter = $this->pageFromList(
1398 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1399 ); // updates $this->bufferAfter
1400 }
1401
1402 /**
1403 * @see Iterator::valid()
1404 * @return bool
1405 */
1406 public function valid() {
1407 if ( $this->bufferIter === null ) {
1408 return false; // some failure?
1409 } else {
1410 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1411 }
1412 }
1413
1414 /**
1415 * Get the given list portion (page)
1416 *
1417 * @param $container string Resolved container name
1418 * @param $dir string Resolved path relative to container
1419 * @param $after string|null
1420 * @param $limit integer
1421 * @param $params Array
1422 * @return Traversable|Array|null Returns null on failure
1423 */
1424 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1425 }
1426
1427 /**
1428 * Iterator for listing directories
1429 */
1430 class SwiftFileBackendDirList extends SwiftFileBackendList {
1431 /**
1432 * @see Iterator::current()
1433 * @return string|bool String (relative path) or false
1434 */
1435 public function current() {
1436 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1437 }
1438
1439 /**
1440 * @see SwiftFileBackendList::pageFromList()
1441 * @return Array|null
1442 */
1443 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1444 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1445 }
1446 }
1447
1448 /**
1449 * Iterator for listing regular files
1450 */
1451 class SwiftFileBackendFileList extends SwiftFileBackendList {
1452 /**
1453 * @see Iterator::current()
1454 * @return string|bool String (relative path) or false
1455 */
1456 public function current() {
1457 return substr( current( $this->bufferIter ), $this->suffixStart );
1458 }
1459
1460 /**
1461 * @see SwiftFileBackendList::pageFromList()
1462 * @return Array|null
1463 */
1464 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1465 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1466 }
1467 }