Merge "Further expand Status unit tests"
[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 (or Ceph RGW) 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 Swift authentication handler */
41 protected $auth;
42
43 /** @var int TTL in seconds */
44 protected $authTTL;
45
46 /** @var string Shared secret value for making temp URLs */
47 protected $swiftTempUrlKey;
48
49 /** @var string Username to handle unauthenticated requests */
50 protected $swiftAnonUser;
51
52 /** @var bool Whether CloudFiles CDN is enabled */
53 protected $swiftUseCDN;
54
55 /** @var int How long to cache things in the CDN */
56 protected $swiftCDNExpiry;
57
58 /** @var bool Whether object CDN purging is enabled */
59 protected $swiftCDNPurgable;
60
61 // Rados Gateway specific options
62 /** @var string S3 access key */
63 protected $rgwS3AccessKey;
64
65 /** @var string S3 authentication key */
66 protected $rgwS3SecretKey;
67
68 /** @var CF_Connection Swift connection handle*/
69 protected $conn;
70
71 /** @var int UNIX timestamp */
72 protected $sessionStarted = 0;
73
74 /** @var CloudFilesException */
75 protected $connException;
76
77 /** @var int UNIX timestamp */
78 protected $connErrorTime = 0;
79
80 /** @var BagOStuff */
81 protected $srvCache;
82
83 /** @var ProcessCacheLRU */
84 protected $connContainerCache; // container object cache
85
86 /**
87 * @see FileBackendStore::__construct()
88 * Additional $config params include:
89 * - swiftAuthUrl : Swift authentication server URL
90 * - swiftUser : Swift user used by MediaWiki (account:username)
91 * - swiftKey : Swift authentication key for the above user
92 * - swiftAuthTTL : Swift authentication TTL (seconds)
93 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
94 * Do not set this until it has been set in the backend.
95 * - swiftAnonUser : Swift user used for end-user requests (account:username).
96 * If set, then views of public containers are assumed to go
97 * through this user. If not set, then public containers are
98 * accessible to unauthenticated requests via ".r:*" in the ACL.
99 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
100 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
101 * If files may likely change, this should probably not exceed
102 * a few days. For example, deletions may take this long to apply.
103 * If object purging is enabled, however, this is not an issue.
104 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
105 * - shardViaHashLevels : Map of container names to sharding config with:
106 * - base : base of hash characters, 16 or 36
107 * - levels : the number of hash levels (and digits)
108 * - repeat : hash subdirectories are prefixed with all the
109 * parent hash directory names (e.g. "a/ab/abc")
110 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
111 * If those are not available, then the main cache will be used.
112 * This is probably insecure in shared hosting environments.
113 * - rgwS3AccessKey : Ragos Gateway S3 "access key" value on the account.
114 * Do not set this until it has been set in the backend.
115 * This is used for generating expiring pre-authenticated URLs.
116 * Only use this when using rgw and to work around
117 * http://tracker.newdream.net/issues/3454.
118 * - rgwS3SecretKey : Ragos Gateway S3 "secret key" value on the account.
119 * Do not set this until it has been set in the backend.
120 * This is used for generating expiring pre-authenticated URLs.
121 * Only use this when using rgw and to work around
122 * http://tracker.newdream.net/issues/3454.
123 */
124 public function __construct( array $config ) {
125 parent::__construct( $config );
126 if ( !class_exists( 'CF_Constants' ) ) {
127 throw new MWException( 'SwiftCloudFiles extension not installed.' );
128 }
129 // Required settings
130 $this->auth = new CF_Authentication(
131 $config['swiftUser'],
132 $config['swiftKey'],
133 null, // account; unused
134 $config['swiftAuthUrl']
135 );
136 // Optional settings
137 $this->authTTL = isset( $config['swiftAuthTTL'] )
138 ? $config['swiftAuthTTL']
139 : 5 * 60; // some sane number
140 $this->swiftAnonUser = isset( $config['swiftAnonUser'] )
141 ? $config['swiftAnonUser']
142 : '';
143 $this->swiftTempUrlKey = isset( $config['swiftTempUrlKey'] )
144 ? $config['swiftTempUrlKey']
145 : '';
146 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
147 ? $config['shardViaHashLevels']
148 : '';
149 $this->swiftUseCDN = isset( $config['swiftUseCDN'] )
150 ? $config['swiftUseCDN']
151 : false;
152 $this->swiftCDNExpiry = isset( $config['swiftCDNExpiry'] )
153 ? $config['swiftCDNExpiry']
154 : 12 * 3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
155 $this->swiftCDNPurgable = isset( $config['swiftCDNPurgable'] )
156 ? $config['swiftCDNPurgable']
157 : true;
158 $this->rgwS3AccessKey = isset( $config['rgwS3AccessKey'] )
159 ? $config['rgwS3AccessKey']
160 : '';
161 $this->rgwS3SecretKey = isset( $config['rgwS3SecretKey'] )
162 ? $config['rgwS3SecretKey']
163 : '';
164 // Cache container information to mask latency
165 $this->memCache = wfGetMainCache();
166 // Process cache for container info
167 $this->connContainerCache = new ProcessCacheLRU( 300 );
168 // Cache auth token information to avoid RTTs
169 if ( !empty( $config['cacheAuthInfo'] ) ) {
170 if ( PHP_SAPI === 'cli' ) {
171 $this->srvCache = wfGetMainCache(); // preferrably memcached
172 } else {
173 try { // look for APC, XCache, WinCache, ect...
174 $this->srvCache = ObjectCache::newAccelerator( array() );
175 } catch ( Exception $e ) {
176 }
177 }
178 }
179 $this->srvCache = $this->srvCache ? $this->srvCache : new EmptyBagOStuff();
180 }
181
182 /**
183 * @see FileBackendStore::resolveContainerPath()
184 * @param string $container
185 * @param string $relStoragePath
186 * @return string|null Returns null when the URL encoded storage path is
187 * longer than 1024 characters or not UTF-8 encoded.
188 */
189 protected function resolveContainerPath( $container, $relStoragePath ) {
190 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
191 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
192 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
193 return null; // too long for Swift
194 }
195
196 return $relStoragePath;
197 }
198
199 public function isPathUsableInternal( $storagePath ) {
200 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
201 if ( $rel === null ) {
202 return false; // invalid
203 }
204
205 try {
206 $this->getContainer( $container );
207
208 return true; // container exists
209 } catch ( NoSuchContainerException $e ) {
210 } catch ( CloudFilesException $e ) { // some other exception?
211 $this->handleException( $e, null, __METHOD__, array( 'path' => $storagePath ) );
212 }
213
214 return false;
215 }
216
217 /**
218 * @param array $headers
219 * @return array
220 */
221 protected function sanitizeHdrs( array $headers ) {
222 // By default, Swift has annoyingly low maximum header value limits
223 if ( isset( $headers['Content-Disposition'] ) ) {
224 $headers['Content-Disposition'] = $this->truncDisp( $headers['Content-Disposition'] );
225 }
226
227 return $headers;
228 }
229
230 /**
231 * @param string $disposition Content-Disposition header value
232 * @return string Truncated Content-Disposition header value to meet Swift limits
233 */
234 protected function truncDisp( $disposition ) {
235 $res = '';
236 foreach ( explode( ';', $disposition ) as $part ) {
237 $part = trim( $part );
238 $new = ( $res === '' ) ? $part : "{$res};{$part}";
239 if ( strlen( $new ) <= 255 ) {
240 $res = $new;
241 } else {
242 break; // too long; sigh
243 }
244 }
245
246 return $res;
247 }
248
249 protected function doCreateInternal( array $params ) {
250 $status = Status::newGood();
251
252 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
253 if ( $dstRel === null ) {
254 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
255
256 return $status;
257 }
258
259 // (a) Check the destination container and object
260 try {
261 $dContObj = $this->getContainer( $dstCont );
262 } catch ( NoSuchContainerException $e ) {
263 $status->fatal( 'backend-fail-create', $params['dst'] );
264
265 return $status;
266 } catch ( CloudFilesException $e ) { // some other exception?
267 $this->handleException( $e, $status, __METHOD__, $params );
268
269 return $status;
270 }
271
272 // (b) Get a SHA-1 hash of the object
273 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
274
275 // (c) Actually create the object
276 try {
277 // Create a fresh CF_Object with no fields preloaded.
278 // We don't want to preserve headers, metadata, and such.
279 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
280 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
281 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
282 // The MD5 here will be checked within Swift against its own MD5.
283 $obj->set_etag( md5( $params['content'] ) );
284 // Use the same content type as StreamFile for security
285 $obj->content_type = $this->getContentType( $params['dst'], $params['content'], null );
286 // Set any other custom headers if requested
287 if ( isset( $params['headers'] ) ) {
288 $obj->headers += $this->sanitizeHdrs( $params['headers'] );
289 }
290 if ( !empty( $params['async'] ) ) { // deferred
291 $op = $obj->write_async( $params['content'] );
292 $status->value = new SwiftFileOpHandle( $this, $params, 'Create', $op );
293 $status->value->affectedObjects[] = $obj;
294 } else { // actually write the object in Swift
295 $obj->write( $params['content'] );
296 $this->purgeCDNCache( array( $obj ) );
297 }
298 } catch ( CDNNotEnabledException $e ) {
299 // CDN not enabled; nothing to see here
300 } catch ( BadContentTypeException $e ) {
301 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
302 } catch ( CloudFilesException $e ) { // some other exception?
303 $this->handleException( $e, $status, __METHOD__, $params );
304 }
305
306 return $status;
307 }
308
309 /**
310 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
311 */
312 protected function getResponseCreate( CF_Async_Op $cfOp, Status $status, array $params ) {
313 try {
314 $cfOp->getLastResponse();
315 } catch ( BadContentTypeException $e ) {
316 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
317 }
318 }
319
320 protected function doStoreInternal( array $params ) {
321 $status = Status::newGood();
322
323 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
324 if ( $dstRel === null ) {
325 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
326
327 return $status;
328 }
329
330 // (a) Check the destination container and object
331 try {
332 $dContObj = $this->getContainer( $dstCont );
333 } catch ( NoSuchContainerException $e ) {
334 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
335
336 return $status;
337 } catch ( CloudFilesException $e ) { // some other exception?
338 $this->handleException( $e, $status, __METHOD__, $params );
339
340 return $status;
341 }
342
343 // (b) Get a SHA-1 hash of the object
344 wfSuppressWarnings();
345 $sha1Hash = sha1_file( $params['src'] );
346 wfRestoreWarnings();
347 if ( $sha1Hash === false ) { // source doesn't exist?
348 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
349
350 return $status;
351 }
352 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
353
354 // (c) Actually store the object
355 try {
356 // Create a fresh CF_Object with no fields preloaded.
357 // We don't want to preserve headers, metadata, and such.
358 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
359 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
360 // The MD5 here will be checked within Swift against its own MD5.
361 $obj->set_etag( md5_file( $params['src'] ) );
362 // Use the same content type as StreamFile for security
363 $obj->content_type = $this->getContentType( $params['dst'], null, $params['src'] );
364 // Set any other custom headers if requested
365 if ( isset( $params['headers'] ) ) {
366 $obj->headers += $this->sanitizeHdrs( $params['headers'] );
367 }
368 if ( !empty( $params['async'] ) ) { // deferred
369 wfSuppressWarnings();
370 $fp = fopen( $params['src'], 'rb' );
371 wfRestoreWarnings();
372 if ( !$fp ) {
373 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
374 } else {
375 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
376 $status->value = new SwiftFileOpHandle( $this, $params, 'Store', $op );
377 $status->value->resourcesToClose[] = $fp;
378 $status->value->affectedObjects[] = $obj;
379 }
380 } else { // actually write the object in Swift
381 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
382 $this->purgeCDNCache( array( $obj ) );
383 }
384 } catch ( CDNNotEnabledException $e ) {
385 // CDN not enabled; nothing to see here
386 } catch ( BadContentTypeException $e ) {
387 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
388 } catch ( IOException $e ) {
389 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
390 } catch ( CloudFilesException $e ) { // some other exception?
391 $this->handleException( $e, $status, __METHOD__, $params );
392 }
393
394 return $status;
395 }
396
397 /**
398 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
399 */
400 protected function getResponseStore( CF_Async_Op $cfOp, Status $status, array $params ) {
401 try {
402 $cfOp->getLastResponse();
403 } catch ( BadContentTypeException $e ) {
404 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
405 } catch ( IOException $e ) {
406 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
407 }
408 }
409
410 protected function doCopyInternal( array $params ) {
411 $status = Status::newGood();
412
413 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
414 if ( $srcRel === null ) {
415 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
416
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
424 return $status;
425 }
426
427 // (a) Check the source/destination containers and destination object
428 try {
429 $sContObj = $this->getContainer( $srcCont );
430 $dContObj = $this->getContainer( $dstCont );
431 } catch ( NoSuchContainerException $e ) {
432 if ( empty( $params['ignoreMissingSource'] ) || isset( $sContObj ) ) {
433 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
434 }
435
436 return $status;
437 } catch ( CloudFilesException $e ) { // some other exception?
438 $this->handleException( $e, $status, __METHOD__, $params );
439
440 return $status;
441 }
442
443 // (b) Actually copy the file to the destination
444 try {
445 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
446 $hdrs = array(); // source file headers to override with new values
447 // Set any other custom headers if requested
448 if ( isset( $params['headers'] ) ) {
449 $hdrs += $this->sanitizeHdrs( $params['headers'] );
450 }
451 if ( !empty( $params['async'] ) ) { // deferred
452 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
453 $status->value = new SwiftFileOpHandle( $this, $params, 'Copy', $op );
454 $status->value->affectedObjects[] = $dstObj;
455 } else { // actually write the object in Swift
456 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
457 $this->purgeCDNCache( array( $dstObj ) );
458 }
459 } catch ( CDNNotEnabledException $e ) {
460 // CDN not enabled; nothing to see here
461 } catch ( NoSuchObjectException $e ) { // source object does not exist
462 if ( empty( $params['ignoreMissingSource'] ) ) {
463 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
464 }
465 } catch ( CloudFilesException $e ) { // some other exception?
466 $this->handleException( $e, $status, __METHOD__, $params );
467 }
468
469 return $status;
470 }
471
472 /**
473 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
474 */
475 protected function getResponseCopy( CF_Async_Op $cfOp, Status $status, array $params ) {
476 try {
477 $cfOp->getLastResponse();
478 } catch ( NoSuchObjectException $e ) { // source object does not exist
479 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
480 }
481 }
482
483 protected function doMoveInternal( 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
490 return $status;
491 }
492
493 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
494 if ( $dstRel === null ) {
495 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
496
497 return $status;
498 }
499
500 // (a) Check the source/destination containers and destination object
501 try {
502 $sContObj = $this->getContainer( $srcCont );
503 $dContObj = $this->getContainer( $dstCont );
504 } catch ( NoSuchContainerException $e ) {
505 if ( empty( $params['ignoreMissingSource'] ) || isset( $sContObj ) ) {
506 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
507 }
508
509 return $status;
510 } catch ( CloudFilesException $e ) { // some other exception?
511 $this->handleException( $e, $status, __METHOD__, $params );
512
513 return $status;
514 }
515
516 // (b) Actually move the file to the destination
517 try {
518 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
519 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
520 $hdrs = array(); // source file headers to override with new values
521 // Set any other custom headers if requested
522 if ( isset( $params['headers'] ) ) {
523 $hdrs += $this->sanitizeHdrs( $params['headers'] );
524 }
525 if ( !empty( $params['async'] ) ) { // deferred
526 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
527 $status->value = new SwiftFileOpHandle( $this, $params, 'Move', $op );
528 $status->value->affectedObjects[] = $srcObj;
529 $status->value->affectedObjects[] = $dstObj;
530 } else { // actually write the object in Swift
531 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
532 $this->purgeCDNCache( array( $srcObj ) );
533 $this->purgeCDNCache( array( $dstObj ) );
534 }
535 } catch ( CDNNotEnabledException $e ) {
536 // CDN not enabled; nothing to see here
537 } catch ( NoSuchObjectException $e ) { // source object does not exist
538 if ( empty( $params['ignoreMissingSource'] ) ) {
539 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
540 }
541 } catch ( CloudFilesException $e ) { // some other exception?
542 $this->handleException( $e, $status, __METHOD__, $params );
543 }
544
545 return $status;
546 }
547
548 /**
549 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
550 */
551 protected function getResponseMove( CF_Async_Op $cfOp, Status $status, array $params ) {
552 try {
553 $cfOp->getLastResponse();
554 } catch ( NoSuchObjectException $e ) { // source object does not exist
555 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
556 }
557 }
558
559 protected function doDeleteInternal( array $params ) {
560 $status = Status::newGood();
561
562 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
563 if ( $srcRel === null ) {
564 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
565
566 return $status;
567 }
568
569 try {
570 $sContObj = $this->getContainer( $srcCont );
571 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
572 if ( !empty( $params['async'] ) ) { // deferred
573 $op = $sContObj->delete_object_async( $srcRel );
574 $status->value = new SwiftFileOpHandle( $this, $params, 'Delete', $op );
575 $status->value->affectedObjects[] = $srcObj;
576 } else { // actually write the object in Swift
577 $sContObj->delete_object( $srcRel );
578 $this->purgeCDNCache( array( $srcObj ) );
579 }
580 } catch ( CDNNotEnabledException $e ) {
581 // CDN not enabled; nothing to see here
582 } catch ( NoSuchContainerException $e ) {
583 if ( empty( $params['ignoreMissingSource'] ) ) {
584 $status->fatal( 'backend-fail-delete', $params['src'] );
585 }
586 } catch ( NoSuchObjectException $e ) {
587 if ( empty( $params['ignoreMissingSource'] ) ) {
588 $status->fatal( 'backend-fail-delete', $params['src'] );
589 }
590 } catch ( CloudFilesException $e ) { // some other exception?
591 $this->handleException( $e, $status, __METHOD__, $params );
592 }
593
594 return $status;
595 }
596
597 /**
598 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
599 */
600 protected function getResponseDelete( CF_Async_Op $cfOp, Status $status, array $params ) {
601 try {
602 $cfOp->getLastResponse();
603 } catch ( NoSuchContainerException $e ) {
604 $status->fatal( 'backend-fail-delete', $params['src'] );
605 } catch ( NoSuchObjectException $e ) {
606 if ( empty( $params['ignoreMissingSource'] ) ) {
607 $status->fatal( 'backend-fail-delete', $params['src'] );
608 }
609 }
610 }
611
612 protected function doDescribeInternal( array $params ) {
613 $status = Status::newGood();
614
615 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
616 if ( $srcRel === null ) {
617 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
618
619 return $status;
620 }
621
622 try {
623 $sContObj = $this->getContainer( $srcCont );
624 // Get the latest version of the current metadata
625 $srcObj = $sContObj->get_object( $srcRel,
626 $this->headersFromParams( array( 'latest' => true ) ) );
627 // Merge in the metadata updates...
628 if ( isset( $params['headers'] ) ) {
629 $srcObj->headers = $this->sanitizeHdrs( $params['headers'] ) + $srcObj->headers;
630 }
631 $srcObj->sync_metadata(); // save to Swift
632 $this->purgeCDNCache( array( $srcObj ) );
633 } catch ( CDNNotEnabledException $e ) {
634 // CDN not enabled; nothing to see here
635 } catch ( NoSuchContainerException $e ) {
636 $status->fatal( 'backend-fail-describe', $params['src'] );
637 } catch ( NoSuchObjectException $e ) {
638 $status->fatal( 'backend-fail-describe', $params['src'] );
639 } catch ( CloudFilesException $e ) { // some other exception?
640 $this->handleException( $e, $status, __METHOD__, $params );
641 }
642
643 return $status;
644 }
645
646 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
647 $status = Status::newGood();
648
649 // (a) Check if container already exists
650 try {
651 $this->getContainer( $fullCont );
652
653 // NoSuchContainerException not thrown: container must exist
654 return $status; // already exists
655 } catch ( NoSuchContainerException $e ) {
656 // NoSuchContainerException thrown: container does not exist
657 } catch ( CloudFilesException $e ) { // some other exception?
658 $this->handleException( $e, $status, __METHOD__, $params );
659
660 return $status;
661 }
662
663 // (b) Create container as needed
664 try {
665 $contObj = $this->createContainer( $fullCont );
666 if ( !empty( $params['noAccess'] ) ) {
667 // Make container private to end-users...
668 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
669 } else {
670 // Make container public to end-users...
671 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
672 }
673 if ( $this->swiftUseCDN ) { // Rackspace style CDN
674 $contObj->make_public( $this->swiftCDNExpiry );
675 }
676 } catch ( CDNNotEnabledException $e ) {
677 // CDN not enabled; nothing to see here
678 } catch ( CloudFilesException $e ) { // some other exception?
679 $this->handleException( $e, $status, __METHOD__, $params );
680
681 return $status;
682 }
683
684 return $status;
685 }
686
687 /**
688 * @see FileBackendStore::doSecureInternal()
689 * @param string $fullCont
690 * @param string $dir
691 * @param array $params
692 * @return Status
693 */
694 protected function doSecureInternal( $fullCont, $dir, array $params ) {
695 $status = Status::newGood();
696 if ( empty( $params['noAccess'] ) ) {
697 return $status; // nothing to do
698 }
699
700 // Restrict container from end-users...
701 try {
702 // doPrepareInternal() should have been called,
703 // so the Swift container should already exist...
704 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
705 // NoSuchContainerException not thrown: container must exist
706
707 // Make container private to end-users...
708 $status->merge( $this->setContainerAccess(
709 $contObj,
710 array( $this->auth->username ), // read
711 array( $this->auth->username ) // write
712 ) );
713 if ( $this->swiftUseCDN && $contObj->is_public() ) { // Rackspace style CDN
714 $contObj->make_private();
715 }
716 } catch ( CDNNotEnabledException $e ) {
717 // CDN not enabled; nothing to see here
718 } catch ( CloudFilesException $e ) { // some other exception?
719 $this->handleException( $e, $status, __METHOD__, $params );
720 }
721
722 return $status;
723 }
724
725 /**
726 * @see FileBackendStore::doPublishInternal()
727 * @param string $fullCont
728 * @param string $dir
729 * @param array $params
730 * @return Status
731 */
732 protected function doPublishInternal( $fullCont, $dir, array $params ) {
733 $status = Status::newGood();
734
735 // Unrestrict container from end-users...
736 try {
737 // doPrepareInternal() should have been called,
738 // so the Swift container should already exist...
739 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
740 // NoSuchContainerException not thrown: container must exist
741
742 // Make container public to end-users...
743 if ( $this->swiftAnonUser != '' ) {
744 $status->merge( $this->setContainerAccess(
745 $contObj,
746 array( $this->auth->username, $this->swiftAnonUser ), // read
747 array( $this->auth->username, $this->swiftAnonUser ) // write
748 ) );
749 } else {
750 $status->merge( $this->setContainerAccess(
751 $contObj,
752 array( $this->auth->username, '.r:*' ), // read
753 array( $this->auth->username ) // write
754 ) );
755 }
756 if ( $this->swiftUseCDN && !$contObj->is_public() ) { // Rackspace style CDN
757 $contObj->make_public();
758 }
759 } catch ( CDNNotEnabledException $e ) {
760 // CDN not enabled; nothing to see here
761 } catch ( CloudFilesException $e ) { // some other exception?
762 $this->handleException( $e, $status, __METHOD__, $params );
763 }
764
765 return $status;
766 }
767
768 protected function doCleanInternal( $fullCont, $dir, array $params ) {
769 $status = Status::newGood();
770
771 // Only containers themselves can be removed, all else is virtual
772 if ( $dir != '' ) {
773 return $status; // nothing to do
774 }
775
776 // (a) Check the container
777 try {
778 $contObj = $this->getContainer( $fullCont, true );
779 } catch ( NoSuchContainerException $e ) {
780 return $status; // ok, nothing to do
781 } catch ( CloudFilesException $e ) { // some other exception?
782 $this->handleException( $e, $status, __METHOD__, $params );
783
784 return $status;
785 }
786
787 // (b) Delete the container if empty
788 if ( $contObj->object_count == 0 ) {
789 try {
790 $this->deleteContainer( $fullCont );
791 } catch ( NoSuchContainerException $e ) {
792 return $status; // race?
793 } catch ( NonEmptyContainerException $e ) {
794 return $status; // race? consistency delay?
795 } catch ( CloudFilesException $e ) { // some other exception?
796 $this->handleException( $e, $status, __METHOD__, $params );
797
798 return $status;
799 }
800 }
801
802 return $status;
803 }
804
805 protected function doGetFileStat( array $params ) {
806 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
807 if ( $srcRel === null ) {
808 return false; // invalid storage path
809 }
810
811 $stat = false;
812 try {
813 $contObj = $this->getContainer( $srcCont );
814 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
815 $this->addMissingMetadata( $srcObj, $params['src'] );
816 $stat = array(
817 // Convert various random Swift dates to TS_MW
818 'mtime' => $this->convertSwiftDate( $srcObj->last_modified, TS_MW ),
819 'size' => (int)$srcObj->content_length,
820 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
821 );
822 } catch ( NoSuchContainerException $e ) {
823 } catch ( NoSuchObjectException $e ) {
824 } catch ( CloudFilesException $e ) { // some other exception?
825 $stat = null;
826 $this->handleException( $e, null, __METHOD__, $params );
827 }
828
829 return $stat;
830 }
831
832 /**
833 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
834 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
835 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
836 *
837 * @param string $ts
838 * @param int $format Output format (TS_* constant)
839 * @return string
840 * @throws MWException
841 */
842 protected function convertSwiftDate( $ts, $format = TS_MW ) {
843 $timestamp = new MWTimestamp( $ts );
844
845 return $timestamp->getTimestamp( $format );
846 }
847
848 /**
849 * Fill in any missing object metadata and save it to Swift
850 *
851 * @param CF_Object $obj
852 * @param string $path Storage path to object
853 * @return bool Success
854 * @throws Exception cloudfiles exceptions
855 */
856 protected function addMissingMetadata( CF_Object $obj, $path ) {
857 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
858 return true; // nothing to do
859 }
860 wfProfileIn( __METHOD__ );
861 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING );
862 $status = Status::newGood();
863 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
864 if ( $status->isOK() ) {
865 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
866 if ( $tmpFile ) {
867 $hash = $tmpFile->getSha1Base36();
868 if ( $hash !== false ) {
869 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
870 $obj->sync_metadata(); // save to Swift
871 wfProfileOut( __METHOD__ );
872
873 return true; // success
874 }
875 }
876 }
877 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING );
878 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
879 wfProfileOut( __METHOD__ );
880
881 return false; // failed
882 }
883
884 protected function doGetFileContentsMulti( array $params ) {
885 $contents = array();
886
887 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
888 // Blindly create tmp files and stream to them, catching any exception if the file does
889 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
890 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
891 $cfOps = array(); // (path => CF_Async_Op)
892
893 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
894 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
895 if ( $srcRel === null ) {
896 $contents[$path] = false;
897 continue;
898 }
899 $data = false;
900 try {
901 $sContObj = $this->getContainer( $srcCont );
902 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
903 // Create a new temporary memory file...
904 $handle = fopen( 'php://temp', 'wb' );
905 if ( $handle ) {
906 $headers = $this->headersFromParams( $params );
907 if ( count( $pathBatch ) > 1 ) {
908 $cfOps[$path] = $obj->stream_async( $handle, $headers );
909 $cfOps[$path]->_file_handle = $handle; // close this later
910 } else {
911 $obj->stream( $handle, $headers );
912 rewind( $handle ); // start from the beginning
913 $data = stream_get_contents( $handle );
914 fclose( $handle );
915 }
916 } else {
917 $data = false;
918 }
919 } catch ( NoSuchContainerException $e ) {
920 $data = false;
921 } catch ( NoSuchObjectException $e ) {
922 $data = false;
923 } catch ( CloudFilesException $e ) { // some other exception?
924 $data = false;
925 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
926 }
927 $contents[$path] = $data;
928 }
929
930 $batch = new CF_Async_Op_Batch( $cfOps );
931 $cfOps = $batch->execute();
932 foreach ( $cfOps as $path => $cfOp ) {
933 try {
934 $cfOp->getLastResponse();
935 rewind( $cfOp->_file_handle ); // start from the beginning
936 $contents[$path] = stream_get_contents( $cfOp->_file_handle );
937 } catch ( NoSuchContainerException $e ) {
938 $contents[$path] = false;
939 } catch ( NoSuchObjectException $e ) {
940 $contents[$path] = false;
941 } catch ( CloudFilesException $e ) { // some other exception?
942 $contents[$path] = false;
943 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
944 }
945 fclose( $cfOp->_file_handle ); // close open handle
946 }
947 }
948
949 return $contents;
950 }
951
952 /**
953 * @see FileBackendStore::doDirectoryExists()
954 * @param string $fullCont
955 * @param string $dir
956 * @param array $params
957 * @return bool|null
958 */
959 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
960 try {
961 $container = $this->getContainer( $fullCont );
962 $prefix = ( $dir == '' ) ? null : "{$dir}/";
963
964 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
965 } catch ( NoSuchContainerException $e ) {
966 return false;
967 } catch ( CloudFilesException $e ) { // some other exception?
968 $this->handleException( $e, null, __METHOD__,
969 array( 'cont' => $fullCont, 'dir' => $dir ) );
970 }
971
972 return null; // error
973 }
974
975 /**
976 * @see FileBackendStore::getDirectoryListInternal()
977 * @param string $fullCont
978 * @param string $dir
979 * @param array $params
980 * @return SwiftFileBackendDirList
981 */
982 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
983 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
984 }
985
986 /**
987 * @see FileBackendStore::getFileListInternal()
988 * @param string $fullCont
989 * @param string $dir
990 * @param array $params
991 * @return SwiftFileBackendFileList
992 */
993 public function getFileListInternal( $fullCont, $dir, array $params ) {
994 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
995 }
996
997 /**
998 * Do not call this function outside of SwiftFileBackendFileList
999 *
1000 * @param string $fullCont Resolved container name
1001 * @param string $dir Resolved storage directory with no trailing slash
1002 * @param string|null $after Resolved container relative path to list items after
1003 * @param int $limit Max number of items to list
1004 * @param array $params Parameters for getDirectoryList()
1005 * @return array List of container relative resolved paths of directories directly under $dir
1006 * @throws FileBackendError
1007 */
1008 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1009 $dirs = array();
1010 if ( $after === INF ) {
1011 return $dirs; // nothing more
1012 }
1013
1014 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
1015 try {
1016 $container = $this->getContainer( $fullCont );
1017 $prefix = ( $dir == '' ) ? null : "{$dir}/";
1018 // Non-recursive: only list dirs right under $dir
1019 if ( !empty( $params['topOnly'] ) ) {
1020 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1021 foreach ( $objects as $object ) { // files and directories
1022 if ( substr( $object, -1 ) === '/' ) {
1023 $dirs[] = $object; // directories end in '/'
1024 }
1025 }
1026 // Recursive: list all dirs under $dir and its subdirs
1027 } else {
1028 // Get directory from last item of prior page
1029 $lastDir = $this->getParentDir( $after ); // must be first page
1030 $objects = $container->list_objects( $limit, $after, $prefix );
1031 foreach ( $objects as $object ) { // files
1032 $objectDir = $this->getParentDir( $object ); // directory of object
1033 if ( $objectDir !== false && $objectDir !== $dir ) {
1034 // Swift stores paths in UTF-8, using binary sorting.
1035 // See function "create_container_table" in common/db.py.
1036 // If a directory is not "greater" than the last one,
1037 // then it was already listed by the calling iterator.
1038 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1039 $pDir = $objectDir;
1040 do { // add dir and all its parent dirs
1041 $dirs[] = "{$pDir}/";
1042 $pDir = $this->getParentDir( $pDir );
1043 } while ( $pDir !== false // sanity
1044 && strcmp( $pDir, $lastDir ) > 0 // not done already
1045 && strlen( $pDir ) > strlen( $dir ) // within $dir
1046 );
1047 }
1048 $lastDir = $objectDir;
1049 }
1050 }
1051 }
1052 // Page on the unfiltered directory listing (what is returned may be filtered)
1053 if ( count( $objects ) < $limit ) {
1054 $after = INF; // avoid a second RTT
1055 } else {
1056 $after = end( $objects ); // update last item
1057 }
1058 } catch ( NoSuchContainerException $e ) {
1059 } catch ( CloudFilesException $e ) { // some other exception?
1060 $this->handleException( $e, null, __METHOD__,
1061 array( 'cont' => $fullCont, 'dir' => $dir ) );
1062 throw new FileBackendError( "Got " . get_class( $e ) . " exception." );
1063 }
1064
1065 return $dirs;
1066 }
1067
1068 protected function getParentDir( $path ) {
1069 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
1070 }
1071
1072 /**
1073 * Do not call this function outside of SwiftFileBackendFileList
1074 *
1075 * @param string $fullCont Resolved container name
1076 * @param string $dir Resolved storage directory with no trailing slash
1077 * @param string|null $after Resolved container relative path of file to list items after
1078 * @param int $limit Max number of items to list
1079 * @param array $params Parameters for getDirectoryList()
1080 * @return array List of resolved container relative paths of files under $dir
1081 * @throws FileBackendError
1082 */
1083 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1084 $files = array(); // list of (path, stat array or null) entries
1085 if ( $after === INF ) {
1086 return $files; // nothing more
1087 }
1088
1089 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
1090 try {
1091 $container = $this->getContainer( $fullCont );
1092 $prefix = ( $dir == '' ) ? null : "{$dir}/";
1093
1094 // $objects will contain a list of unfiltered names or CF_Object items
1095 // Non-recursive: only list files right under $dir
1096 if ( !empty( $params['topOnly'] ) ) {
1097 if ( !empty( $params['adviseStat'] ) ) {
1098 // Note: get_objects() does not include directories
1099 $objects = $container->get_objects( $limit, $after, $prefix, null, '/' );
1100 } else {
1101 // Note: list_objects() includes directories here
1102 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1103 }
1104 $files = $this->buildFileObjectListing( $params, $dir, $objects );
1105 // Recursive: list all files under $dir and its subdirs
1106 } else {
1107 // Note: get_objects()/list_objects() here only return file objects
1108 if ( !empty( $params['adviseStat'] ) ) {
1109 $objects = $container->get_objects( $limit, $after, $prefix );
1110 } else {
1111 $objects = $container->list_objects( $limit, $after, $prefix );
1112 }
1113 $files = $this->buildFileObjectListing( $params, $dir, $objects );
1114 }
1115 // Page on the unfiltered object listing (what is returned may be filtered)
1116 if ( count( $objects ) < $limit ) {
1117 $after = INF; // avoid a second RTT
1118 } else {
1119 $after = end( $objects ); // update last item
1120 $after = is_object( $after ) ? $after->name : $after;
1121 }
1122 } catch ( NoSuchContainerException $e ) {
1123 } catch ( CloudFilesException $e ) { // some other exception?
1124 $this->handleException( $e, null, __METHOD__,
1125 array( 'cont' => $fullCont, 'dir' => $dir ) );
1126 throw new FileBackendError( "Got " . get_class( $e ) . " exception." );
1127 }
1128
1129 return $files;
1130 }
1131
1132 /**
1133 * Build a list of file objects, filtering out any directories
1134 * and extracting any stat info if provided in $objects (for CF_Objects)
1135 *
1136 * @param array $params Parameters for getDirectoryList()
1137 * @param string $dir Resolved container directory path
1138 * @param array $objects List of CF_Object items or object names
1139 * @return array List of (names,stat array or null) entries
1140 */
1141 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1142 $names = array();
1143 foreach ( $objects as $object ) {
1144 if ( is_object( $object ) ) {
1145 $stat = array(
1146 // Convert various random Swift dates to TS_MW
1147 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
1148 'size' => (int)$object->content_length,
1149 'latest' => false // eventually consistent
1150 );
1151 $names[] = array( $object->name, $stat );
1152 } elseif ( substr( $object, -1 ) !== '/' ) {
1153 // Omit directories, which end in '/' in listings
1154 $names[] = array( $object, null );
1155 }
1156 }
1157
1158 return $names;
1159 }
1160
1161 /**
1162 * Do not call this function outside of SwiftFileBackendFileList
1163 *
1164 * @param string $path Storage path
1165 * @param array $val Stat value
1166 */
1167 public function loadListingStatInternal( $path, array $val ) {
1168 $this->cheapCache->set( $path, 'stat', $val );
1169 }
1170
1171 protected function doGetFileSha1base36( array $params ) {
1172 $stat = $this->getFileStat( $params );
1173 if ( $stat ) {
1174 if ( !isset( $stat['sha1'] ) ) {
1175 // Stat entries filled by file listings don't include SHA1
1176 $this->clearCache( array( $params['src'] ) );
1177 $stat = $this->getFileStat( $params );
1178 }
1179
1180 return $stat['sha1'];
1181 } else {
1182 return false;
1183 }
1184 }
1185
1186 protected function doStreamFile( array $params ) {
1187 $status = Status::newGood();
1188
1189 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1190 if ( $srcRel === null ) {
1191 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1192 }
1193
1194 try {
1195 $cont = $this->getContainer( $srcCont );
1196 } catch ( NoSuchContainerException $e ) {
1197 $status->fatal( 'backend-fail-stream', $params['src'] );
1198
1199 return $status;
1200 } catch ( CloudFilesException $e ) { // some other exception?
1201 $this->handleException( $e, $status, __METHOD__, $params );
1202
1203 return $status;
1204 }
1205
1206 try {
1207 $output = fopen( 'php://output', 'wb' );
1208 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1209 $obj->stream( $output, $this->headersFromParams( $params ) );
1210 } catch ( NoSuchObjectException $e ) {
1211 $status->fatal( 'backend-fail-stream', $params['src'] );
1212 } catch ( CloudFilesException $e ) { // some other exception?
1213 $this->handleException( $e, $status, __METHOD__, $params );
1214 }
1215
1216 return $status;
1217 }
1218
1219 protected function doGetLocalCopyMulti( array $params ) {
1220 $tmpFiles = array();
1221
1222 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1223 // Blindly create tmp files and stream to them, catching any exception if the file does
1224 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1225 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1226 $cfOps = array(); // (path => CF_Async_Op)
1227
1228 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1229 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1230 if ( $srcRel === null ) {
1231 $tmpFiles[$path] = null;
1232 continue;
1233 }
1234 $tmpFile = null;
1235 try {
1236 $sContObj = $this->getContainer( $srcCont );
1237 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1238 // Get source file extension
1239 $ext = FileBackend::extensionFromPath( $path );
1240 // Create a new temporary file...
1241 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1242 if ( $tmpFile ) {
1243 $handle = fopen( $tmpFile->getPath(), 'wb' );
1244 if ( $handle ) {
1245 $headers = $this->headersFromParams( $params );
1246 if ( count( $pathBatch ) > 1 ) {
1247 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1248 $cfOps[$path]->_file_handle = $handle; // close this later
1249 } else {
1250 $obj->stream( $handle, $headers );
1251 fclose( $handle );
1252 }
1253 } else {
1254 $tmpFile = null;
1255 }
1256 }
1257 } catch ( NoSuchContainerException $e ) {
1258 $tmpFile = null;
1259 } catch ( NoSuchObjectException $e ) {
1260 $tmpFile = null;
1261 } catch ( CloudFilesException $e ) { // some other exception?
1262 $tmpFile = null;
1263 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1264 }
1265 $tmpFiles[$path] = $tmpFile;
1266 }
1267
1268 $batch = new CF_Async_Op_Batch( $cfOps );
1269 $cfOps = $batch->execute();
1270 foreach ( $cfOps as $path => $cfOp ) {
1271 try {
1272 $cfOp->getLastResponse();
1273 } catch ( NoSuchContainerException $e ) {
1274 $tmpFiles[$path] = null;
1275 } catch ( NoSuchObjectException $e ) {
1276 $tmpFiles[$path] = null;
1277 } catch ( CloudFilesException $e ) { // some other exception?
1278 $tmpFiles[$path] = null;
1279 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1280 }
1281 fclose( $cfOp->_file_handle ); // close open handle
1282 }
1283 }
1284
1285 return $tmpFiles;
1286 }
1287
1288 public function getFileHttpUrl( array $params ) {
1289 if ( $this->swiftTempUrlKey != '' ||
1290 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1291 ) {
1292 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1293 if ( $srcRel === null ) {
1294 return null; // invalid path
1295 }
1296 try {
1297 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1298 $sContObj = $this->getContainer( $srcCont );
1299 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1300 if ( $this->swiftTempUrlKey != '' ) {
1301 return $obj->get_temp_url( $this->swiftTempUrlKey, $ttl, "GET" );
1302 } else { // give S3 API URL for rgw
1303 $expires = time() + $ttl;
1304 // Path for signature starts with the bucket
1305 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1306 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1307 // Calculate the hash
1308 $signature = base64_encode( hash_hmac(
1309 'sha1',
1310 "GET\n\n\n{$expires}\n{$spath}",
1311 $this->rgwS3SecretKey,
1312 true // raw
1313 ) );
1314
1315 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1316 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1317 return wfAppendQuery(
1318 str_replace( '/swift/v1', '', // S3 API is the rgw default
1319 $sContObj->cfs_http->getStorageUrl() . $spath ),
1320 array(
1321 'Signature' => $signature,
1322 'Expires' => $expires,
1323 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1324 );
1325 }
1326 } catch ( NoSuchContainerException $e ) {
1327 } catch ( CloudFilesException $e ) { // some other exception?
1328 $this->handleException( $e, null, __METHOD__, $params );
1329 }
1330 }
1331
1332 return null;
1333 }
1334
1335 protected function directoriesAreVirtual() {
1336 return true;
1337 }
1338
1339 /**
1340 * Get headers to send to Swift when reading a file based
1341 * on a FileBackend params array, e.g. that of getLocalCopy().
1342 * $params is currently only checked for a 'latest' flag.
1343 *
1344 * @param array $params
1345 * @return array
1346 */
1347 protected function headersFromParams( array $params ) {
1348 $hdrs = array();
1349 if ( !empty( $params['latest'] ) ) {
1350 $hdrs[] = 'X-Newest: true';
1351 }
1352
1353 return $hdrs;
1354 }
1355
1356 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1357 $statuses = array();
1358
1359 $cfOps = array(); // list of CF_Async_Op objects
1360 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1361 $cfOps[$index] = $fileOpHandle->cfOp;
1362 }
1363 $batch = new CF_Async_Op_Batch( $cfOps );
1364
1365 $cfOps = $batch->execute();
1366 foreach ( $cfOps as $index => $cfOp ) {
1367 $status = Status::newGood();
1368 $function = 'getResponse' . $fileOpHandles[$index]->call;
1369 try { // catch exceptions; update status
1370 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1371 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1372 } catch ( CloudFilesException $e ) { // some other exception?
1373 $this->handleException( $e, $status,
1374 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1375 }
1376 $statuses[$index] = $status;
1377 }
1378
1379 return $statuses;
1380 }
1381
1382 /**
1383 * Set read/write permissions for a Swift container.
1384 *
1385 * @see http://swift.openstack.org/misc.html#acls
1386 *
1387 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1388 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1389 *
1390 * @param CF_Container $contObj Swift container
1391 * @param array $readGrps List of the possible criteria for a request to have
1392 * access to read a container. Each item is one of the following formats:
1393 * - account:user : Grants access if the request is by the given user
1394 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1395 * matches the expression and the request is not for a listing.
1396 * Setting this to '*' effectively makes a container public.
1397 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1398 * matches the expression and the request is for a listing.
1399 * @param array $writeGrps A list of the possible criteria for a request to have
1400 * access to write to a container. Each item is of the following format:
1401 * - account:user : Grants access if the request is by the given user
1402 * @return Status
1403 */
1404 protected function setContainerAccess(
1405 CF_Container $contObj, array $readGrps, array $writeGrps
1406 ) {
1407 $creds = $contObj->cfs_auth->export_credentials();
1408
1409 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1410
1411 // Note: 10 second timeout consistent with php-cloudfiles
1412 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1413 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1414 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1415 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1416
1417 return $req->execute(); // should return 204
1418 }
1419
1420 /**
1421 * Purge the CDN cache of affected objects if CDN caching is enabled.
1422 * This is for Rackspace/Akamai CDNs.
1423 *
1424 * @param array $objects List of CF_Object items
1425 */
1426 public function purgeCDNCache( array $objects ) {
1427 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1428 foreach ( $objects as $object ) {
1429 try {
1430 $object->purge_from_cdn();
1431 } catch ( CDNNotEnabledException $e ) {
1432 // CDN not enabled; nothing to see here
1433 } catch ( CloudFilesException $e ) {
1434 $this->handleException( $e, null, __METHOD__,
1435 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1436 }
1437 }
1438 }
1439 }
1440
1441 /**
1442 * Get an authenticated connection handle to the Swift proxy
1443 *
1444 * @throws CloudFilesException
1445 * @throws CloudFilesException|Exception
1446 * @return CF_Connection|bool False on failure
1447 */
1448 protected function getConnection() {
1449 if ( $this->connException instanceof CloudFilesException ) {
1450 if ( ( time() - $this->connErrorTime ) < 60 ) {
1451 throw $this->connException; // failed last attempt; don't bother
1452 } else { // actually retry this time
1453 $this->connException = null;
1454 $this->connErrorTime = 0;
1455 }
1456 }
1457 // Session keys expire after a while, so we renew them periodically
1458 $reAuth = ( ( time() - $this->sessionStarted ) > $this->authTTL );
1459 // Authenticate with proxy and get a session key...
1460 if ( !$this->conn || $reAuth ) {
1461 $this->sessionStarted = 0;
1462 $this->connContainerCache->clear();
1463 $cacheKey = $this->getCredsCacheKey( $this->auth->username );
1464 $creds = $this->srvCache->get( $cacheKey ); // credentials
1465 if ( is_array( $creds ) ) { // cache hit
1466 $this->auth->load_cached_credentials(
1467 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1468 $this->sessionStarted = time() - ceil( $this->authTTL / 2 ); // skew for worst case
1469 } else { // cache miss
1470 try {
1471 $this->auth->authenticate();
1472 $creds = $this->auth->export_credentials();
1473 $this->srvCache->add( $cacheKey, $creds, ceil( $this->authTTL / 2 ) ); // cache
1474 $this->sessionStarted = time();
1475 } catch ( CloudFilesException $e ) {
1476 $this->connException = $e; // don't keep re-trying
1477 $this->connErrorTime = time();
1478 throw $e; // throw it back
1479 }
1480 }
1481 if ( $this->conn ) { // re-authorizing?
1482 $this->conn->close(); // close active cURL handles in CF_Http object
1483 }
1484 $this->conn = new CF_Connection( $this->auth );
1485 }
1486
1487 return $this->conn;
1488 }
1489
1490 /**
1491 * Close the connection to the Swift proxy
1492 */
1493 protected function closeConnection() {
1494 if ( $this->conn ) {
1495 $this->conn->close(); // close active cURL handles in CF_Http object
1496 $this->conn = null;
1497 $this->sessionStarted = 0;
1498 $this->connContainerCache->clear();
1499 }
1500 }
1501
1502 /**
1503 * Get the cache key for a container
1504 *
1505 * @param string $username
1506 * @return string
1507 */
1508 private function getCredsCacheKey( $username ) {
1509 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1510 }
1511
1512 /**
1513 * Get a Swift container object, possibly from process cache.
1514 * Use $reCache if the file count or byte count is needed.
1515 *
1516 * @param string $container Container name
1517 * @param bool $bypassCache Bypass all caches and load from Swift
1518 * @return CF_Container
1519 * @throws CloudFilesException
1520 */
1521 protected function getContainer( $container, $bypassCache = false ) {
1522 $conn = $this->getConnection(); // Swift proxy connection
1523 if ( $bypassCache ) { // purge cache
1524 $this->connContainerCache->clear( $container );
1525 } elseif ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1526 $this->primeContainerCache( array( $container ) ); // check persistent cache
1527 }
1528 if ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1529 $contObj = $conn->get_container( $container );
1530 // NoSuchContainerException not thrown: container must exist
1531 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache it
1532 if ( !$bypassCache ) {
1533 $this->setContainerCache( $container, // update persistent cache
1534 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1535 );
1536 }
1537 }
1538
1539 return $this->connContainerCache->get( $container, 'obj' );
1540 }
1541
1542 /**
1543 * Create a Swift container
1544 *
1545 * @param string $container Container name
1546 * @return CF_Container
1547 * @throws CloudFilesException
1548 */
1549 protected function createContainer( $container ) {
1550 $conn = $this->getConnection(); // Swift proxy connection
1551 $contObj = $conn->create_container( $container );
1552 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache
1553 return $contObj;
1554 }
1555
1556 /**
1557 * Delete a Swift container
1558 *
1559 * @param string $container Container name
1560 * @throws CloudFilesException
1561 */
1562 protected function deleteContainer( $container ) {
1563 $conn = $this->getConnection(); // Swift proxy connection
1564 $this->connContainerCache->clear( $container ); // purge
1565 $conn->delete_container( $container );
1566 }
1567
1568 protected function doPrimeContainerCache( array $containerInfo ) {
1569 try {
1570 $conn = $this->getConnection(); // Swift proxy connection
1571 foreach ( $containerInfo as $container => $info ) {
1572 $contObj = new CF_Container( $conn->cfs_auth, $conn->cfs_http,
1573 $container, $info['count'], $info['bytes'] );
1574 $this->connContainerCache->set( $container, 'obj', $contObj );
1575 }
1576 } catch ( CloudFilesException $e ) { // some other exception?
1577 $this->handleException( $e, null, __METHOD__, array() );
1578 }
1579 }
1580
1581 /**
1582 * Log an unexpected exception for this backend.
1583 * This also sets the Status object to have a fatal error.
1584 *
1585 * @param Exception $e
1586 * @param Status $status null
1587 * @param string $func
1588 * @param array $params
1589 */
1590 protected function handleException( Exception $e, $status, $func, array $params ) {
1591 if ( $status instanceof Status ) {
1592 if ( $e instanceof AuthenticationException ) {
1593 $status->fatal( 'backend-fail-connect', $this->name );
1594 } else {
1595 $status->fatal( 'backend-fail-internal', $this->name );
1596 }
1597 }
1598 if ( $e->getMessage() ) {
1599 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1600 }
1601 if ( $e instanceof InvalidResponseException ) { // possibly a stale token
1602 $this->srvCache->delete( $this->getCredsCacheKey( $this->auth->username ) );
1603 $this->closeConnection(); // force a re-connect and re-auth next time
1604 }
1605 wfDebugLog( 'SwiftBackend',
1606 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1607 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1608 );
1609 }
1610 }
1611
1612 /**
1613 * @see FileBackendStoreOpHandle
1614 */
1615 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1616 /** @var CF_Async_Op */
1617 public $cfOp;
1618
1619 /** @var array */
1620 public $affectedObjects = array();
1621
1622 /**
1623 * @param SwiftFileBackend $backend
1624 * @param array $params
1625 * @param string $call
1626 * @param CF_Async_Op $cfOp
1627 */
1628 public function __construct(
1629 SwiftFileBackend $backend, array $params, $call, CF_Async_Op $cfOp
1630 ) {
1631 $this->backend = $backend;
1632 $this->params = $params;
1633 $this->call = $call;
1634 $this->cfOp = $cfOp;
1635 }
1636 }
1637
1638 /**
1639 * SwiftFileBackend helper class to page through listings.
1640 * Swift also has a listing limit of 10,000 objects for sanity.
1641 * Do not use this class from places outside SwiftFileBackend.
1642 *
1643 * @ingroup FileBackend
1644 */
1645 abstract class SwiftFileBackendList implements Iterator {
1646 /** @var array List of path or (path,stat array) entries */
1647 protected $bufferIter = array();
1648
1649 /** @var string List items *after* this path */
1650 protected $bufferAfter = null;
1651
1652 /** @var int */
1653 protected $pos = 0;
1654
1655 /** @var array */
1656 protected $params = array();
1657
1658 /** @var SwiftFileBackend */
1659 protected $backend;
1660
1661 /** @var string Container name */
1662 protected $container;
1663
1664 /** @var string Storage directory */
1665 protected $dir;
1666
1667 /** @var int */
1668 protected $suffixStart;
1669
1670 const PAGE_SIZE = 9000; // file listing buffer size
1671
1672 /**
1673 * @param SwiftFileBackend $backend
1674 * @param string $fullCont Resolved container name
1675 * @param string $dir Resolved directory relative to container
1676 * @param array $params
1677 */
1678 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1679 $this->backend = $backend;
1680 $this->container = $fullCont;
1681 $this->dir = $dir;
1682 if ( substr( $this->dir, -1 ) === '/' ) {
1683 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1684 }
1685 if ( $this->dir == '' ) { // whole container
1686 $this->suffixStart = 0;
1687 } else { // dir within container
1688 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1689 }
1690 $this->params = $params;
1691 }
1692
1693 /**
1694 * @see Iterator::key()
1695 * @return int
1696 */
1697 public function key() {
1698 return $this->pos;
1699 }
1700
1701 /**
1702 * @see Iterator::next()
1703 */
1704 public function next() {
1705 // Advance to the next file in the page
1706 next( $this->bufferIter );
1707 ++$this->pos;
1708 // Check if there are no files left in this page and
1709 // advance to the next page if this page was not empty.
1710 if ( !$this->valid() && count( $this->bufferIter ) ) {
1711 $this->bufferIter = $this->pageFromList(
1712 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1713 ); // updates $this->bufferAfter
1714 }
1715 }
1716
1717 /**
1718 * @see Iterator::rewind()
1719 */
1720 public function rewind() {
1721 $this->pos = 0;
1722 $this->bufferAfter = null;
1723 $this->bufferIter = $this->pageFromList(
1724 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1725 ); // updates $this->bufferAfter
1726 }
1727
1728 /**
1729 * @see Iterator::valid()
1730 * @return bool
1731 */
1732 public function valid() {
1733 if ( $this->bufferIter === null ) {
1734 return false; // some failure?
1735 } else {
1736 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1737 }
1738 }
1739
1740 /**
1741 * Get the given list portion (page)
1742 *
1743 * @param string $container Resolved container name
1744 * @param string $dir Resolved path relative to container
1745 * @param string $after null
1746 * @param int $limit
1747 * @param array $params
1748 * @return Traversable|array
1749 */
1750 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1751 }
1752
1753 /**
1754 * Iterator for listing directories
1755 */
1756 class SwiftFileBackendDirList extends SwiftFileBackendList {
1757 /**
1758 * @see Iterator::current()
1759 * @return string|bool String (relative path) or false
1760 */
1761 public function current() {
1762 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1763 }
1764
1765 /**
1766 * @see SwiftFileBackendList::pageFromList()
1767 * @param string $container
1768 * @param string $dir
1769 * @param string $after
1770 * @param int $limit
1771 * @param array $params
1772 * @return array
1773 */
1774 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1775 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1776 }
1777 }
1778
1779 /**
1780 * Iterator for listing regular files
1781 */
1782 class SwiftFileBackendFileList extends SwiftFileBackendList {
1783 /**
1784 * @see Iterator::current()
1785 * @return string|bool String (relative path) or false
1786 */
1787 public function current() {
1788 list( $path, $stat ) = current( $this->bufferIter );
1789 $relPath = substr( $path, $this->suffixStart );
1790 if ( is_array( $stat ) ) {
1791 $storageDir = rtrim( $this->params['dir'], '/' );
1792 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1793 }
1794
1795 return $relPath;
1796 }
1797
1798 /**
1799 * @see SwiftFileBackendList::pageFromList()
1800 * @param string $container
1801 * @param string $dir
1802 * @param string $after
1803 * @param int $limit
1804 * @param array $params
1805 * @return array
1806 */
1807 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1808 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1809 }
1810 }