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