MediaWiki master
SwiftFileBackend.php
Go to the documentation of this file.
1<?php
27use Psr\Log\LoggerInterface;
28use Wikimedia\AtEase\AtEase;
33use Wikimedia\RequestTimeout\TimeoutException;
34
45 private const DEFAULT_HTTP_OPTIONS = [ 'httpVersion' => 'v1.1' ];
46 private const AUTH_FAILURE_ERROR = 'Could not connect due to prior authentication failure';
47
49 protected $http;
51 protected $authTTL;
53 protected $swiftAuthUrl;
57 protected $swiftUser;
59 protected $swiftKey;
63 protected $rgwS3AccessKey;
65 protected $rgwS3SecretKey;
67 protected $readUsers;
69 protected $writeUsers;
74
76 protected $srvCache;
77
80
82 protected $authCreds;
84 protected $authErrorTimestamp = null;
85
87 protected $isRGW = false;
88
127 public function __construct( array $config ) {
128 parent::__construct( $config );
129 // Required settings
130 $this->swiftAuthUrl = $config['swiftAuthUrl'];
131 $this->swiftUser = $config['swiftUser'];
132 $this->swiftKey = $config['swiftKey'];
133 // Optional settings
134 $this->authTTL = $config['swiftAuthTTL'] ?? 15 * 60; // some sensible number
135 $this->swiftTempUrlKey = $config['swiftTempUrlKey'] ?? '';
136 $this->swiftStorageUrl = $config['swiftStorageUrl'] ?? null;
137 $this->shardViaHashLevels = $config['shardViaHashLevels'] ?? '';
138 $this->rgwS3AccessKey = $config['rgwS3AccessKey'] ?? '';
139 $this->rgwS3SecretKey = $config['rgwS3SecretKey'] ?? '';
140
141 // HTTP helper client
142 $httpOptions = [];
143 foreach ( [ 'connTimeout', 'reqTimeout' ] as $optionName ) {
144 if ( isset( $config[$optionName] ) ) {
145 $httpOptions[$optionName] = $config[$optionName];
146 }
147 }
148 $this->http = new MultiHttpClient( $httpOptions );
149 $this->http->setLogger( $this->logger );
150
151 // Cache container information to mask latency
152 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache ) {
153 $this->memCache = $config['wanCache'];
154 }
155 // Process cache for container info
156 $this->containerStatCache = new MapCacheLRU( 300 );
157 // Cache auth token information to avoid RTTs
158 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
159 $this->srvCache = $config['srvCache'];
160 } else {
161 $this->srvCache = new EmptyBagOStuff();
162 }
163 $this->readUsers = $config['readUsers'] ?? [];
164 $this->writeUsers = $config['writeUsers'] ?? [];
165 $this->secureReadUsers = $config['secureReadUsers'] ?? [];
166 $this->secureWriteUsers = $config['secureWriteUsers'] ?? [];
167 // Per https://docs.openstack.org/swift/latest/overview_large_objects.html
168 // we need to split objects if they are larger than 5 GB. Support for
169 // splitting objects has not yet been implemented by this class
170 // so limit max file size to 5GiB.
171 $this->maxFileSize = 5 * 1024 * 1024 * 1024;
172 }
173
174 public function setLogger( LoggerInterface $logger ) {
175 parent::setLogger( $logger );
176 $this->http->setLogger( $logger );
177 }
178
179 public function getFeatures() {
180 return (
181 self::ATTR_UNICODE_PATHS |
182 self::ATTR_HEADERS |
183 self::ATTR_METADATA
184 );
185 }
186
187 protected function resolveContainerPath( $container, $relStoragePath ) {
188 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
189 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
190 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
191 return null; // too long for Swift
192 }
193
194 return $relStoragePath;
195 }
196
197 public function isPathUsableInternal( $storagePath ) {
198 [ $container, $rel ] = $this->resolveStoragePathReal( $storagePath );
199 if ( $rel === null ) {
200 return false; // invalid
201 }
202
203 return is_array( $this->getContainerStat( $container ) );
204 }
205
215 protected function extractMutableContentHeaders( array $headers ) {
216 $contentHeaders = [];
217 // Normalize casing, and strip out illegal headers
218 foreach ( $headers as $name => $value ) {
219 $name = strtolower( $name );
220 if ( $name === 'x-delete-at' && is_numeric( $value ) ) {
221 // Expects a Unix Epoch date
222 $contentHeaders[$name] = $value;
223 } elseif ( $name === 'x-delete-after' && is_numeric( $value ) ) {
224 // Expects number of minutes time to live.
225 $contentHeaders[$name] = $value;
226 } elseif ( preg_match( '/^(x-)?content-(?!length$)/', $name ) ) {
227 // Only allow content-* and x-content-* headers (but not content-length)
228 $contentHeaders[$name] = $value;
229 } elseif ( $name === 'content-type' && strlen( $value ) ) {
230 // This header can be set to a value but not unset
231 $contentHeaders[$name] = $value;
232 }
233 }
234 // By default, Swift has annoyingly low maximum header value limits
235 if ( isset( $contentHeaders['content-disposition'] ) ) {
236 $maxLength = 255;
237 // @note: assume FileBackend::makeContentDisposition() already used
238 $offset = $maxLength - strlen( $contentHeaders['content-disposition'] );
239 if ( $offset < 0 ) {
240 $pos = strrpos( $contentHeaders['content-disposition'], ';', $offset );
241 $contentHeaders['content-disposition'] = $pos === false
242 ? ''
243 : trim( substr( $contentHeaders['content-disposition'], 0, $pos ) );
244 }
245 }
246
247 return $contentHeaders;
248 }
249
255 protected function extractMetadataHeaders( array $headers ) {
256 $metadataHeaders = [];
257 foreach ( $headers as $name => $value ) {
258 $name = strtolower( $name );
259 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
260 $metadataHeaders[$name] = $value;
261 }
262 }
263
264 return $metadataHeaders;
265 }
266
272 protected function getMetadataFromHeaders( array $headers ) {
273 $prefixLen = strlen( 'x-object-meta-' );
274
275 $metadata = [];
276 foreach ( $this->extractMetadataHeaders( $headers ) as $name => $value ) {
277 $metadata[substr( $name, $prefixLen )] = $value;
278 }
279
280 return $metadata;
281 }
282
283 protected function doCreateInternal( array $params ) {
284 $status = $this->newStatus();
285
286 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
287 if ( $dstRel === null ) {
288 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
289
290 return $status;
291 }
292
293 // Headers that are not strictly a function of the file content
294 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] );
295 // Make sure that the "content-type" header is set to something sensible
296 $mutableHeaders['content-type']
297 ??= $this->getContentType( $params['dst'], $params['content'], null );
298
299 $reqs = [ [
300 'method' => 'PUT',
301 'container' => $dstCont,
302 'relPath' => $dstRel,
303 'headers' => array_merge(
304 $mutableHeaders,
305 [
306 'etag' => md5( $params['content'] ),
307 'content-length' => strlen( $params['content'] ),
308 'x-object-meta-sha1base36' =>
309 Wikimedia\base_convert( sha1( $params['content'] ), 16, 36, 31 )
310 ]
311 ),
312 'body' => $params['content']
313 ] ];
314
315 $method = __METHOD__;
316 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
317 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
318 if ( $rcode === 201 || $rcode === 202 ) {
319 // good
320 } elseif ( $rcode === 412 ) {
321 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
322 } else {
323 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
324 }
325
326 return SwiftFileOpHandle::CONTINUE_IF_OK;
327 };
328
329 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
330 if ( !empty( $params['async'] ) ) { // deferred
331 $status->value = $opHandle;
332 } else { // actually write the object in Swift
333 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
334 }
335
336 return $status;
337 }
338
339 protected function doStoreInternal( array $params ) {
340 $status = $this->newStatus();
341
342 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
343 if ( $dstRel === null ) {
344 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
345
346 return $status;
347 }
348
349 // Open a handle to the source file so that it can be streamed. The size and hash
350 // will be computed using the handle. In the off chance that the source file changes
351 // during this operation, the PUT will fail due to an ETag mismatch and be aborted.
352 AtEase::suppressWarnings();
353 $srcHandle = fopen( $params['src'], 'rb' );
354 AtEase::restoreWarnings();
355 if ( $srcHandle === false ) { // source doesn't exist?
356 $status->fatal( 'backend-fail-notexists', $params['src'] );
357
358 return $status;
359 }
360
361 // Compute the MD5 and SHA-1 hashes in one pass
362 $srcSize = fstat( $srcHandle )['size'];
363 $md5Context = hash_init( 'md5' );
364 $sha1Context = hash_init( 'sha1' );
365 $hashDigestSize = 0;
366 while ( !feof( $srcHandle ) ) {
367 $buffer = (string)fread( $srcHandle, 131_072 ); // 128 KiB
368 hash_update( $md5Context, $buffer );
369 hash_update( $sha1Context, $buffer );
370 $hashDigestSize += strlen( $buffer );
371 }
372 // Reset the handle back to the beginning so that it can be streamed
373 rewind( $srcHandle );
374
375 if ( $hashDigestSize !== $srcSize ) {
376 $status->fatal( 'backend-fail-hash', $params['src'] );
377
378 return $status;
379 }
380
381 // Headers that are not strictly a function of the file content
382 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] );
383 // Make sure that the "content-type" header is set to something sensible
384 $mutableHeaders['content-type']
385 ??= $this->getContentType( $params['dst'], null, $params['src'] );
386
387 $reqs = [ [
388 'method' => 'PUT',
389 'container' => $dstCont,
390 'relPath' => $dstRel,
391 'headers' => array_merge(
392 $mutableHeaders,
393 [
394 'content-length' => $srcSize,
395 'etag' => hash_final( $md5Context ),
396 'x-object-meta-sha1base36' =>
397 Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
398 ]
399 ),
400 'body' => $srcHandle // resource
401 ] ];
402
403 $method = __METHOD__;
404 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
405 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
406 if ( $rcode === 201 || $rcode === 202 ) {
407 // good
408 } elseif ( $rcode === 412 ) {
409 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
410 } else {
411 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
412 }
413
414 return SwiftFileOpHandle::CONTINUE_IF_OK;
415 };
416
417 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
418 $opHandle->resourcesToClose[] = $srcHandle;
419
420 if ( !empty( $params['async'] ) ) { // deferred
421 $status->value = $opHandle;
422 } else { // actually write the object in Swift
423 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
424 }
425
426 return $status;
427 }
428
429 protected function doCopyInternal( array $params ) {
430 $status = $this->newStatus();
431
432 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
433 if ( $srcRel === null ) {
434 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
435
436 return $status;
437 }
438
439 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
440 if ( $dstRel === null ) {
441 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
442
443 return $status;
444 }
445
446 $reqs = [ [
447 'method' => 'PUT',
448 'container' => $dstCont,
449 'relPath' => $dstRel,
450 'headers' => array_merge(
451 $this->extractMutableContentHeaders( $params['headers'] ?? [] ),
452 [
453 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
454 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
455 ]
456 )
457 ] ];
458
459 $method = __METHOD__;
460 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
461 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
462 if ( $rcode === 201 ) {
463 // good
464 } elseif ( $rcode === 404 ) {
465 if ( empty( $params['ignoreMissingSource'] ) ) {
466 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
467 }
468 } else {
469 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
470 }
471
472 return SwiftFileOpHandle::CONTINUE_IF_OK;
473 };
474
475 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
476 if ( !empty( $params['async'] ) ) { // deferred
477 $status->value = $opHandle;
478 } else { // actually write the object in Swift
479 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
480 }
481
482 return $status;
483 }
484
485 protected function doMoveInternal( array $params ) {
486 $status = $this->newStatus();
487
488 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
489 if ( $srcRel === null ) {
490 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
491
492 return $status;
493 }
494
495 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
496 if ( $dstRel === null ) {
497 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
498
499 return $status;
500 }
501
502 $reqs = [ [
503 'method' => 'PUT',
504 'container' => $dstCont,
505 'relPath' => $dstRel,
506 'headers' => array_merge(
507 $this->extractMutableContentHeaders( $params['headers'] ?? [] ),
508 [
509 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
510 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
511 ]
512 )
513 ] ];
514 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
515 $reqs[] = [
516 'method' => 'DELETE',
517 'container' => $srcCont,
518 'relPath' => $srcRel,
519 'headers' => []
520 ];
521 }
522
523 $method = __METHOD__;
524 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
525 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
526 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
527 // good
528 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
529 // good
530 } elseif ( $rcode === 404 ) {
531 if ( empty( $params['ignoreMissingSource'] ) ) {
532 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
533 } else {
534 // Leave Status as OK but skip the DELETE request
535 return SwiftFileOpHandle::CONTINUE_NO;
536 }
537 } else {
538 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
539 }
540
541 return SwiftFileOpHandle::CONTINUE_IF_OK;
542 };
543
544 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
545 if ( !empty( $params['async'] ) ) { // deferred
546 $status->value = $opHandle;
547 } else { // actually move the object in Swift
548 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
549 }
550
551 return $status;
552 }
553
554 protected function doDeleteInternal( array $params ) {
555 $status = $this->newStatus();
556
557 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
558 if ( $srcRel === null ) {
559 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
560
561 return $status;
562 }
563
564 $reqs = [ [
565 'method' => 'DELETE',
566 'container' => $srcCont,
567 'relPath' => $srcRel,
568 'headers' => []
569 ] ];
570
571 $method = __METHOD__;
572 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
573 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
574 if ( $rcode === 204 ) {
575 // good
576 } elseif ( $rcode === 404 ) {
577 if ( empty( $params['ignoreMissingSource'] ) ) {
578 $status->fatal( 'backend-fail-delete', $params['src'] );
579 }
580 } else {
581 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
582 }
583
584 return SwiftFileOpHandle::CONTINUE_IF_OK;
585 };
586
587 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
588 if ( !empty( $params['async'] ) ) { // deferred
589 $status->value = $opHandle;
590 } else { // actually delete the object in Swift
591 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
592 }
593
594 return $status;
595 }
596
597 protected function doDescribeInternal( array $params ) {
598 $status = $this->newStatus();
599
600 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
601 if ( $srcRel === null ) {
602 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
603
604 return $status;
605 }
606
607 // Fetch the old object headers/metadata...this should be in stat cache by now
608 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
609 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
610 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
611 }
612 if ( !$stat ) {
613 $status->fatal( 'backend-fail-describe', $params['src'] );
614
615 return $status;
616 }
617
618 // Swift object POST clears any prior headers, so merge the new and old headers here.
619 // Also, during, POST, libcurl adds "Content-Type: application/x-www-form-urlencoded"
620 // if "Content-Type" is not set, which would clobber the header value for the object.
621 $oldMetadataHeaders = [];
622 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
623 $oldMetadataHeaders["x-object-meta-$name"] = $value;
624 }
625 $newContentHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] );
626 $oldContentHeaders = $stat['xattr']['headers'];
627
628 $reqs = [ [
629 'method' => 'POST',
630 'container' => $srcCont,
631 'relPath' => $srcRel,
632 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
633 ] ];
634
635 $method = __METHOD__;
636 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
637 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
638 if ( $rcode === 202 ) {
639 // good
640 } elseif ( $rcode === 404 ) {
641 $status->fatal( 'backend-fail-describe', $params['src'] );
642 } else {
643 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
644 }
645 };
646
647 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
648 if ( !empty( $params['async'] ) ) { // deferred
649 $status->value = $opHandle;
650 } else { // actually change the object in Swift
651 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
652 }
653
654 return $status;
655 }
656
660 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
661 $status = $this->newStatus();
662
663 // (a) Check if container already exists
664 $stat = $this->getContainerStat( $fullCont );
665 if ( is_array( $stat ) ) {
666 return $status; // already there
667 } elseif ( $stat === self::RES_ERROR ) {
668 $status->fatal( 'backend-fail-internal', $this->name );
669 $this->logger->error( __METHOD__ . ': cannot get container stat' );
670 } else {
671 // (b) Create container as needed with proper ACLs
672 $params['op'] = 'prepare';
673 $status->merge( $this->createContainer( $fullCont, $params ) );
674 }
675
676 return $status;
677 }
678
679 protected function doSecureInternal( $fullCont, $dir, array $params ) {
680 $status = $this->newStatus();
681 if ( empty( $params['noAccess'] ) ) {
682 return $status; // nothing to do
683 }
684
685 $stat = $this->getContainerStat( $fullCont );
686 if ( is_array( $stat ) ) {
687 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
688 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
689 // Make container private to end-users...
690 $status->merge( $this->setContainerAccess(
691 $fullCont,
694 ) );
695 } elseif ( $stat === self::RES_ABSENT ) {
696 $status->fatal( 'backend-fail-usable', $params['dir'] );
697 } else {
698 $status->fatal( 'backend-fail-internal', $this->name );
699 $this->logger->error( __METHOD__ . ': cannot get container stat' );
700 }
701
702 return $status;
703 }
704
705 protected function doPublishInternal( $fullCont, $dir, array $params ) {
706 $status = $this->newStatus();
707 if ( empty( $params['access'] ) ) {
708 return $status; // nothing to do
709 }
710
711 $stat = $this->getContainerStat( $fullCont );
712 if ( is_array( $stat ) ) {
713 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser, '.r:*' ] );
714 if ( !empty( $params['listing'] ) ) {
715 array_push( $readUsers, '.rlistings' );
716 }
717 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
718
719 // Make container public to end-users...
720 $status->merge( $this->setContainerAccess(
721 $fullCont,
724 ) );
725 } elseif ( $stat === self::RES_ABSENT ) {
726 $status->fatal( 'backend-fail-usable', $params['dir'] );
727 } else {
728 $status->fatal( 'backend-fail-internal', $this->name );
729 $this->logger->error( __METHOD__ . ': cannot get container stat' );
730 }
731
732 return $status;
733 }
734
735 protected function doCleanInternal( $fullCont, $dir, array $params ) {
736 $status = $this->newStatus();
737
738 // Only containers themselves can be removed, all else is virtual
739 if ( $dir != '' ) {
740 return $status; // nothing to do
741 }
742
743 // (a) Check the container
744 $stat = $this->getContainerStat( $fullCont, true );
745 if ( $stat === self::RES_ABSENT ) {
746 return $status; // ok, nothing to do
747 } elseif ( $stat === self::RES_ERROR ) {
748 $status->fatal( 'backend-fail-internal', $this->name );
749 $this->logger->error( __METHOD__ . ': cannot get container stat' );
750 } elseif ( is_array( $stat ) && $stat['count'] == 0 ) {
751 // (b) Delete the container if empty
752 $params['op'] = 'clean';
753 $status->merge( $this->deleteContainer( $fullCont, $params ) );
754 }
755
756 return $status;
757 }
758
759 protected function doGetFileStat( array $params ) {
760 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] + $params;
761 unset( $params['src'] );
762 $stats = $this->doGetFileStatMulti( $params );
763
764 return reset( $stats );
765 }
766
777 protected function convertSwiftDate( $ts, $format = TS_MW ) {
778 try {
779 $timestamp = new MWTimestamp( $ts );
780
781 return $timestamp->getTimestamp( $format );
782 } catch ( TimeoutException $e ) {
783 throw $e;
784 } catch ( Exception $e ) {
785 throw new FileBackendError( $e->getMessage() );
786 }
787 }
788
796 protected function addMissingHashMetadata( array $objHdrs, $path ) {
797 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
798 return $objHdrs; // nothing to do
799 }
800
802 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
803 $this->logger->error( __METHOD__ . ": {path} was not stored with SHA-1 metadata.",
804 [ 'path' => $path ] );
805
806 $objHdrs['x-object-meta-sha1base36'] = false;
807
808 // Find prior custom HTTP headers
809 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
810 // Find prior metadata headers
811 $postHeaders += $this->extractMetadataHeaders( $objHdrs );
812
813 $status = $this->newStatus();
815 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager::LOCK_UW, $status );
816 if ( $status->isOK() ) {
817 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
818 if ( $tmpFile ) {
819 $hash = $tmpFile->getSha1Base36();
820 if ( $hash !== false ) {
821 $objHdrs['x-object-meta-sha1base36'] = $hash;
822 // Merge new SHA1 header into the old ones
823 $postHeaders['x-object-meta-sha1base36'] = $hash;
824 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
825 [ $rcode ] = $this->requestWithAuth( [
826 'method' => 'POST',
827 'container' => $srcCont,
828 'relPath' => $srcRel,
829 'headers' => $postHeaders
830 ] );
831 if ( $rcode >= 200 && $rcode <= 299 ) {
832 $this->deleteFileCache( $path );
833
834 return $objHdrs; // success
835 }
836 }
837 }
838 }
839
840 $this->logger->error( __METHOD__ . ': unable to set SHA-1 metadata for {path}',
841 [ 'path' => $path ] );
842
843 return $objHdrs; // failed
844 }
845
846 protected function doGetFileContentsMulti( array $params ) {
847 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
848 // Blindly create tmp files and stream to them, catching any exception
849 // if the file does not exist. Do not waste time doing file stats here.
850 $reqs = []; // (path => op)
851
852 // Initial dummy values to preserve path order
853 $contents = array_fill_keys( $params['srcs'], self::RES_ERROR );
854 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
855 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
856 if ( $srcRel === null ) {
857 continue; // invalid storage path
858 }
859 // Create a new temporary memory file...
860 $handle = fopen( 'php://temp', 'wb' );
861 if ( $handle ) {
862 $reqs[$path] = [
863 'method' => 'GET',
864 'container' => $srcCont,
865 'relPath' => $srcRel,
866 'headers' => $this->headersFromParams( $params ),
867 'stream' => $handle,
868 ];
869 }
870 }
871
872 $reqs = $this->requestMultiWithAuth(
873 $reqs,
874 [ 'maxConnsPerHost' => $params['concurrency'] ]
875 );
876 foreach ( $reqs as $path => $op ) {
877 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
878 if ( $rcode >= 200 && $rcode <= 299 ) {
879 rewind( $op['stream'] ); // start from the beginning
880 $content = (string)stream_get_contents( $op['stream'] );
881 $size = strlen( $content );
882 // Make sure that stream finished
883 if ( $size === (int)$rhdrs['content-length'] ) {
884 $contents[$path] = $content;
885 } else {
886 $contents[$path] = self::RES_ERROR;
887 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
888 $this->onError( null, __METHOD__,
889 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
890 }
891 } elseif ( $rcode === 404 ) {
892 $contents[$path] = self::RES_ABSENT;
893 } else {
894 $contents[$path] = self::RES_ERROR;
895 $this->onError( null, __METHOD__,
896 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
897 }
898 fclose( $op['stream'] ); // close open handle
899 }
900
901 return $contents;
902 }
903
904 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
905 $prefix = ( $dir == '' ) ? null : "{$dir}/";
906 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
907 if ( $status->isOK() ) {
908 return ( count( $status->value ) ) > 0;
909 }
910
911 return self::RES_ERROR;
912 }
913
921 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
922 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
923 }
924
932 public function getFileListInternal( $fullCont, $dir, array $params ) {
933 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
934 }
935
947 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
948 $dirs = [];
949 if ( $after === INF ) {
950 return $dirs; // nothing more
951 }
952
954 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
955
956 $prefix = ( $dir == '' ) ? null : "{$dir}/";
957 // Non-recursive: only list dirs right under $dir
958 if ( !empty( $params['topOnly'] ) ) {
959 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
960 if ( !$status->isOK() ) {
961 throw new FileBackendError( "Iterator page I/O error." );
962 }
963 $objects = $status->value;
964 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
965 foreach ( $objects as $object ) { // files and directories
966 if ( substr( $object, -1 ) === '/' ) {
967 $dirs[] = $object; // directories end in '/'
968 }
969 }
970 } else {
971 // Recursive: list all dirs under $dir and its subdirs
972 $getParentDir = static function ( $path ) {
973 return ( $path !== null && strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
974 };
975
976 // Get directory from last item of prior page
977 $lastDir = $getParentDir( $after ); // must be first page
978 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
979
980 if ( !$status->isOK() ) {
981 throw new FileBackendError( "Iterator page I/O error." );
982 }
983
984 $objects = $status->value;
985
986 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
987 foreach ( $objects as $object ) { // files
988 $objectDir = $getParentDir( $object ); // directory of object
989
990 if ( $objectDir !== false && $objectDir !== $dir ) {
991 // Swift stores paths in UTF-8, using binary sorting.
992 // See function "create_container_table" in common/db.py.
993 // If a directory is not "greater" than the last one,
994 // then it was already listed by the calling iterator.
995 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
996 $pDir = $objectDir;
997 do { // add dir and all its parent dirs
998 $dirs[] = "{$pDir}/";
999 $pDir = $getParentDir( $pDir );
1000 } while ( $pDir !== false
1001 && strcmp( $pDir, $lastDir ) > 0 // not done already
1002 && strlen( $pDir ) > strlen( $dir ) // within $dir
1003 );
1004 }
1005 $lastDir = $objectDir;
1006 }
1007 }
1008 }
1009 // Page on the unfiltered directory listing (what is returned may be filtered)
1010 if ( count( $objects ) < $limit ) {
1011 $after = INF; // avoid a second RTT
1012 } else {
1013 $after = end( $objects ); // update last item
1014 }
1015
1016 return $dirs;
1017 }
1018
1030 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1031 $files = []; // list of (path, stat map or null) entries
1032 if ( $after === INF ) {
1033 return $files; // nothing more
1034 }
1035
1037 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1038
1039 $prefix = ( $dir == '' ) ? null : "{$dir}/";
1040 // $objects will contain a list of unfiltered names or stdClass items
1041 // Non-recursive: only list files right under $dir
1042 if ( !empty( $params['topOnly'] ) ) {
1043 if ( !empty( $params['adviseStat'] ) ) {
1044 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
1045 } else {
1046 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
1047 }
1048 } else {
1049 // Recursive: list all files under $dir and its subdirs
1050 if ( !empty( $params['adviseStat'] ) ) {
1051 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
1052 } else {
1053 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
1054 }
1055 }
1056
1057 // Reformat this list into a list of (name, stat map or null) entries
1058 if ( !$status->isOK() ) {
1059 throw new FileBackendError( "Iterator page I/O error." );
1060 }
1061
1062 $objects = $status->value;
1063 $files = $this->buildFileObjectListing( $objects );
1064
1065 // Page on the unfiltered object listing (what is returned may be filtered)
1066 if ( count( $objects ) < $limit ) {
1067 $after = INF; // avoid a second RTT
1068 } else {
1069 $after = end( $objects ); // update last item
1070 $after = is_object( $after ) ? $after->name : $after;
1071 }
1072
1073 return $files;
1074 }
1075
1083 private function buildFileObjectListing( array $objects ) {
1084 $names = [];
1085 foreach ( $objects as $object ) {
1086 if ( is_object( $object ) ) {
1087 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1088 continue; // virtual directory entry; ignore
1089 }
1090 $stat = [
1091 // Convert various random Swift dates to TS_MW
1092 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
1093 'size' => (int)$object->bytes,
1094 'sha1' => null,
1095 // Note: manifest ETags are not an MD5 of the file
1096 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
1097 'latest' => false // eventually consistent
1098 ];
1099 $names[] = [ $object->name, $stat ];
1100 } elseif ( substr( $object, -1 ) !== '/' ) {
1101 // Omit directories, which end in '/' in listings
1102 $names[] = [ $object, null ];
1103 }
1104 }
1105
1106 return $names;
1107 }
1108
1115 public function loadListingStatInternal( $path, array $val ) {
1116 $this->cheapCache->setField( $path, 'stat', $val );
1117 }
1118
1119 protected function doGetFileXAttributes( array $params ) {
1120 $stat = $this->getFileStat( $params );
1121 // Stat entries filled by file listings don't include metadata/headers
1122 if ( is_array( $stat ) && !isset( $stat['xattr'] ) ) {
1123 $this->clearCache( [ $params['src'] ] );
1124 $stat = $this->getFileStat( $params );
1125 }
1126
1127 if ( is_array( $stat ) ) {
1128 return $stat['xattr'];
1129 }
1130
1131 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1132 }
1133
1134 protected function doGetFileSha1base36( array $params ) {
1135 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1136 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1137 $params['requireSHA1'] = true;
1138
1139 $stat = $this->getFileStat( $params );
1140 if ( is_array( $stat ) ) {
1141 return $stat['sha1'];
1142 }
1143
1144 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1145 }
1146
1147 protected function doStreamFile( array $params ) {
1148 $status = $this->newStatus();
1149
1150 $flags = !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1151
1152 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
1153 if ( $srcRel === null ) {
1154 HTTPFileStreamer::send404Message( $params['src'], $flags );
1155 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1156
1157 return $status;
1158 }
1159
1160 if ( !is_array( $this->getContainerStat( $srcCont ) ) ) {
1161 HTTPFileStreamer::send404Message( $params['src'], $flags );
1162 $status->fatal( 'backend-fail-stream', $params['src'] );
1163
1164 return $status;
1165 }
1166
1167 // If "headers" is set, we only want to send them if the file is there.
1168 // Do not bother checking if the file exists if headers are not set though.
1169 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1170 HTTPFileStreamer::send404Message( $params['src'], $flags );
1171 $status->fatal( 'backend-fail-stream', $params['src'] );
1172
1173 return $status;
1174 }
1175
1176 // Send the requested additional headers
1177 if ( empty( $params['headless'] ) ) {
1178 foreach ( $params['headers'] as $header ) {
1179 $this->header( $header );
1180 }
1181 }
1182
1183 if ( empty( $params['allowOB'] ) ) {
1184 // Cancel output buffering and gzipping if set
1185 $this->resetOutputBuffer();
1186 }
1187
1188 $handle = fopen( 'php://output', 'wb' );
1189 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1190 'method' => 'GET',
1191 'container' => $srcCont,
1192 'relPath' => $srcRel,
1193 'headers' => $this->headersFromParams( $params ) + $params['options'],
1194 'stream' => $handle,
1195 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1196 ] );
1197
1198 if ( $rcode >= 200 && $rcode <= 299 ) {
1199 // good
1200 } elseif ( $rcode === 404 ) {
1201 $status->fatal( 'backend-fail-stream', $params['src'] );
1202 // Per T43113, nasty things can happen if bad cache entries get
1203 // stuck in cache. It's also possible that this error can come up
1204 // with simple race conditions. Clear out the stat cache to be safe.
1205 $this->clearCache( [ $params['src'] ] );
1206 $this->deleteFileCache( $params['src'] );
1207 } else {
1208 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1209 }
1210
1211 return $status;
1212 }
1213
1214 protected function doGetLocalCopyMulti( array $params ) {
1215 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1216 // Blindly create tmp files and stream to them, catching any exception
1217 // if the file does not exist. Do not waste time doing file stats here.
1218 $reqs = []; // (path => op)
1219
1220 // Initial dummy values to preserve path order
1221 $tmpFiles = array_fill_keys( $params['srcs'], self::RES_ERROR );
1222 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1223 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
1224 if ( $srcRel === null ) {
1225 continue; // invalid storage path
1226 }
1227 // Get source file extension
1228 $ext = FileBackend::extensionFromPath( $path );
1229 // Create a new temporary file...
1230 $tmpFile = $this->tmpFileFactory->newTempFSFile( 'localcopy_', $ext );
1231 $handle = $tmpFile ? fopen( $tmpFile->getPath(), 'wb' ) : false;
1232 if ( $handle ) {
1233 $reqs[$path] = [
1234 'method' => 'GET',
1235 'container' => $srcCont,
1236 'relPath' => $srcRel,
1237 'headers' => $this->headersFromParams( $params ),
1238 'stream' => $handle,
1239 ];
1240 $tmpFiles[$path] = $tmpFile;
1241 }
1242 }
1243
1244 // Ceph RADOS Gateway is in use (strong consistency) or X-Newest will be used
1245 $latest = ( $this->isRGW || !empty( $params['latest'] ) );
1246
1247 $reqs = $this->requestMultiWithAuth(
1248 $reqs,
1249 [ 'maxConnsPerHost' => $params['concurrency'] ]
1250 );
1251 foreach ( $reqs as $path => $op ) {
1252 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
1253 fclose( $op['stream'] ); // close open handle
1254 if ( $rcode >= 200 && $rcode <= 299 ) {
1256 $tmpFile = $tmpFiles[$path];
1257 // Make sure that the stream finished and fully wrote to disk
1258 $size = $tmpFile->getSize();
1259 if ( $size !== (int)$rhdrs['content-length'] ) {
1260 $tmpFiles[$path] = self::RES_ERROR;
1261 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1262 $this->onError( null, __METHOD__,
1263 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1264 }
1265 // Set the file stat process cache in passing
1266 $stat = $this->getStatFromHeaders( $rhdrs );
1267 $stat['latest'] = $latest;
1268 $this->cheapCache->setField( $path, 'stat', $stat );
1269 } elseif ( $rcode === 404 ) {
1270 $tmpFiles[$path] = self::RES_ABSENT;
1271 $this->cheapCache->setField(
1272 $path,
1273 'stat',
1274 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
1275 );
1276 } else {
1277 $tmpFiles[$path] = self::RES_ERROR;
1278 $this->onError( null, __METHOD__,
1279 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
1280 }
1281 }
1282
1283 return $tmpFiles;
1284 }
1285
1286 public function getFileHttpUrl( array $params ) {
1287 if ( $this->swiftTempUrlKey != '' ||
1288 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1289 ) {
1290 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
1291 if ( $srcRel === null ) {
1292 return self::TEMPURL_ERROR; // invalid path
1293 }
1294
1295 $auth = $this->getAuthentication();
1296 if ( !$auth ) {
1297 return self::TEMPURL_ERROR;
1298 }
1299
1300 $ttl = $params['ttl'] ?? 86400;
1301 $expires = time() + $ttl;
1302
1303 if ( $this->swiftTempUrlKey != '' ) {
1304 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1305 // Swift wants the signature based on the unencoded object name
1306 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1307 $signature = hash_hmac( 'sha1',
1308 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1309 $this->swiftTempUrlKey
1310 );
1311
1312 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1313 } else { // give S3 API URL for rgw
1314 // Path for signature starts with the bucket
1315 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1316 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1317 // Calculate the hash
1318 $signature = base64_encode( hash_hmac(
1319 'sha1',
1320 "GET\n\n\n{$expires}\n{$spath}",
1321 $this->rgwS3SecretKey,
1322 true // raw
1323 ) );
1324 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1325 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1326 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1327 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1328 '?' .
1329 http_build_query( [
1330 'Signature' => $signature,
1331 'Expires' => $expires,
1332 'AWSAccessKeyId' => $this->rgwS3AccessKey
1333 ] );
1334 }
1335 }
1336
1337 return self::TEMPURL_ERROR;
1338 }
1339
1340 protected function directoriesAreVirtual() {
1341 return true;
1342 }
1343
1352 protected function headersFromParams( array $params ) {
1353 $hdrs = [];
1354 if ( !empty( $params['latest'] ) ) {
1355 $hdrs['x-newest'] = 'true';
1356 }
1357
1358 return $hdrs;
1359 }
1360
1361 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1363 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1364
1366 $statuses = [];
1367
1368 // Split the HTTP requests into stages that can be done concurrently
1369 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1370 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1371 $reqs = $fileOpHandle->httpOp;
1372 foreach ( $reqs as $stage => $req ) {
1373 $httpReqsByStage[$stage][$index] = $req;
1374 }
1375 $statuses[$index] = $this->newStatus();
1376 }
1377
1378 // Run all requests for the first stage, then the next, and so on
1379 $reqCount = count( $httpReqsByStage );
1380 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1381 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1382 foreach ( $httpReqs as $index => $httpReq ) {
1384 $fileOpHandle = $fileOpHandles[$index];
1385 // Run the callback for each request of this operation
1386 $status = $statuses[$index];
1387 ( $fileOpHandle->callback )( $httpReq, $status );
1388 // On failure, abort all remaining requests for this operation. This is used
1389 // in "move" operations to abort the DELETE request if the PUT request fails.
1390 if (
1391 !$status->isOK() ||
1392 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1393 ) {
1394 $stages = count( $fileOpHandle->httpOp );
1395 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1396 unset( $httpReqsByStage[$s][$index] );
1397 }
1398 }
1399 }
1400 }
1401
1402 return $statuses;
1403 }
1404
1427 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1428 $status = $this->newStatus();
1429
1430 [ $rcode, , , , ] = $this->requestWithAuth( [
1431 'method' => 'POST',
1432 'container' => $container,
1433 'headers' => [
1434 'x-container-read' => implode( ',', $readUsers ),
1435 'x-container-write' => implode( ',', $writeUsers )
1436 ]
1437 ] );
1438
1439 if ( $rcode != 204 && $rcode !== 202 ) {
1440 $status->fatal( 'backend-fail-internal', $this->name );
1441 $this->logger->error( __METHOD__ . ': unexpected rcode value ({rcode})',
1442 [ 'rcode' => $rcode ] );
1443 }
1444
1445 return $status;
1446 }
1447
1456 protected function getContainerStat( $container, $bypassCache = false ) {
1458 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1459
1460 if ( $bypassCache ) { // purge cache
1461 $this->containerStatCache->clear( $container );
1462 } elseif ( !$this->containerStatCache->hasField( $container, 'stat' ) ) {
1463 $this->primeContainerCache( [ $container ] ); // check persistent cache
1464 }
1465 if ( !$this->containerStatCache->hasField( $container, 'stat' ) ) {
1466 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1467 'method' => 'HEAD',
1468 'container' => $container
1469 ] );
1470
1471 if ( $rcode === 204 ) {
1472 $stat = [
1473 'count' => $rhdrs['x-container-object-count'],
1474 'bytes' => $rhdrs['x-container-bytes-used']
1475 ];
1476 if ( $bypassCache ) {
1477 return $stat;
1478 } else {
1479 $this->containerStatCache->setField( $container, 'stat', $stat ); // cache it
1480 $this->setContainerCache( $container, $stat ); // update persistent cache
1481 }
1482 } elseif ( $rcode === 404 ) {
1483 return self::RES_ABSENT;
1484 } else {
1485 $this->onError( null, __METHOD__,
1486 [ 'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1487
1488 return self::RES_ERROR;
1489 }
1490 }
1491
1492 return $this->containerStatCache->getField( $container, 'stat' );
1493 }
1494
1502 protected function createContainer( $container, array $params ) {
1503 $status = $this->newStatus();
1504
1505 // @see SwiftFileBackend::setContainerAccess()
1506 if ( empty( $params['noAccess'] ) ) {
1507 // public
1508 $readUsers = array_merge( $this->readUsers, [ '.r:*', $this->swiftUser ] );
1509 if ( empty( $params['noListing'] ) ) {
1510 array_push( $readUsers, '.rlistings' );
1511 }
1512 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1513 } else {
1514 // private
1515 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1516 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1517 }
1518
1519 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1520 'method' => 'PUT',
1521 'container' => $container,
1522 'headers' => [
1523 'x-container-read' => implode( ',', $readUsers ),
1524 'x-container-write' => implode( ',', $writeUsers )
1525 ]
1526 ] );
1527
1528 if ( $rcode === 201 ) { // new
1529 // good
1530 } elseif ( $rcode === 202 ) { // already there
1531 // this shouldn't really happen, but is OK
1532 } else {
1533 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1534 }
1535
1536 return $status;
1537 }
1538
1546 protected function deleteContainer( $container, array $params ) {
1547 $status = $this->newStatus();
1548
1549 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1550 'method' => 'DELETE',
1551 'container' => $container
1552 ] );
1553
1554 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1555 $this->containerStatCache->clear( $container ); // purge
1556 } elseif ( $rcode === 404 ) { // not there
1557 // this shouldn't really happen, but is OK
1558 } elseif ( $rcode === 409 ) { // not empty
1559 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1560 } else {
1561 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1562 }
1563
1564 return $status;
1565 }
1566
1579 private function objectListing(
1580 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1581 ) {
1582 $status = $this->newStatus();
1583
1584 $query = [ 'limit' => $limit ];
1585 if ( $type === 'info' ) {
1586 $query['format'] = 'json';
1587 }
1588 if ( $after !== null ) {
1589 $query['marker'] = $after;
1590 }
1591 if ( $prefix !== null ) {
1592 $query['prefix'] = $prefix;
1593 }
1594 if ( $delim !== null ) {
1595 $query['delimiter'] = $delim;
1596 }
1597
1598 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1599 'method' => 'GET',
1600 'container' => $fullCont,
1601 'query' => $query,
1602 ] );
1603
1604 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1605 if ( $rcode === 200 ) { // good
1606 if ( $type === 'info' ) {
1607 $status->value = FormatJson::decode( trim( $rbody ) );
1608 } else {
1609 $status->value = explode( "\n", trim( $rbody ) );
1610 }
1611 } elseif ( $rcode === 204 ) {
1612 $status->value = []; // empty container
1613 } elseif ( $rcode === 404 ) {
1614 $status->value = []; // no container
1615 } else {
1616 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1617 }
1618
1619 return $status;
1620 }
1621
1622 protected function doPrimeContainerCache( array $containerInfo ) {
1623 foreach ( $containerInfo as $container => $info ) {
1624 $this->containerStatCache->setField( $container, 'stat', $info );
1625 }
1626 }
1627
1628 protected function doGetFileStatMulti( array $params ) {
1629 $stats = [];
1630
1631 $reqs = []; // (path => op)
1632 // (a) Check the containers of the paths...
1633 foreach ( $params['srcs'] as $path ) {
1634 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
1635 if ( $srcRel === null ) {
1636 // invalid storage path
1637 $stats[$path] = self::RES_ERROR;
1638 continue;
1639 }
1640
1641 $cstat = $this->getContainerStat( $srcCont );
1642 if ( $cstat === self::RES_ABSENT ) {
1643 $stats[$path] = self::RES_ABSENT;
1644 continue; // ok, nothing to do
1645 } elseif ( $cstat === self::RES_ERROR ) {
1646 $stats[$path] = self::RES_ERROR;
1647 continue;
1648 }
1649
1650 $reqs[$path] = [
1651 'method' => 'HEAD',
1652 'container' => $srcCont,
1653 'relPath' => $srcRel,
1654 'headers' => $this->headersFromParams( $params )
1655 ];
1656 }
1657
1658 // (b) Check the files themselves...
1659 $reqs = $this->requestMultiWithAuth(
1660 $reqs,
1661 [ 'maxConnsPerHost' => $params['concurrency'] ]
1662 );
1663 foreach ( $reqs as $path => $op ) {
1664 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
1665 if ( $rcode === 200 || $rcode === 204 ) {
1666 // Update the object if it is missing some headers
1667 if ( !empty( $params['requireSHA1'] ) ) {
1668 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1669 }
1670 // Load the stat map from the headers
1671 $stat = $this->getStatFromHeaders( $rhdrs );
1672 if ( $this->isRGW ) {
1673 $stat['latest'] = true; // strong consistency
1674 }
1675 } elseif ( $rcode === 404 ) {
1676 $stat = self::RES_ABSENT;
1677 } else {
1678 $stat = self::RES_ERROR;
1679 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1680 }
1681 $stats[$path] = $stat;
1682 }
1683
1684 return $stats;
1685 }
1686
1691 protected function getStatFromHeaders( array $rhdrs ) {
1692 // Fetch all of the custom metadata headers
1693 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1694 // Fetch all of the custom raw HTTP headers
1695 $headers = $this->extractMutableContentHeaders( $rhdrs );
1696
1697 return [
1698 // Convert various random Swift dates to TS_MW
1699 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1700 // Empty objects actually return no content-length header in Ceph
1701 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1702 'sha1' => $metadata['sha1base36'] ?? null,
1703 // Note: manifest ETags are not an MD5 of the file
1704 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1705 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1706 ];
1707 }
1708
1714 protected function getAuthentication() {
1715 if ( $this->authErrorTimestamp !== null ) {
1716 $interval = time() - $this->authErrorTimestamp;
1717 if ( $interval < 60 ) {
1718 $this->logger->debug(
1719 'rejecting request since auth failure occurred {interval} seconds ago',
1720 [ 'interval' => $interval ]
1721 );
1722 return null;
1723 } else { // actually retry this time
1724 $this->authErrorTimestamp = null;
1725 }
1726 }
1727 // Authenticate with proxy and get a session key...
1728 if ( !$this->authCreds ) {
1729 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1730 $creds = $this->srvCache->get( $cacheKey ); // credentials
1731 // Try to use the credential cache
1732 if ( isset( $creds['auth_token'] )
1733 && isset( $creds['storage_url'] )
1734 && isset( $creds['expiry_time'] )
1735 && $creds['expiry_time'] > time()
1736 ) {
1737 $this->setAuthCreds( $creds );
1738 } else { // cache miss
1739 $this->refreshAuthentication();
1740 }
1741 }
1742
1743 return $this->authCreds;
1744 }
1745
1751 private function setAuthCreds( ?array $creds ) {
1752 $this->logger->debug( 'Using auth token with expiry_time={expiry_time}',
1753 [
1754 'expiry_time' => isset( $creds['expiry_time'] )
1755 ? gmdate( 'c', $creds['expiry_time'] ) : 'null'
1756 ]
1757 );
1758 $this->authCreds = $creds;
1759 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1760 if ( $creds && str_ends_with( $creds['storage_url'], '/v1' ) ) {
1761 $this->isRGW = true; // take advantage of strong consistency in Ceph
1762 }
1763 }
1764
1770 private function refreshAuthentication() {
1771 [ $rcode, , $rhdrs, $rbody, ] = $this->http->run( [
1772 'method' => 'GET',
1773 'url' => "{$this->swiftAuthUrl}/v1.0",
1774 'headers' => [
1775 'x-auth-user' => $this->swiftUser,
1776 'x-auth-key' => $this->swiftKey
1777 ]
1778 ], self::DEFAULT_HTTP_OPTIONS );
1779
1780 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1781 if ( isset( $rhdrs['x-auth-token-expires'] ) ) {
1782 $ttl = intval( $rhdrs['x-auth-token-expires'] );
1783 } else {
1784 $ttl = $this->authTTL;
1785 }
1786 $expiryTime = time() + $ttl;
1787 $creds = [
1788 'auth_token' => $rhdrs['x-auth-token'],
1789 'storage_url' => $this->swiftStorageUrl ?? $rhdrs['x-storage-url'],
1790 'expiry_time' => $expiryTime,
1791 ];
1792 $this->srvCache->set( $this->getCredsCacheKey( $this->swiftUser ), $creds, $expiryTime );
1793 } elseif ( $rcode === 401 ) {
1794 $this->onError( null, __METHOD__, [], "Authentication failed.", $rcode );
1795 $this->authErrorTimestamp = time();
1796 $creds = null;
1797 } else {
1798 $this->onError( null, __METHOD__, [], "HTTP return code: $rcode", $rcode, $rbody );
1799 $this->authErrorTimestamp = time();
1800 $creds = null;
1801 }
1802 $this->setAuthCreds( $creds );
1803 return $creds;
1804 }
1805
1812 protected function storageUrl( array $creds, $container = null, $object = null ) {
1813 $parts = [ $creds['storage_url'] ];
1814 if ( strlen( $container ?? '' ) ) {
1815 $parts[] = rawurlencode( $container );
1816 }
1817 if ( strlen( $object ?? '' ) ) {
1818 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1819 }
1820
1821 return implode( '/', $parts );
1822 }
1823
1828 protected function authTokenHeaders( array $creds ) {
1829 return [ 'x-auth-token' => $creds['auth_token'] ];
1830 }
1831
1838 private function getCredsCacheKey( $username ) {
1839 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1840 }
1841
1856 private function requestWithAuth( array $req, array $options = [] ) {
1857 return $this->requestMultiWithAuth( [ $req ], $options )[0]['response'];
1858 }
1859
1869 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1870 $remainingTries = 2;
1871 $auth = $this->getAuthentication();
1872 while ( true ) {
1873 if ( !$auth ) {
1874 foreach ( $reqs as &$req ) {
1875 if ( !isset( $req['response'] ) ) {
1876 $req['response'] = $this->getAuthFailureResponse();
1877 }
1878 }
1879 break;
1880 }
1881 foreach ( $reqs as &$req ) {
1882 '@phan-var array $req'; // Not array[]
1883 if ( isset( $req['response'] ) ) {
1884 // Request was attempted before
1885 // Retry only if it gave a 401 response code
1886 if ( $req['response']['code'] !== 401 ) {
1887 continue;
1888 }
1889 }
1890 $req['headers'] = $this->authTokenHeaders( $auth ) + ( $req['headers'] ?? [] );
1891 $req['url'] = $this->storageUrl( $auth, $req['container'], $req['relPath'] ?? null );
1892 }
1893 unset( $req );
1894 $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS );
1895 if ( --$remainingTries > 0 ) {
1896 // Retry if any request failed with 401 "not authorized"
1897 foreach ( $reqs as $req ) {
1898 if ( $req['response']['code'] === 401 ) {
1899 $auth = $this->refreshAuthentication();
1900 continue 2;
1901 }
1902 }
1903 }
1904 break;
1905 }
1906 return $reqs;
1907 }
1908
1917 private function getAuthFailureResponse() {
1918 return [
1919 'code' => 0,
1920 0 => 0,
1921 'reason' => '',
1922 1 => '',
1923 'headers' => [],
1924 2 => [],
1925 'body' => '',
1926 3 => '',
1927 'error' => self::AUTH_FAILURE_ERROR,
1928 4 => self::AUTH_FAILURE_ERROR
1929 ];
1930 }
1931
1939 private function isAuthFailureResponse( $code, $error ) {
1940 return $code === 0 && $error === self::AUTH_FAILURE_ERROR;
1941 }
1942
1955 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '', $body = '' ) {
1956 if ( $this->isAuthFailureResponse( $code, $err ) ) {
1957 if ( $status instanceof StatusValue ) {
1958 $status->fatal( 'backend-fail-connect', $this->name );
1959 }
1960 // Already logged
1961 return;
1962 }
1963 if ( $status instanceof StatusValue ) {
1964 $status->fatal( 'backend-fail-internal', $this->name );
1965 }
1966 $msg = "HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1967 $msgParams = [
1968 'code' => $code,
1969 'desc' => $desc,
1970 'func' => $func,
1971 'req_params' => FormatJson::encode( $params ),
1972 ];
1973 if ( $err ) {
1974 $msg .= ': {err}';
1975 $msgParams['err'] = $err;
1976 }
1977 if ( $code == 502 ) {
1978 $msg .= ' ({truncatedBody})';
1979 $msgParams['truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
1980 }
1981 $this->logger->error( $msg, $msgParams );
1982 }
1983}
array $params
The job parameters.
File backend exception for checked exceptions (e.g.
Base class for all backends using particular storage medium.
setContainerCache( $container, array $val)
Set the cached info for a container.
executeOpHandlesInternal(array $fileOpHandles)
Execute a list of FileBackendStoreOpHandle handles in parallel.
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
clearCache(array $paths=null)
Invalidate any in-process file stat and property cache.
primeContainerCache(array $items)
Do a batch lookup from cache for container stats for all containers used in a list of container names...
deleteFileCache( $path)
Delete the cached stat info for a file path.
getContentType( $storagePath, $content, $fsPath)
Get the content type to use in HEAD/GET requests for a file.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
Store key-value entries in a size-limited in-memory LRU cache.
JSON formatter wrapper class.
Library for creating and parsing MW-style timestamps.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Iterator for listing directories.
Iterator for listing regular files.
Class for an OpenStack Swift (or Ceph RGW) based file backend.
string $swiftUser
Swift user (account:user) to authenticate as.
string $swiftAuthUrl
Authentication base URL (without version)
string $swiftTempUrlKey
Shared secret value for making temp URLs.
MapCacheLRU $containerStatCache
Container stat cache.
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path in the backend.
getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params)
Do not call this function outside of SwiftFileBackendFileList.
doPublishInternal( $fullCont, $dir, array $params)
doCreateInternal(array $params)
doGetFileStatMulti(array $params)
Get file stat information (concurrently if possible) for several files.
doGetFileSha1base36(array $params)
int null $authErrorTimestamp
UNIX timestamp.
array $writeUsers
Additional users (account:user) with write permissions on public containers.
__construct(array $config)
MultiHttpClient $http
doGetFileXAttributes(array $params)
authTokenHeaders(array $creds)
getStatFromHeaders(array $rhdrs)
string $swiftStorageUrl
Override of storage base URL.
createContainer( $container, array $params)
Create a Swift container.
doCopyInternal(array $params)
getDirectoryListInternal( $fullCont, $dir, array $params)
string $rgwS3AccessKey
S3 access key (RADOS Gateway)
setContainerAccess( $container, array $readUsers, array $writeUsers)
Set read/write permissions for a Swift container.
getFileHttpUrl(array $params)
array $secureWriteUsers
Additional users (account:user) with write permissions on private containers.
extractMetadataHeaders(array $headers)
int $authTTL
TTL in seconds.
headersFromParams(array $params)
Get headers to send to Swift when reading a file based on a FileBackend params array,...
bool $isRGW
Whether the server is an Ceph RGW.
doStoreInternal(array $params)
onError( $status, $func, array $params, $err='', $code=0, $desc='', $body='')
Log an unexpected exception for this backend.
loadListingStatInternal( $path, array $val)
Do not call this function outside of SwiftFileBackendFileList.
doPrepareInternal( $fullCont, $dir, array $params)
FileBackendStore::doPrepare() to override StatusValue Good status without value for success,...
setLogger(LoggerInterface $logger)
doSecureInternal( $fullCont, $dir, array $params)
getFileListInternal( $fullCont, $dir, array $params)
getMetadataFromHeaders(array $headers)
doMoveInternal(array $params)
addMissingHashMetadata(array $objHdrs, $path)
Fill in any missing object metadata and save it to Swift.
getFeatures()
Get the a bitfield of extra features supported by the backend medium.
deleteContainer( $container, array $params)
Delete a Swift container.
doGetFileStat(array $params)
getAuthentication()
Get the cached auth token.
doGetLocalCopyMulti(array $params)
string $rgwS3SecretKey
S3 authentication key (RADOS Gateway)
doGetFileContentsMulti(array $params)
storageUrl(array $creds, $container=null, $object=null)
convertSwiftDate( $ts, $format=TS_MW)
Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
doStreamFile(array $params)
doPrimeContainerCache(array $containerInfo)
Fill the backend-specific process cache given an array of resolved container names and their correspo...
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
array $readUsers
Additional users (account:user) with read permissions on public containers.
array $secureReadUsers
Additional users (account:user) with read permissions on private containers.
doCleanInternal( $fullCont, $dir, array $params)
getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params)
Do not call this function outside of SwiftFileBackendFileList.
string $swiftKey
Secret key for user.
doDirectoryExists( $fullCont, $dir, array $params)
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
doExecuteOpHandlesInternal(array $fileOpHandles)
doDeleteInternal(array $params)
doDescribeInternal(array $params)
extractMutableContentHeaders(array $headers)
Filter/normalize a header map to only include mutable "content-"/"x-content-" headers.
getContainerStat( $container, $bypassCache=false)
Get a Swift container stat map, possibly from process cache.
Multi-datacenter aware caching interface.
Base class for all file backend classes (including multi-write backends).
string $name
Unique backend name.
getLocalCopy(array $params)
Get a local copy on disk of the file at a storage path in the backend.
newStatus(... $args)
Yields the result of the status wrapper callback on either:
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
Class to handle multiple HTTP requests.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:88
A BagOStuff object with no objects in it.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
$header