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