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