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