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