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