Merge "Provide direction hinting in the personal toolbar"
[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['concurrency'] = 1;
621 $stats = $this->doGetFileStatMulti( array( 'srcs' => array( $params['src'] ) ) + $params );
622
623 return reset( $stats );
624 }
625
626 /**
627 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
628 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
629 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
630 *
631 * @param string $ts
632 * @param int $format Output format (TS_* constant)
633 * @return string
634 * @throws FileBackendError
635 */
636 protected function convertSwiftDate( $ts, $format = TS_MW ) {
637 try {
638 $timestamp = new MWTimestamp( $ts );
639
640 return $timestamp->getTimestamp( $format );
641 } catch ( MWException $e ) {
642 throw new FileBackendError( $e->getMessage() );
643 }
644 }
645
646 /**
647 * Fill in any missing object metadata and save it to Swift
648 *
649 * @param array $objHdrs Object response headers
650 * @param string $path Storage path to object
651 * @return array New headers
652 */
653 protected function addMissingMetadata( array $objHdrs, $path ) {
654 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
655 return $objHdrs; // nothing to do
656 }
657
658 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
659 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING );
660
661 $auth = $this->getAuthentication();
662 if ( !$auth ) {
663 $objHdrs['x-object-meta-sha1base36'] = false;
664
665 return $objHdrs; // failed
666 }
667
668 $status = Status::newGood();
669 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
670 if ( $status->isOK() ) {
671 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
672 if ( $tmpFile ) {
673 $hash = $tmpFile->getSha1Base36();
674 if ( $hash !== false ) {
675 $objHdrs['x-object-meta-sha1base36'] = $hash;
676 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
677 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
678 'method' => 'POST',
679 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
680 'headers' => $this->authTokenHeaders( $auth ) + $objHdrs
681 ) );
682 if ( $rcode >= 200 && $rcode <= 299 ) {
683 return $objHdrs; // success
684 }
685 }
686 }
687 }
688 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING );
689 $objHdrs['x-object-meta-sha1base36'] = false;
690
691 return $objHdrs; // failed
692 }
693
694 protected function doGetFileContentsMulti( array $params ) {
695 $contents = array();
696
697 $auth = $this->getAuthentication();
698
699 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
700 // Blindly create tmp files and stream to them, catching any exception if the file does
701 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
702 $reqs = array(); // (path => op)
703
704 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
705 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
706 if ( $srcRel === null || !$auth ) {
707 $contents[$path] = false;
708 continue;
709 }
710 // Create a new temporary memory file...
711 $handle = fopen( 'php://temp', 'wb' );
712 if ( $handle ) {
713 $reqs[$path] = array(
714 'method' => 'GET',
715 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
716 'headers' => $this->authTokenHeaders( $auth )
717 + $this->headersFromParams( $params ),
718 'stream' => $handle,
719 );
720 }
721 $contents[$path] = false;
722 }
723
724 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
725 $reqs = $this->http->runMulti( $reqs, $opts );
726 foreach ( $reqs as $path => $op ) {
727 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
728 if ( $rcode >= 200 && $rcode <= 299 ) {
729 rewind( $op['stream'] ); // start from the beginning
730 $contents[$path] = stream_get_contents( $op['stream'] );
731 } elseif ( $rcode === 404 ) {
732 $contents[$path] = false;
733 } else {
734 $this->onError( null, __METHOD__,
735 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
736 }
737 fclose( $op['stream'] ); // close open handle
738 }
739
740 return $contents;
741 }
742
743 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
744 $prefix = ( $dir == '' ) ? null : "{$dir}/";
745 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
746 if ( $status->isOk() ) {
747 return ( count( $status->value ) ) > 0;
748 }
749
750 return null; // error
751 }
752
753 /**
754 * @see FileBackendStore::getDirectoryListInternal()
755 * @param string $fullCont
756 * @param string $dir
757 * @param array $params
758 * @return SwiftFileBackendDirList
759 */
760 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
761 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
762 }
763
764 /**
765 * @see FileBackendStore::getFileListInternal()
766 * @param string $fullCont
767 * @param string $dir
768 * @param array $params
769 * @return SwiftFileBackendFileList
770 */
771 public function getFileListInternal( $fullCont, $dir, array $params ) {
772 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
773 }
774
775 /**
776 * Do not call this function outside of SwiftFileBackendFileList
777 *
778 * @param string $fullCont Resolved container name
779 * @param string $dir Resolved storage directory with no trailing slash
780 * @param string|null $after Resolved container relative path to list items after
781 * @param int $limit Max number of items to list
782 * @param array $params Parameters for getDirectoryList()
783 * @return array List of container relative resolved paths of directories directly under $dir
784 * @throws FileBackendError
785 */
786 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
787 $dirs = array();
788 if ( $after === INF ) {
789 return $dirs; // nothing more
790 }
791
792 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
793
794 $prefix = ( $dir == '' ) ? null : "{$dir}/";
795 // Non-recursive: only list dirs right under $dir
796 if ( !empty( $params['topOnly'] ) ) {
797 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
798 if ( !$status->isOk() ) {
799 return $dirs; // error
800 }
801 $objects = $status->value;
802 foreach ( $objects as $object ) { // files and directories
803 if ( substr( $object, -1 ) === '/' ) {
804 $dirs[] = $object; // directories end in '/'
805 }
806 }
807 } else {
808 // Recursive: list all dirs under $dir and its subdirs
809 $getParentDir = function ( $path ) {
810 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
811 };
812
813 // Get directory from last item of prior page
814 $lastDir = $getParentDir( $after ); // must be first page
815 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
816
817 if ( !$status->isOk() ) {
818 return $dirs; // error
819 }
820
821 $objects = $status->value;
822
823 foreach ( $objects as $object ) { // files
824 $objectDir = $getParentDir( $object ); // directory of object
825
826 if ( $objectDir !== false && $objectDir !== $dir ) {
827 // Swift stores paths in UTF-8, using binary sorting.
828 // See function "create_container_table" in common/db.py.
829 // If a directory is not "greater" than the last one,
830 // then it was already listed by the calling iterator.
831 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
832 $pDir = $objectDir;
833 do { // add dir and all its parent dirs
834 $dirs[] = "{$pDir}/";
835 $pDir = $getParentDir( $pDir );
836 } while ( $pDir !== false // sanity
837 && strcmp( $pDir, $lastDir ) > 0 // not done already
838 && strlen( $pDir ) > strlen( $dir ) // within $dir
839 );
840 }
841 $lastDir = $objectDir;
842 }
843 }
844 }
845 // Page on the unfiltered directory listing (what is returned may be filtered)
846 if ( count( $objects ) < $limit ) {
847 $after = INF; // avoid a second RTT
848 } else {
849 $after = end( $objects ); // update last item
850 }
851
852 return $dirs;
853 }
854
855 /**
856 * Do not call this function outside of SwiftFileBackendFileList
857 *
858 * @param string $fullCont Resolved container name
859 * @param string $dir Resolved storage directory with no trailing slash
860 * @param string|null $after Resolved container relative path of file to list items after
861 * @param int $limit Max number of items to list
862 * @param array $params Parameters for getDirectoryList()
863 * @return array List of resolved container relative paths of files under $dir
864 * @throws FileBackendError
865 */
866 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
867 $files = array(); // list of (path, stat array or null) entries
868 if ( $after === INF ) {
869 return $files; // nothing more
870 }
871
872 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
873
874 $prefix = ( $dir == '' ) ? null : "{$dir}/";
875 // $objects will contain a list of unfiltered names or CF_Object items
876 // Non-recursive: only list files right under $dir
877 if ( !empty( $params['topOnly'] ) ) {
878 if ( !empty( $params['adviseStat'] ) ) {
879 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
880 } else {
881 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
882 }
883 } else {
884 // Recursive: list all files under $dir and its subdirs
885 if ( !empty( $params['adviseStat'] ) ) {
886 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
887 } else {
888 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
889 }
890 }
891
892 // Reformat this list into a list of (name, stat array or null) entries
893 if ( !$status->isOk() ) {
894 return $files; // error
895 }
896
897 $objects = $status->value;
898 $files = $this->buildFileObjectListing( $params, $dir, $objects );
899
900 // Page on the unfiltered object listing (what is returned may be filtered)
901 if ( count( $objects ) < $limit ) {
902 $after = INF; // avoid a second RTT
903 } else {
904 $after = end( $objects ); // update last item
905 $after = is_object( $after ) ? $after->name : $after;
906 }
907
908 return $files;
909 }
910
911 /**
912 * Build a list of file objects, filtering out any directories
913 * and extracting any stat info if provided in $objects (for CF_Objects)
914 *
915 * @param array $params Parameters for getDirectoryList()
916 * @param string $dir Resolved container directory path
917 * @param array $objects List of CF_Object items or object names
918 * @return array List of (names,stat array or null) entries
919 */
920 private function buildFileObjectListing( array $params, $dir, array $objects ) {
921 $names = array();
922 foreach ( $objects as $object ) {
923 if ( is_object( $object ) ) {
924 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
925 continue; // virtual directory entry; ignore
926 }
927 $stat = array(
928 // Convert various random Swift dates to TS_MW
929 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
930 'size' => (int)$object->bytes,
931 // Note: manifiest ETags are not an MD5 of the file
932 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
933 'latest' => false // eventually consistent
934 );
935 $names[] = array( $object->name, $stat );
936 } elseif ( substr( $object, -1 ) !== '/' ) {
937 // Omit directories, which end in '/' in listings
938 $names[] = array( $object, null );
939 }
940 }
941
942 return $names;
943 }
944
945 /**
946 * Do not call this function outside of SwiftFileBackendFileList
947 *
948 * @param string $path Storage path
949 * @param array $val Stat value
950 */
951 public function loadListingStatInternal( $path, array $val ) {
952 $this->cheapCache->set( $path, 'stat', $val );
953 }
954
955 protected function doGetFileXAttributes( array $params ) {
956 $stat = $this->getFileStat( $params );
957 if ( $stat ) {
958 if ( !isset( $stat['xattr'] ) ) {
959 // Stat entries filled by file listings don't include metadata/headers
960 $this->clearCache( array( $params['src'] ) );
961 $stat = $this->getFileStat( $params );
962 }
963
964 return $stat['xattr'];
965 } else {
966 return false;
967 }
968 }
969
970 protected function doGetFileSha1base36( array $params ) {
971 $stat = $this->getFileStat( $params );
972 if ( $stat ) {
973 if ( !isset( $stat['sha1'] ) ) {
974 // Stat entries filled by file listings don't include SHA1
975 $this->clearCache( array( $params['src'] ) );
976 $stat = $this->getFileStat( $params );
977 }
978
979 return $stat['sha1'];
980 } else {
981 return false;
982 }
983 }
984
985 protected function doStreamFile( array $params ) {
986 $status = Status::newGood();
987
988 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
989 if ( $srcRel === null ) {
990 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
991 }
992
993 $auth = $this->getAuthentication();
994 if ( !$auth || !is_array( $this->getContainerStat( $srcCont ) ) ) {
995 $status->fatal( 'backend-fail-stream', $params['src'] );
996
997 return $status;
998 }
999
1000 $handle = fopen( 'php://output', 'wb' );
1001
1002 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1003 'method' => 'GET',
1004 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1005 'headers' => $this->authTokenHeaders( $auth )
1006 + $this->headersFromParams( $params ),
1007 'stream' => $handle,
1008 ) );
1009
1010 if ( $rcode >= 200 && $rcode <= 299 ) {
1011 // good
1012 } elseif ( $rcode === 404 ) {
1013 $status->fatal( 'backend-fail-stream', $params['src'] );
1014 } else {
1015 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1016 }
1017
1018 return $status;
1019 }
1020
1021 protected function doGetLocalCopyMulti( array $params ) {
1022 $tmpFiles = array();
1023
1024 $auth = $this->getAuthentication();
1025
1026 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1027 // Blindly create tmp files and stream to them, catching any exception if the file does
1028 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1029 $reqs = array(); // (path => op)
1030
1031 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1032 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1033 if ( $srcRel === null || !$auth ) {
1034 $tmpFiles[$path] = null;
1035 continue;
1036 }
1037 // Get source file extension
1038 $ext = FileBackend::extensionFromPath( $path );
1039 // Create a new temporary file...
1040 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1041 if ( $tmpFile ) {
1042 $handle = fopen( $tmpFile->getPath(), 'wb' );
1043 if ( $handle ) {
1044 $reqs[$path] = array(
1045 'method' => 'GET',
1046 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1047 'headers' => $this->authTokenHeaders( $auth )
1048 + $this->headersFromParams( $params ),
1049 'stream' => $handle,
1050 );
1051 } else {
1052 $tmpFile = null;
1053 }
1054 }
1055 $tmpFiles[$path] = $tmpFile;
1056 }
1057
1058 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1059 $reqs = $this->http->runMulti( $reqs, $opts );
1060 foreach ( $reqs as $path => $op ) {
1061 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1062 fclose( $op['stream'] ); // close open handle
1063 if ( $rcode >= 200 && $rcode <= 299
1064 // double check that the disk is not full/broken
1065 && $tmpFiles[$path]->getSize() == $rhdrs['content-length']
1066 ) {
1067 // good
1068 } elseif ( $rcode === 404 ) {
1069 $tmpFiles[$path] = false;
1070 } else {
1071 $tmpFiles[$path] = null;
1072 $this->onError( null, __METHOD__,
1073 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1074 }
1075 }
1076
1077 return $tmpFiles;
1078 }
1079
1080 public function getFileHttpUrl( array $params ) {
1081 if ( $this->swiftTempUrlKey != '' ||
1082 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1083 ) {
1084 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1085 if ( $srcRel === null ) {
1086 return null; // invalid path
1087 }
1088
1089 $auth = $this->getAuthentication();
1090 if ( !$auth ) {
1091 return null;
1092 }
1093
1094 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1095 $expires = time() + $ttl;
1096
1097 if ( $this->swiftTempUrlKey != '' ) {
1098 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1099 // Swift wants the signature based on the unencoded object name
1100 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1101 $signature = hash_hmac( 'sha1',
1102 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1103 $this->swiftTempUrlKey
1104 );
1105
1106 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1107 } else { // give S3 API URL for rgw
1108 // Path for signature starts with the bucket
1109 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1110 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1111 // Calculate the hash
1112 $signature = base64_encode( hash_hmac(
1113 'sha1',
1114 "GET\n\n\n{$expires}\n{$spath}",
1115 $this->rgwS3SecretKey,
1116 true // raw
1117 ) );
1118 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1119 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1120 return wfAppendQuery(
1121 str_replace( '/swift/v1', '', // S3 API is the rgw default
1122 $this->storageUrl( $auth ) . $spath ),
1123 array(
1124 'Signature' => $signature,
1125 'Expires' => $expires,
1126 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1127 );
1128 }
1129 }
1130
1131 return null;
1132 }
1133
1134 protected function directoriesAreVirtual() {
1135 return true;
1136 }
1137
1138 /**
1139 * Get headers to send to Swift when reading a file based
1140 * on a FileBackend params array, e.g. that of getLocalCopy().
1141 * $params is currently only checked for a 'latest' flag.
1142 *
1143 * @param array $params
1144 * @return array
1145 */
1146 protected function headersFromParams( array $params ) {
1147 $hdrs = array();
1148 if ( !empty( $params['latest'] ) ) {
1149 $hdrs['x-newest'] = 'true';
1150 }
1151
1152 return $hdrs;
1153 }
1154
1155 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1156 $statuses = array();
1157
1158 $auth = $this->getAuthentication();
1159 if ( !$auth ) {
1160 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1161 $statuses[$index] = Status::newFatal( 'backend-fail-connect', $this->name );
1162 }
1163
1164 return $statuses;
1165 }
1166
1167 // Split the HTTP requests into stages that can be done concurrently
1168 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1169 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1170 $reqs = $fileOpHandle->httpOp;
1171 // Convert the 'url' parameter to an actual URL using $auth
1172 foreach ( $reqs as $stage => &$req ) {
1173 list( $container, $relPath ) = $req['url'];
1174 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1175 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : array();
1176 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1177 $httpReqsByStage[$stage][$index] = $req;
1178 }
1179 $statuses[$index] = Status::newGood();
1180 }
1181
1182 // Run all requests for the first stage, then the next, and so on
1183 $reqCount = count( $httpReqsByStage );
1184 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1185 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1186 foreach ( $httpReqs as $index => $httpReq ) {
1187 // Run the callback for each request of this operation
1188 $callback = $fileOpHandles[$index]->callback;
1189 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1190 // On failure, abort all remaining requests for this operation
1191 // (e.g. abort the DELETE request if the COPY request fails for a move)
1192 if ( !$statuses[$index]->isOK() ) {
1193 $stages = count( $fileOpHandles[$index]->httpOp );
1194 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1195 unset( $httpReqsByStage[$s][$index] );
1196 }
1197 }
1198 }
1199 }
1200
1201 return $statuses;
1202 }
1203
1204 /**
1205 * Set read/write permissions for a Swift container.
1206 *
1207 * @see http://swift.openstack.org/misc.html#acls
1208 *
1209 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1210 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1211 *
1212 * @param string $container Resolved Swift container
1213 * @param array $readGrps List of the possible criteria for a request to have
1214 * access to read a container. Each item is one of the following formats:
1215 * - account:user : Grants access if the request is by the given user
1216 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1217 * matches the expression and the request is not for a listing.
1218 * Setting this to '*' effectively makes a container public.
1219 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1220 * matches the expression and the request is for a listing.
1221 * @param array $writeGrps A list of the possible criteria for a request to have
1222 * access to write to a container. Each item is of the following format:
1223 * - account:user : Grants access if the request is by the given user
1224 * @return Status
1225 */
1226 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1227 $status = Status::newGood();
1228 $auth = $this->getAuthentication();
1229
1230 if ( !$auth ) {
1231 $status->fatal( 'backend-fail-connect', $this->name );
1232
1233 return $status;
1234 }
1235
1236 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1237 'method' => 'POST',
1238 'url' => $this->storageUrl( $auth, $container ),
1239 'headers' => $this->authTokenHeaders( $auth ) + array(
1240 'x-container-read' => implode( ',', $readGrps ),
1241 'x-container-write' => implode( ',', $writeGrps )
1242 )
1243 ) );
1244
1245 if ( $rcode != 204 && $rcode !== 202 ) {
1246 $status->fatal( 'backend-fail-internal', $this->name );
1247 }
1248
1249 return $status;
1250 }
1251
1252 /**
1253 * Get a Swift container stat array, possibly from process cache.
1254 * Use $reCache if the file count or byte count is needed.
1255 *
1256 * @param string $container Container name
1257 * @param bool $bypassCache Bypass all caches and load from Swift
1258 * @return array|bool|null False on 404, null on failure
1259 */
1260 protected function getContainerStat( $container, $bypassCache = false ) {
1261 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
1262
1263 if ( $bypassCache ) { // purge cache
1264 $this->containerStatCache->clear( $container );
1265 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1266 $this->primeContainerCache( array( $container ) ); // check persistent cache
1267 }
1268 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1269 $auth = $this->getAuthentication();
1270 if ( !$auth ) {
1271 return null;
1272 }
1273
1274 wfProfileIn( __METHOD__. "-{$this->name}-miss" );
1275 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1276 'method' => 'HEAD',
1277 'url' => $this->storageUrl( $auth, $container ),
1278 'headers' => $this->authTokenHeaders( $auth )
1279 ) );
1280 wfProfileOut( __METHOD__ . "-{$this->name}-miss" );
1281
1282 if ( $rcode === 204 ) {
1283 $stat = array(
1284 'count' => $rhdrs['x-container-object-count'],
1285 'bytes' => $rhdrs['x-container-bytes-used']
1286 );
1287 if ( $bypassCache ) {
1288 return $stat;
1289 } else {
1290 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1291 $this->setContainerCache( $container, $stat ); // update persistent cache
1292 }
1293 } elseif ( $rcode === 404 ) {
1294 return false;
1295 } else {
1296 $this->onError( null, __METHOD__,
1297 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1298
1299 return null;
1300 }
1301 }
1302
1303 return $this->containerStatCache->get( $container, 'stat' );
1304 }
1305
1306 /**
1307 * Create a Swift container
1308 *
1309 * @param string $container Container name
1310 * @param array $params
1311 * @return Status
1312 */
1313 protected function createContainer( $container, array $params ) {
1314 $status = Status::newGood();
1315
1316 $auth = $this->getAuthentication();
1317 if ( !$auth ) {
1318 $status->fatal( 'backend-fail-connect', $this->name );
1319
1320 return $status;
1321 }
1322
1323 // @see SwiftFileBackend::setContainerAccess()
1324 if ( empty( $params['noAccess'] ) ) {
1325 $readGrps = array( '.r:*', $this->swiftUser ); // public
1326 } else {
1327 $readGrps = array( $this->swiftUser ); // private
1328 }
1329 $writeGrps = array( $this->swiftUser ); // sanity
1330
1331 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1332 'method' => 'PUT',
1333 'url' => $this->storageUrl( $auth, $container ),
1334 'headers' => $this->authTokenHeaders( $auth ) + array(
1335 'x-container-read' => implode( ',', $readGrps ),
1336 'x-container-write' => implode( ',', $writeGrps )
1337 )
1338 ) );
1339
1340 if ( $rcode === 201 ) { // new
1341 // good
1342 } elseif ( $rcode === 202 ) { // already there
1343 // this shouldn't really happen, but is OK
1344 } else {
1345 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1346 }
1347
1348 return $status;
1349 }
1350
1351 /**
1352 * Delete a Swift container
1353 *
1354 * @param string $container Container name
1355 * @param array $params
1356 * @return Status
1357 */
1358 protected function deleteContainer( $container, array $params ) {
1359 $status = Status::newGood();
1360
1361 $auth = $this->getAuthentication();
1362 if ( !$auth ) {
1363 $status->fatal( 'backend-fail-connect', $this->name );
1364
1365 return $status;
1366 }
1367
1368 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1369 'method' => 'DELETE',
1370 'url' => $this->storageUrl( $auth, $container ),
1371 'headers' => $this->authTokenHeaders( $auth )
1372 ) );
1373
1374 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1375 $this->containerStatCache->clear( $container ); // purge
1376 } elseif ( $rcode === 404 ) { // not there
1377 // this shouldn't really happen, but is OK
1378 } elseif ( $rcode === 409 ) { // not empty
1379 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1380 } else {
1381 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1382 }
1383
1384 return $status;
1385 }
1386
1387 /**
1388 * Get a list of objects under a container.
1389 * Either just the names or a list of stdClass objects with details can be returned.
1390 *
1391 * @param string $fullCont
1392 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1393 * @param integer $limit
1394 * @param string|null $after
1395 * @param string|null $prefix
1396 * @param string|null $delim
1397 * @return Status With the list as value
1398 */
1399 private function objectListing(
1400 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1401 ) {
1402 $status = Status::newGood();
1403
1404 $auth = $this->getAuthentication();
1405 if ( !$auth ) {
1406 $status->fatal( 'backend-fail-connect', $this->name );
1407
1408 return $status;
1409 }
1410
1411 $query = array( 'limit' => $limit );
1412 if ( $type === 'info' ) {
1413 $query['format'] = 'json';
1414 }
1415 if ( $after !== null ) {
1416 $query['marker'] = $after;
1417 }
1418 if ( $prefix !== null ) {
1419 $query['prefix'] = $prefix;
1420 }
1421 if ( $delim !== null ) {
1422 $query['delimiter'] = $delim;
1423 }
1424
1425 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1426 'method' => 'GET',
1427 'url' => $this->storageUrl( $auth, $fullCont ),
1428 'query' => $query,
1429 'headers' => $this->authTokenHeaders( $auth )
1430 ) );
1431
1432 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1433 if ( $rcode === 200 ) { // good
1434 if ( $type === 'info' ) {
1435 $status->value = FormatJson::decode( trim( $rbody ) );
1436 } else {
1437 $status->value = explode( "\n", trim( $rbody ) );
1438 }
1439 } elseif ( $rcode === 204 ) {
1440 $status->value = array(); // empty container
1441 } elseif ( $rcode === 404 ) {
1442 $status->value = array(); // no container
1443 } else {
1444 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1445 }
1446
1447 return $status;
1448 }
1449
1450 protected function doPrimeContainerCache( array $containerInfo ) {
1451 foreach ( $containerInfo as $container => $info ) {
1452 $this->containerStatCache->set( $container, 'stat', $info );
1453 }
1454 }
1455
1456 protected function doGetFileStatMulti( array $params ) {
1457 $stats = array();
1458
1459 $auth = $this->getAuthentication();
1460
1461 $reqs = array();
1462 foreach ( $params['srcs'] as $path ) {
1463 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1464 if ( $srcRel === null ) {
1465 $stats[$path] = false;
1466 continue; // invalid storage path
1467 } elseif ( !$auth ) {
1468 $stats[$path] = null;
1469 continue;
1470 }
1471
1472 // (a) Check the container
1473 $cstat = $this->getContainerStat( $srcCont );
1474 if ( $cstat === false ) {
1475 $stats[$path] = false;
1476 continue; // ok, nothing to do
1477 } elseif ( !is_array( $cstat ) ) {
1478 $stats[$path] = null;
1479 continue;
1480 }
1481
1482 $reqs[$path] = array(
1483 'method' => 'HEAD',
1484 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1485 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1486 );
1487 }
1488
1489 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1490 $reqs = $this->http->runMulti( $reqs, $opts );
1491
1492 foreach ( $params['srcs'] as $path ) {
1493 if ( array_key_exists( $path, $stats ) ) {
1494 continue; // some sort of failure above
1495 }
1496 // (b) Check the file
1497 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1498 if ( $rcode === 200 || $rcode === 204 ) {
1499 // Update the object if it is missing some headers
1500 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1501 // Fetch all of the custom metadata headers
1502 $metadata = array();
1503 foreach ( $rhdrs as $name => $value ) {
1504 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
1505 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
1506 }
1507 }
1508 // Fetch all of the custom raw HTTP headers
1509 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1510 $stat = array(
1511 // Convert various random Swift dates to TS_MW
1512 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1513 // Empty objects actually return no content-length header in Ceph
1514 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1515 'sha1' => $rhdrs[ 'x-object-meta-sha1base36'],
1516 // Note: manifiest ETags are not an MD5 of the file
1517 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1518 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1519 );
1520 } elseif ( $rcode === 404 ) {
1521 $stat = false;
1522 } else {
1523 $stat = null;
1524 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1525 }
1526 $stats[$path] = $stat;
1527 }
1528
1529 return $stats;
1530 }
1531
1532 /**
1533 * @return array|null Credential map
1534 */
1535 protected function getAuthentication() {
1536 if ( $this->authErrorTimestamp !== null ) {
1537 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1538 return null; // failed last attempt; don't bother
1539 } else { // actually retry this time
1540 $this->authErrorTimestamp = null;
1541 }
1542 }
1543 // Session keys expire after a while, so we renew them periodically
1544 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1545 // Authenticate with proxy and get a session key...
1546 if ( !$this->authCreds || $reAuth ) {
1547 $this->authSessionTimestamp = 0;
1548 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1549 $creds = $this->srvCache->get( $cacheKey ); // credentials
1550 // Try to use the credential cache
1551 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1552 $this->authCreds = $creds;
1553 // Skew the timestamp for worst case to avoid using stale credentials
1554 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1555 } else { // cache miss
1556 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1557 'method' => 'GET',
1558 'url' => "{$this->swiftAuthUrl}/v1.0",
1559 'headers' => array(
1560 'x-auth-user' => $this->swiftUser,
1561 'x-auth-key' => $this->swiftKey
1562 )
1563 ) );
1564
1565 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1566 $this->authCreds = array(
1567 'auth_token' => $rhdrs['x-auth-token'],
1568 'storage_url' => $rhdrs['x-storage-url']
1569 );
1570 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1571 $this->authSessionTimestamp = time();
1572 } elseif ( $rcode === 401 ) {
1573 $this->onError( null, __METHOD__, array(), "Authentication failed.", $rcode );
1574 $this->authErrorTimestamp = time();
1575
1576 return null;
1577 } else {
1578 $this->onError( null, __METHOD__, array(), "HTTP return code: $rcode", $rcode );
1579 $this->authErrorTimestamp = time();
1580
1581 return null;
1582 }
1583 }
1584 }
1585
1586 return $this->authCreds;
1587 }
1588
1589 /**
1590 * @param array $creds From getAuthentication()
1591 * @param string $container
1592 * @param string $object
1593 * @return array
1594 */
1595 protected function storageUrl( array $creds, $container = null, $object = null ) {
1596 $parts = array( $creds['storage_url'] );
1597 if ( strlen( $container ) ) {
1598 $parts[] = rawurlencode( $container );
1599 }
1600 if ( strlen( $object ) ) {
1601 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1602 }
1603
1604 return implode( '/', $parts );
1605 }
1606
1607 /**
1608 * @param array $creds From getAuthentication()
1609 * @return array
1610 */
1611 protected function authTokenHeaders( array $creds ) {
1612 return array( 'x-auth-token' => $creds['auth_token'] );
1613 }
1614
1615 /**
1616 * Get the cache key for a container
1617 *
1618 * @param string $username
1619 * @return string
1620 */
1621 private function getCredsCacheKey( $username ) {
1622 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1623 }
1624
1625 /**
1626 * Log an unexpected exception for this backend.
1627 * This also sets the Status object to have a fatal error.
1628 *
1629 * @param Status|null $status
1630 * @param string $func
1631 * @param array $params
1632 * @param string $err Error string
1633 * @param integer $code HTTP status
1634 * @param string $desc HTTP status description
1635 */
1636 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1637 if ( $status instanceof Status ) {
1638 $status->fatal( 'backend-fail-internal', $this->name );
1639 }
1640 if ( $code == 401 ) { // possibly a stale token
1641 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1642 }
1643 wfDebugLog( 'SwiftBackend',
1644 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1645 ( $err ? ": $err" : "" )
1646 );
1647 }
1648 }
1649
1650 /**
1651 * @see FileBackendStoreOpHandle
1652 */
1653 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1654 /** @var array List of Requests for MultiHttpClient */
1655 public $httpOp;
1656 /** @var Closure */
1657 public $callback;
1658
1659 /**
1660 * @param SwiftFileBackend $backend
1661 * @param Closure $callback Function that takes (HTTP request array, status)
1662 * @param array $httpOp MultiHttpClient op
1663 */
1664 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1665 $this->backend = $backend;
1666 $this->callback = $callback;
1667 $this->httpOp = $httpOp;
1668 }
1669 }
1670
1671 /**
1672 * SwiftFileBackend helper class to page through listings.
1673 * Swift also has a listing limit of 10,000 objects for sanity.
1674 * Do not use this class from places outside SwiftFileBackend.
1675 *
1676 * @ingroup FileBackend
1677 */
1678 abstract class SwiftFileBackendList implements Iterator {
1679 /** @var array List of path or (path,stat array) entries */
1680 protected $bufferIter = array();
1681
1682 /** @var string List items *after* this path */
1683 protected $bufferAfter = null;
1684
1685 /** @var int */
1686 protected $pos = 0;
1687
1688 /** @var array */
1689 protected $params = array();
1690
1691 /** @var SwiftFileBackend */
1692 protected $backend;
1693
1694 /** @var string Container name */
1695 protected $container;
1696
1697 /** @var string Storage directory */
1698 protected $dir;
1699
1700 /** @var int */
1701 protected $suffixStart;
1702
1703 const PAGE_SIZE = 9000; // file listing buffer size
1704
1705 /**
1706 * @param SwiftFileBackend $backend
1707 * @param string $fullCont Resolved container name
1708 * @param string $dir Resolved directory relative to container
1709 * @param array $params
1710 */
1711 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1712 $this->backend = $backend;
1713 $this->container = $fullCont;
1714 $this->dir = $dir;
1715 if ( substr( $this->dir, -1 ) === '/' ) {
1716 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1717 }
1718 if ( $this->dir == '' ) { // whole container
1719 $this->suffixStart = 0;
1720 } else { // dir within container
1721 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1722 }
1723 $this->params = $params;
1724 }
1725
1726 /**
1727 * @see Iterator::key()
1728 * @return int
1729 */
1730 public function key() {
1731 return $this->pos;
1732 }
1733
1734 /**
1735 * @see Iterator::next()
1736 */
1737 public function next() {
1738 // Advance to the next file in the page
1739 next( $this->bufferIter );
1740 ++$this->pos;
1741 // Check if there are no files left in this page and
1742 // advance to the next page if this page was not empty.
1743 if ( !$this->valid() && count( $this->bufferIter ) ) {
1744 $this->bufferIter = $this->pageFromList(
1745 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1746 ); // updates $this->bufferAfter
1747 }
1748 }
1749
1750 /**
1751 * @see Iterator::rewind()
1752 */
1753 public function rewind() {
1754 $this->pos = 0;
1755 $this->bufferAfter = null;
1756 $this->bufferIter = $this->pageFromList(
1757 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1758 ); // updates $this->bufferAfter
1759 }
1760
1761 /**
1762 * @see Iterator::valid()
1763 * @return bool
1764 */
1765 public function valid() {
1766 if ( $this->bufferIter === null ) {
1767 return false; // some failure?
1768 } else {
1769 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1770 }
1771 }
1772
1773 /**
1774 * Get the given list portion (page)
1775 *
1776 * @param string $container Resolved container name
1777 * @param string $dir Resolved path relative to container
1778 * @param string $after null
1779 * @param int $limit
1780 * @param array $params
1781 * @return Traversable|array
1782 */
1783 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1784 }
1785
1786 /**
1787 * Iterator for listing directories
1788 */
1789 class SwiftFileBackendDirList extends SwiftFileBackendList {
1790 /**
1791 * @see Iterator::current()
1792 * @return string|bool String (relative path) or false
1793 */
1794 public function current() {
1795 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1796 }
1797
1798 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1799 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1800 }
1801 }
1802
1803 /**
1804 * Iterator for listing regular files
1805 */
1806 class SwiftFileBackendFileList extends SwiftFileBackendList {
1807 /**
1808 * @see Iterator::current()
1809 * @return string|bool String (relative path) or false
1810 */
1811 public function current() {
1812 list( $path, $stat ) = current( $this->bufferIter );
1813 $relPath = substr( $path, $this->suffixStart );
1814 if ( is_array( $stat ) ) {
1815 $storageDir = rtrim( $this->params['dir'], '/' );
1816 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1817 }
1818
1819 return $relPath;
1820 }
1821
1822 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1823 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1824 }
1825 }