Merge "Fix default value of domain select box in templates"
[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 $objects = array(); // list of unfiltered names or CF_Object items
1094 // Non-recursive: only list files right under $dir
1095 if ( !empty( $params['topOnly'] ) ) {
1096 if ( !empty( $params['adviseStat'] ) ) {
1097 // Note: get_objects() does not include directories
1098 $objects = $container->get_objects( $limit, $after, $prefix, null, '/' );
1099 } else {
1100 // Note: list_objects() includes directories here
1101 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1102 }
1103 $files = $this->buildFileObjectListing( $params, $dir, $objects );
1104 // Recursive: list all files under $dir and its subdirs
1105 } else {
1106 // Note: get_objects()/list_objects() here only return file objects
1107 if ( !empty( $params['adviseStat'] ) ) {
1108 $objects = $container->get_objects( $limit, $after, $prefix );
1109 } else {
1110 $objects = $container->list_objects( $limit, $after, $prefix );
1111 }
1112 $files = $this->buildFileObjectListing( $params, $dir, $objects );
1113 }
1114 // Page on the unfiltered object listing (what is returned may be filtered)
1115 if ( count( $objects ) < $limit ) {
1116 $after = INF; // avoid a second RTT
1117 } else {
1118 $after = end( $objects ); // update last item
1119 $after = is_object( $after ) ? $after->name : $after;
1120 }
1121 } catch ( NoSuchContainerException $e ) {
1122 } catch ( CloudFilesException $e ) { // some other exception?
1123 $this->handleException( $e, null, __METHOD__,
1124 array( 'cont' => $fullCont, 'dir' => $dir ) );
1125 throw new FileBackendError( "Got " . get_class( $e ) . " exception." );
1126 }
1127
1128 return $files;
1129 }
1130
1131 /**
1132 * Build a list of file objects, filtering out any directories
1133 * and extracting any stat info if provided in $objects (for CF_Objects)
1134 *
1135 * @param array $params Parameters for getDirectoryList()
1136 * @param string $dir Resolved container directory path
1137 * @param array $objects List of CF_Object items or object names
1138 * @return array List of (names,stat array or null) entries
1139 */
1140 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1141 $names = array();
1142 foreach ( $objects as $object ) {
1143 if ( is_object( $object ) ) {
1144 $stat = array(
1145 // Convert various random Swift dates to TS_MW
1146 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
1147 'size' => (int)$object->content_length,
1148 'latest' => false // eventually consistent
1149 );
1150 $names[] = array( $object->name, $stat );
1151 } elseif ( substr( $object, -1 ) !== '/' ) {
1152 // Omit directories, which end in '/' in listings
1153 $names[] = array( $object, null );
1154 }
1155 }
1156
1157 return $names;
1158 }
1159
1160 /**
1161 * Do not call this function outside of SwiftFileBackendFileList
1162 *
1163 * @param string $path Storage path
1164 * @param array $val Stat value
1165 */
1166 public function loadListingStatInternal( $path, array $val ) {
1167 $this->cheapCache->set( $path, 'stat', $val );
1168 }
1169
1170 protected function doGetFileSha1base36( array $params ) {
1171 $stat = $this->getFileStat( $params );
1172 if ( $stat ) {
1173 if ( !isset( $stat['sha1'] ) ) {
1174 // Stat entries filled by file listings don't include SHA1
1175 $this->clearCache( array( $params['src'] ) );
1176 $stat = $this->getFileStat( $params );
1177 }
1178
1179 return $stat['sha1'];
1180 } else {
1181 return false;
1182 }
1183 }
1184
1185 protected function doStreamFile( array $params ) {
1186 $status = Status::newGood();
1187
1188 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1189 if ( $srcRel === null ) {
1190 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1191 }
1192
1193 try {
1194 $cont = $this->getContainer( $srcCont );
1195 } catch ( NoSuchContainerException $e ) {
1196 $status->fatal( 'backend-fail-stream', $params['src'] );
1197
1198 return $status;
1199 } catch ( CloudFilesException $e ) { // some other exception?
1200 $this->handleException( $e, $status, __METHOD__, $params );
1201
1202 return $status;
1203 }
1204
1205 try {
1206 $output = fopen( 'php://output', 'wb' );
1207 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1208 $obj->stream( $output, $this->headersFromParams( $params ) );
1209 } catch ( NoSuchObjectException $e ) {
1210 $status->fatal( 'backend-fail-stream', $params['src'] );
1211 } catch ( CloudFilesException $e ) { // some other exception?
1212 $this->handleException( $e, $status, __METHOD__, $params );
1213 }
1214
1215 return $status;
1216 }
1217
1218 protected function doGetLocalCopyMulti( array $params ) {
1219 $tmpFiles = array();
1220
1221 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1222 // Blindly create tmp files and stream to them, catching any exception if the file does
1223 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1224 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1225 $cfOps = array(); // (path => CF_Async_Op)
1226
1227 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1228 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1229 if ( $srcRel === null ) {
1230 $tmpFiles[$path] = null;
1231 continue;
1232 }
1233 $tmpFile = null;
1234 try {
1235 $sContObj = $this->getContainer( $srcCont );
1236 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1237 // Get source file extension
1238 $ext = FileBackend::extensionFromPath( $path );
1239 // Create a new temporary file...
1240 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1241 if ( $tmpFile ) {
1242 $handle = fopen( $tmpFile->getPath(), 'wb' );
1243 if ( $handle ) {
1244 $headers = $this->headersFromParams( $params );
1245 if ( count( $pathBatch ) > 1 ) {
1246 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1247 $cfOps[$path]->_file_handle = $handle; // close this later
1248 } else {
1249 $obj->stream( $handle, $headers );
1250 fclose( $handle );
1251 }
1252 } else {
1253 $tmpFile = null;
1254 }
1255 }
1256 } catch ( NoSuchContainerException $e ) {
1257 $tmpFile = null;
1258 } catch ( NoSuchObjectException $e ) {
1259 $tmpFile = null;
1260 } catch ( CloudFilesException $e ) { // some other exception?
1261 $tmpFile = null;
1262 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1263 }
1264 $tmpFiles[$path] = $tmpFile;
1265 }
1266
1267 $batch = new CF_Async_Op_Batch( $cfOps );
1268 $cfOps = $batch->execute();
1269 foreach ( $cfOps as $path => $cfOp ) {
1270 try {
1271 $cfOp->getLastResponse();
1272 } catch ( NoSuchContainerException $e ) {
1273 $tmpFiles[$path] = null;
1274 } catch ( NoSuchObjectException $e ) {
1275 $tmpFiles[$path] = null;
1276 } catch ( CloudFilesException $e ) { // some other exception?
1277 $tmpFiles[$path] = null;
1278 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1279 }
1280 fclose( $cfOp->_file_handle ); // close open handle
1281 }
1282 }
1283
1284 return $tmpFiles;
1285 }
1286
1287 public function getFileHttpUrl( array $params ) {
1288 if ( $this->swiftTempUrlKey != '' ||
1289 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1290 ) {
1291 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1292 if ( $srcRel === null ) {
1293 return null; // invalid path
1294 }
1295 try {
1296 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1297 $sContObj = $this->getContainer( $srcCont );
1298 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1299 if ( $this->swiftTempUrlKey != '' ) {
1300 return $obj->get_temp_url( $this->swiftTempUrlKey, $ttl, "GET" );
1301 } else { // give S3 API URL for rgw
1302 $expires = time() + $ttl;
1303 // Path for signature starts with the bucket
1304 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1305 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1306 // Calculate the hash
1307 $signature = base64_encode( hash_hmac(
1308 'sha1',
1309 "GET\n\n\n{$expires}\n{$spath}",
1310 $this->rgwS3SecretKey,
1311 true // raw
1312 ) );
1313
1314 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1315 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1316 return wfAppendQuery(
1317 str_replace( '/swift/v1', '', // S3 API is the rgw default
1318 $sContObj->cfs_http->getStorageUrl() . $spath ),
1319 array(
1320 'Signature' => $signature,
1321 'Expires' => $expires,
1322 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1323 );
1324 }
1325 } catch ( NoSuchContainerException $e ) {
1326 } catch ( CloudFilesException $e ) { // some other exception?
1327 $this->handleException( $e, null, __METHOD__, $params );
1328 }
1329 }
1330
1331 return null;
1332 }
1333
1334 protected function directoriesAreVirtual() {
1335 return true;
1336 }
1337
1338 /**
1339 * Get headers to send to Swift when reading a file based
1340 * on a FileBackend params array, e.g. that of getLocalCopy().
1341 * $params is currently only checked for a 'latest' flag.
1342 *
1343 * @param array $params
1344 * @return array
1345 */
1346 protected function headersFromParams( array $params ) {
1347 $hdrs = array();
1348 if ( !empty( $params['latest'] ) ) {
1349 $hdrs[] = 'X-Newest: true';
1350 }
1351
1352 return $hdrs;
1353 }
1354
1355 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1356 $statuses = array();
1357
1358 $cfOps = array(); // list of CF_Async_Op objects
1359 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1360 $cfOps[$index] = $fileOpHandle->cfOp;
1361 }
1362 $batch = new CF_Async_Op_Batch( $cfOps );
1363
1364 $cfOps = $batch->execute();
1365 foreach ( $cfOps as $index => $cfOp ) {
1366 $status = Status::newGood();
1367 $function = '_getResponse' . $fileOpHandles[$index]->call;
1368 try { // catch exceptions; update status
1369 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1370 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1371 } catch ( CloudFilesException $e ) { // some other exception?
1372 $this->handleException( $e, $status,
1373 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1374 }
1375 $statuses[$index] = $status;
1376 }
1377
1378 return $statuses;
1379 }
1380
1381 /**
1382 * Set read/write permissions for a Swift container.
1383 *
1384 * @see http://swift.openstack.org/misc.html#acls
1385 *
1386 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1387 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1388 *
1389 * @param CF_Container $contObj Swift container
1390 * @param array $readGrps List of the possible criteria for a request to have
1391 * access to read a container. Each item is one of the following formats:
1392 * - account:user : Grants access if the request is by the given user
1393 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1394 * matches the expression and the request is not for a listing.
1395 * Setting this to '*' effectively makes a container public.
1396 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1397 * matches the expression and the request is for a listing.
1398 * @param array $writeGrps A list of the possible criteria for a request to have
1399 * access to write to a container. Each item is of the following format:
1400 * - account:user : Grants access if the request is by the given user
1401 * @return Status
1402 */
1403 protected function setContainerAccess(
1404 CF_Container $contObj, array $readGrps, array $writeGrps
1405 ) {
1406 $creds = $contObj->cfs_auth->export_credentials();
1407
1408 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1409
1410 // Note: 10 second timeout consistent with php-cloudfiles
1411 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1412 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1413 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1414 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1415
1416 return $req->execute(); // should return 204
1417 }
1418
1419 /**
1420 * Purge the CDN cache of affected objects if CDN caching is enabled.
1421 * This is for Rackspace/Akamai CDNs.
1422 *
1423 * @param array $objects List of CF_Object items
1424 */
1425 public function purgeCDNCache( array $objects ) {
1426 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1427 foreach ( $objects as $object ) {
1428 try {
1429 $object->purge_from_cdn();
1430 } catch ( CDNNotEnabledException $e ) {
1431 // CDN not enabled; nothing to see here
1432 } catch ( CloudFilesException $e ) {
1433 $this->handleException( $e, null, __METHOD__,
1434 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1435 }
1436 }
1437 }
1438 }
1439
1440 /**
1441 * Get an authenticated connection handle to the Swift proxy
1442 *
1443 * @throws CloudFilesException
1444 * @throws CloudFilesException|Exception
1445 * @return CF_Connection|bool False on failure
1446 */
1447 protected function getConnection() {
1448 if ( $this->connException instanceof CloudFilesException ) {
1449 if ( ( time() - $this->connErrorTime ) < 60 ) {
1450 throw $this->connException; // failed last attempt; don't bother
1451 } else { // actually retry this time
1452 $this->connException = null;
1453 $this->connErrorTime = 0;
1454 }
1455 }
1456 // Session keys expire after a while, so we renew them periodically
1457 $reAuth = ( ( time() - $this->sessionStarted ) > $this->authTTL );
1458 // Authenticate with proxy and get a session key...
1459 if ( !$this->conn || $reAuth ) {
1460 $this->sessionStarted = 0;
1461 $this->connContainerCache->clear();
1462 $cacheKey = $this->getCredsCacheKey( $this->auth->username );
1463 $creds = $this->srvCache->get( $cacheKey ); // credentials
1464 if ( is_array( $creds ) ) { // cache hit
1465 $this->auth->load_cached_credentials(
1466 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1467 $this->sessionStarted = time() - ceil( $this->authTTL / 2 ); // skew for worst case
1468 } else { // cache miss
1469 try {
1470 $this->auth->authenticate();
1471 $creds = $this->auth->export_credentials();
1472 $this->srvCache->add( $cacheKey, $creds, ceil( $this->authTTL / 2 ) ); // cache
1473 $this->sessionStarted = time();
1474 } catch ( CloudFilesException $e ) {
1475 $this->connException = $e; // don't keep re-trying
1476 $this->connErrorTime = time();
1477 throw $e; // throw it back
1478 }
1479 }
1480 if ( $this->conn ) { // re-authorizing?
1481 $this->conn->close(); // close active cURL handles in CF_Http object
1482 }
1483 $this->conn = new CF_Connection( $this->auth );
1484 }
1485
1486 return $this->conn;
1487 }
1488
1489 /**
1490 * Close the connection to the Swift proxy
1491 */
1492 protected function closeConnection() {
1493 if ( $this->conn ) {
1494 $this->conn->close(); // close active cURL handles in CF_Http object
1495 $this->conn = null;
1496 $this->sessionStarted = 0;
1497 $this->connContainerCache->clear();
1498 }
1499 }
1500
1501 /**
1502 * Get the cache key for a container
1503 *
1504 * @param string $username
1505 * @return string
1506 */
1507 private function getCredsCacheKey( $username ) {
1508 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1509 }
1510
1511 /**
1512 * Get a Swift container object, possibly from process cache.
1513 * Use $reCache if the file count or byte count is needed.
1514 *
1515 * @param string $container Container name
1516 * @param bool $bypassCache Bypass all caches and load from Swift
1517 * @return CF_Container
1518 * @throws CloudFilesException
1519 */
1520 protected function getContainer( $container, $bypassCache = false ) {
1521 $conn = $this->getConnection(); // Swift proxy connection
1522 if ( $bypassCache ) { // purge cache
1523 $this->connContainerCache->clear( $container );
1524 } elseif ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1525 $this->primeContainerCache( array( $container ) ); // check persistent cache
1526 }
1527 if ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1528 $contObj = $conn->get_container( $container );
1529 // NoSuchContainerException not thrown: container must exist
1530 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache it
1531 if ( !$bypassCache ) {
1532 $this->setContainerCache( $container, // update persistent cache
1533 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1534 );
1535 }
1536 }
1537
1538 return $this->connContainerCache->get( $container, 'obj' );
1539 }
1540
1541 /**
1542 * Create a Swift container
1543 *
1544 * @param string $container Container name
1545 * @return CF_Container
1546 * @throws CloudFilesException
1547 */
1548 protected function createContainer( $container ) {
1549 $conn = $this->getConnection(); // Swift proxy connection
1550 $contObj = $conn->create_container( $container );
1551 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache
1552 return $contObj;
1553 }
1554
1555 /**
1556 * Delete a Swift container
1557 *
1558 * @param string $container Container name
1559 * @throws CloudFilesException
1560 */
1561 protected function deleteContainer( $container ) {
1562 $conn = $this->getConnection(); // Swift proxy connection
1563 $this->connContainerCache->clear( $container ); // purge
1564 $conn->delete_container( $container );
1565 }
1566
1567 protected function doPrimeContainerCache( array $containerInfo ) {
1568 try {
1569 $conn = $this->getConnection(); // Swift proxy connection
1570 foreach ( $containerInfo as $container => $info ) {
1571 $contObj = new CF_Container( $conn->cfs_auth, $conn->cfs_http,
1572 $container, $info['count'], $info['bytes'] );
1573 $this->connContainerCache->set( $container, 'obj', $contObj );
1574 }
1575 } catch ( CloudFilesException $e ) { // some other exception?
1576 $this->handleException( $e, null, __METHOD__, array() );
1577 }
1578 }
1579
1580 /**
1581 * Log an unexpected exception for this backend.
1582 * This also sets the Status object to have a fatal error.
1583 *
1584 * @param Exception $e
1585 * @param Status $status null
1586 * @param string $func
1587 * @param array $params
1588 */
1589 protected function handleException( Exception $e, $status, $func, array $params ) {
1590 if ( $status instanceof Status ) {
1591 if ( $e instanceof AuthenticationException ) {
1592 $status->fatal( 'backend-fail-connect', $this->name );
1593 } else {
1594 $status->fatal( 'backend-fail-internal', $this->name );
1595 }
1596 }
1597 if ( $e->getMessage() ) {
1598 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1599 }
1600 if ( $e instanceof InvalidResponseException ) { // possibly a stale token
1601 $this->srvCache->delete( $this->getCredsCacheKey( $this->auth->username ) );
1602 $this->closeConnection(); // force a re-connect and re-auth next time
1603 }
1604 wfDebugLog( 'SwiftBackend',
1605 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1606 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1607 );
1608 }
1609 }
1610
1611 /**
1612 * @see FileBackendStoreOpHandle
1613 */
1614 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1615 /** @var CF_Async_Op */
1616 public $cfOp;
1617
1618 /** @var array */
1619 public $affectedObjects = array();
1620
1621 /**
1622 * @param SwiftFileBackend $backend
1623 * @param array $params
1624 * @param string $call
1625 * @param CF_Async_Op $cfOp
1626 */
1627 public function __construct(
1628 SwiftFileBackend $backend, array $params, $call, CF_Async_Op $cfOp
1629 ) {
1630 $this->backend = $backend;
1631 $this->params = $params;
1632 $this->call = $call;
1633 $this->cfOp = $cfOp;
1634 }
1635 }
1636
1637 /**
1638 * SwiftFileBackend helper class to page through listings.
1639 * Swift also has a listing limit of 10,000 objects for sanity.
1640 * Do not use this class from places outside SwiftFileBackend.
1641 *
1642 * @ingroup FileBackend
1643 */
1644 abstract class SwiftFileBackendList implements Iterator {
1645 /** @var array List of path or (path,stat array) entries */
1646 protected $bufferIter = array();
1647
1648 /** @var string List items *after* this path */
1649 protected $bufferAfter = null;
1650
1651 /** @var int */
1652 protected $pos = 0;
1653
1654 /** @var array */
1655 protected $params = array();
1656
1657 /** @var SwiftFileBackend */
1658 protected $backend;
1659
1660 /** @var string Container name */
1661 protected $container;
1662
1663 /** @var string Storage directory */
1664 protected $dir;
1665
1666 /** @var int */
1667 protected $suffixStart;
1668
1669 const PAGE_SIZE = 9000; // file listing buffer size
1670
1671 /**
1672 * @param SwiftFileBackend $backend
1673 * @param string $fullCont Resolved container name
1674 * @param string $dir Resolved directory relative to container
1675 * @param array $params
1676 */
1677 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1678 $this->backend = $backend;
1679 $this->container = $fullCont;
1680 $this->dir = $dir;
1681 if ( substr( $this->dir, -1 ) === '/' ) {
1682 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1683 }
1684 if ( $this->dir == '' ) { // whole container
1685 $this->suffixStart = 0;
1686 } else { // dir within container
1687 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1688 }
1689 $this->params = $params;
1690 }
1691
1692 /**
1693 * @see Iterator::key()
1694 * @return int
1695 */
1696 public function key() {
1697 return $this->pos;
1698 }
1699
1700 /**
1701 * @see Iterator::next()
1702 */
1703 public function next() {
1704 // Advance to the next file in the page
1705 next( $this->bufferIter );
1706 ++$this->pos;
1707 // Check if there are no files left in this page and
1708 // advance to the next page if this page was not empty.
1709 if ( !$this->valid() && count( $this->bufferIter ) ) {
1710 $this->bufferIter = $this->pageFromList(
1711 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1712 ); // updates $this->bufferAfter
1713 }
1714 }
1715
1716 /**
1717 * @see Iterator::rewind()
1718 */
1719 public function rewind() {
1720 $this->pos = 0;
1721 $this->bufferAfter = null;
1722 $this->bufferIter = $this->pageFromList(
1723 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1724 ); // updates $this->bufferAfter
1725 }
1726
1727 /**
1728 * @see Iterator::valid()
1729 * @return bool
1730 */
1731 public function valid() {
1732 if ( $this->bufferIter === null ) {
1733 return false; // some failure?
1734 } else {
1735 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1736 }
1737 }
1738
1739 /**
1740 * Get the given list portion (page)
1741 *
1742 * @param string $container Resolved container name
1743 * @param string $dir Resolved path relative to container
1744 * @param string $after null
1745 * @param int $limit
1746 * @param array $params
1747 * @return Traversable|array
1748 */
1749 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1750 }
1751
1752 /**
1753 * Iterator for listing directories
1754 */
1755 class SwiftFileBackendDirList extends SwiftFileBackendList {
1756 /**
1757 * @see Iterator::current()
1758 * @return string|bool String (relative path) or false
1759 */
1760 public function current() {
1761 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1762 }
1763
1764 /**
1765 * @see SwiftFileBackendList::pageFromList()
1766 * @param string $container
1767 * @param string $dir
1768 * @param string $after
1769 * @param int $limit
1770 * @param array $params
1771 * @return array
1772 */
1773 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1774 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1775 }
1776 }
1777
1778 /**
1779 * Iterator for listing regular files
1780 */
1781 class SwiftFileBackendFileList extends SwiftFileBackendList {
1782 /**
1783 * @see Iterator::current()
1784 * @return string|bool String (relative path) or false
1785 */
1786 public function current() {
1787 list( $path, $stat ) = current( $this->bufferIter );
1788 $relPath = substr( $path, $this->suffixStart );
1789 if ( is_array( $stat ) ) {
1790 $storageDir = rtrim( $this->params['dir'], '/' );
1791 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1792 }
1793
1794 return $relPath;
1795 }
1796
1797 /**
1798 * @see SwiftFileBackendList::pageFromList()
1799 * @param string $container
1800 * @param string $dir
1801 * @param string $after
1802 * @param int $limit
1803 * @param array $params
1804 * @return array
1805 */
1806 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1807 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1808 }
1809 }