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