30use Psr\Log\LoggerInterface;
31use Shellbox\Command\BoxedCommand;
34use Wikimedia\AtEase\AtEase;
42use Wikimedia\RequestTimeout\TimeoutException;
43use Wikimedia\Timestamp\ConvertibleTimestamp;
55 private const DEFAULT_HTTP_OPTIONS = [
'httpVersion' =>
'v1.1' ];
56 private const AUTH_FAILURE_ERROR =
'Could not connect due to prior authentication failure';
147 parent::__construct( $config );
149 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
150 $this->swiftUser = $config[
'swiftUser'];
151 $this->swiftKey = $config[
'swiftKey'];
153 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
154 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
155 $this->canShellboxGetTempUrl = $config[
'canShellboxGetTempUrl'] ??
false;
156 $this->shellboxIpRange = $config[
'shellboxIpRange'] ??
null;
157 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
158 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
159 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
160 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
164 foreach ( [
'connTimeout',
'reqTimeout' ] as $optionName ) {
165 if ( isset( $config[$optionName] ) ) {
166 $httpOptions[$optionName] = $config[$optionName];
170 $this->http->setLogger( $this->logger );
173 if ( isset( $config[
'wanCache'] ) && $config[
'wanCache'] instanceof
WANObjectCache ) {
174 $this->memCache = $config[
'wanCache'];
177 $this->containerStatCache =
new MapCacheLRU( 300 );
179 if ( !empty( $config[
'cacheAuthInfo'] ) && isset( $config[
'srvCache'] ) ) {
180 $this->srvCache = $config[
'srvCache'];
184 $this->readUsers = $config[
'readUsers'] ?? [];
185 $this->writeUsers = $config[
'writeUsers'] ?? [];
186 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
187 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
192 $this->maxFileSize = 5 * 1024 * 1024 * 1024;
197 $this->http->setLogger(
$logger );
202 self::ATTR_UNICODE_PATHS |
209 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
211 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
215 return $relStoragePath;
220 if ( $rel ===
null ) {
237 $contentHeaders = [];
239 foreach ( $headers as
$name => $value ) {
241 if (
$name ===
'x-delete-at' && is_numeric( $value ) ) {
243 $contentHeaders[
$name] = $value;
244 } elseif (
$name ===
'x-delete-after' && is_numeric( $value ) ) {
246 $contentHeaders[
$name] = $value;
247 } elseif ( preg_match(
'/^(x-)?content-(?!length$)/',
$name ) ) {
249 $contentHeaders[
$name] = $value;
250 } elseif (
$name ===
'content-type' && $value !==
'' ) {
252 $contentHeaders[
$name] = $value;
256 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
259 $offset = $maxLength - strlen( $contentHeaders[
'content-disposition'] );
261 $pos = strrpos( $contentHeaders[
'content-disposition'],
';', $offset );
262 $contentHeaders[
'content-disposition'] = $pos ===
false
264 : trim( substr( $contentHeaders[
'content-disposition'], 0, $pos ) );
268 return $contentHeaders;
277 $metadataHeaders = [];
278 foreach ( $headers as
$name => $value ) {
280 if ( strpos(
$name,
'x-object-meta-' ) === 0 ) {
281 $metadataHeaders[
$name] = $value;
285 return $metadataHeaders;
294 $prefixLen = strlen(
'x-object-meta-' );
298 $metadata[substr(
$name, $prefixLen )] = $value;
308 if ( $dstRel ===
null ) {
309 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
317 $mutableHeaders[
'content-type']
318 ??= $this->
getContentType( $params[
'dst'], $params[
'content'],
null );
322 'container' => $dstCont,
323 'relPath' => $dstRel,
324 'headers' => array_merge(
327 'etag' => md5( $params[
'content'] ),
328 'content-length' => strlen( $params[
'content'] ),
329 'x-object-meta-sha1base36' =>
330 \
Wikimedia\base_convert( sha1( $params[
'content'] ), 16, 36, 31 )
333 'body' => $params[
'content']
336 $method = __METHOD__;
337 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
338 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
339 if ( $rcode === 201 || $rcode === 202 ) {
341 } elseif ( $rcode === 412 ) {
342 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
344 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
347 return SwiftFileOpHandle::CONTINUE_IF_OK;
351 if ( !empty( $params[
'async'] ) ) {
352 $status->value = $opHandle;
364 if ( $dstRel ===
null ) {
365 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
373 AtEase::suppressWarnings();
374 $srcHandle = fopen( $params[
'src'],
'rb' );
375 AtEase::restoreWarnings();
376 if ( $srcHandle ===
false ) {
377 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
383 $srcSize = fstat( $srcHandle )[
'size'];
384 $md5Context = hash_init(
'md5' );
385 $sha1Context = hash_init(
'sha1' );
387 while ( !feof( $srcHandle ) ) {
388 $buffer = (string)fread( $srcHandle, 131_072 );
389 hash_update( $md5Context, $buffer );
390 hash_update( $sha1Context, $buffer );
391 $hashDigestSize += strlen( $buffer );
394 rewind( $srcHandle );
396 if ( $hashDigestSize !== $srcSize ) {
397 $status->fatal(
'backend-fail-hash', $params[
'src'] );
405 $mutableHeaders[
'content-type']
406 ??= $this->
getContentType( $params[
'dst'],
null, $params[
'src'] );
410 'container' => $dstCont,
411 'relPath' => $dstRel,
412 'headers' => array_merge(
415 'content-length' => $srcSize,
416 'etag' => hash_final( $md5Context ),
417 'x-object-meta-sha1base36' =>
418 \
Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
424 $method = __METHOD__;
425 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
426 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
427 if ( $rcode === 201 || $rcode === 202 ) {
429 } elseif ( $rcode === 412 ) {
430 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
432 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
435 return SwiftFileOpHandle::CONTINUE_IF_OK;
439 $opHandle->resourcesToClose[] = $srcHandle;
441 if ( !empty( $params[
'async'] ) ) {
442 $status->value = $opHandle;
454 if ( $srcRel ===
null ) {
455 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
461 if ( $dstRel ===
null ) {
462 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
469 'container' => $dstCont,
470 'relPath' => $dstRel,
471 'headers' => array_merge(
474 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
475 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
480 $method = __METHOD__;
481 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
482 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
483 if ( $rcode === 201 ) {
485 } elseif ( $rcode === 404 ) {
486 if ( empty( $params[
'ignoreMissingSource'] ) ) {
487 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
490 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
493 return SwiftFileOpHandle::CONTINUE_IF_OK;
497 if ( !empty( $params[
'async'] ) ) {
498 $status->value = $opHandle;
510 if ( $srcRel ===
null ) {
511 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
517 if ( $dstRel ===
null ) {
518 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
525 'container' => $dstCont,
526 'relPath' => $dstRel,
527 'headers' => array_merge(
530 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
531 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
535 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
537 'method' =>
'DELETE',
538 'container' => $srcCont,
539 'relPath' => $srcRel,
544 $method = __METHOD__;
545 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
546 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
547 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
549 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
551 } elseif ( $rcode === 404 ) {
552 if ( empty( $params[
'ignoreMissingSource'] ) ) {
553 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
556 return SwiftFileOpHandle::CONTINUE_NO;
559 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
562 return SwiftFileOpHandle::CONTINUE_IF_OK;
566 if ( !empty( $params[
'async'] ) ) {
567 $status->value = $opHandle;
579 if ( $srcRel ===
null ) {
580 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
586 'method' =>
'DELETE',
587 'container' => $srcCont,
588 'relPath' => $srcRel,
592 $method = __METHOD__;
593 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
594 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
595 if ( $rcode === 204 ) {
597 } elseif ( $rcode === 404 ) {
598 if ( empty( $params[
'ignoreMissingSource'] ) ) {
599 $status->fatal(
'backend-fail-delete', $params[
'src'] );
602 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
605 return SwiftFileOpHandle::CONTINUE_IF_OK;
609 if ( !empty( $params[
'async'] ) ) {
610 $status->value = $opHandle;
622 if ( $srcRel ===
null ) {
623 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
629 $stat = $this->
getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
630 if ( $stat && !isset( $stat[
'xattr'] ) ) {
631 $stat = $this->
doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
634 $status->fatal(
'backend-fail-describe', $params[
'src'] );
642 $oldMetadataHeaders = [];
643 foreach ( $stat[
'xattr'][
'metadata'] as
$name => $value ) {
644 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
647 $oldContentHeaders = $stat[
'xattr'][
'headers'];
651 'container' => $srcCont,
652 'relPath' => $srcRel,
653 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
656 $method = __METHOD__;
657 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
658 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
659 if ( $rcode === 202 ) {
661 } elseif ( $rcode === 404 ) {
662 $status->fatal(
'backend-fail-describe', $params[
'src'] );
664 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
669 if ( !empty( $params[
'async'] ) ) {
670 $status->value = $opHandle;
686 if ( is_array( $stat ) ) {
688 } elseif ( $stat === self::RES_ERROR ) {
689 $status->fatal(
'backend-fail-internal', $this->name );
690 $this->logger->error( __METHOD__ .
': cannot get container stat' );
693 $params[
'op'] =
'prepare';
702 if ( empty( $params[
'noAccess'] ) ) {
707 if ( is_array( $stat ) ) {
708 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
709 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
716 } elseif ( $stat === self::RES_ABSENT ) {
717 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
719 $status->fatal(
'backend-fail-internal', $this->name );
720 $this->logger->error( __METHOD__ .
': cannot get container stat' );
728 if ( empty( $params[
'access'] ) ) {
733 if ( is_array( $stat ) ) {
734 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
735 if ( !empty( $params[
'listing'] ) ) {
738 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
746 } elseif ( $stat === self::RES_ABSENT ) {
747 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
749 $status->fatal(
'backend-fail-internal', $this->name );
750 $this->logger->error( __METHOD__ .
': cannot get container stat' );
766 if ( $stat === self::RES_ABSENT ) {
768 } elseif ( $stat === self::RES_ERROR ) {
769 $status->fatal(
'backend-fail-internal', $this->name );
770 $this->logger->error( __METHOD__ .
': cannot get container stat' );
771 } elseif ( is_array( $stat ) && $stat[
'count'] == 0 ) {
773 $params[
'op'] =
'clean';
781 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
782 unset( $params[
'src'] );
785 return reset( $stats );
800 $timestamp =
new ConvertibleTimestamp( $ts );
802 return $timestamp->getTimestamp( $format );
803 }
catch ( TimeoutException $e ) {
805 }
catch ( Exception $e ) {
818 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
824 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
825 [
'path' =>
$path ] );
827 $objHdrs[
'x-object-meta-sha1base36'] =
false;
837 if ( $status->isOK() ) {
840 $hash = $tmpFile->getSha1Base36();
841 if ( $hash !==
false ) {
842 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
844 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
846 [ $rcode ] = $this->requestWithAuth( [
848 'container' => $srcCont,
849 'relPath' => $srcRel,
850 'headers' => $postHeaders
852 if ( $rcode >= 200 && $rcode <= 299 ) {
861 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
862 [
'path' =>
$path ] );
868 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
874 $contents = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
875 foreach ( $params[
'srcs'] as
$path ) {
877 if ( $srcRel ===
null ) {
881 $handle = fopen(
'php://temp',
'wb' );
885 'container' => $srcCont,
886 'relPath' => $srcRel,
893 $reqs = $this->requestMultiWithAuth(
895 [
'maxConnsPerHost' => $params[
'concurrency'] ]
897 foreach ( $reqs as
$path => $op ) {
898 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
899 if ( $rcode >= 200 && $rcode <= 299 ) {
900 rewind( $op[
'stream'] );
901 $content = (string)stream_get_contents( $op[
'stream'] );
902 $size = strlen( $content );
904 if ( $size === (
int)$rhdrs[
'content-length'] ) {
905 $contents[
$path] = $content;
907 $contents[
$path] = self::RES_ERROR;
908 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
909 $this->
onError(
null, __METHOD__,
910 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
912 } elseif ( $rcode === 404 ) {
913 $contents[
$path] = self::RES_ABSENT;
915 $contents[
$path] = self::RES_ERROR;
916 $this->
onError(
null, __METHOD__,
917 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
919 fclose( $op[
'stream'] );
926 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
927 $status = $this->objectListing( $fullCont,
'names', 1,
null, $prefix );
928 if ( $status->isOK() ) {
929 return ( count( $status->value ) ) > 0;
932 return self::RES_ERROR;
970 if ( $after === INF ) {
977 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
979 if ( !empty( $params[
'topOnly'] ) ) {
980 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
981 if ( !$status->isOK() ) {
984 $objects = $status->value;
986 foreach ( $objects as $object ) {
987 if ( substr( $object, -1 ) ===
'/' ) {
993 $getParentDir =
static function (
$path ) {
994 return (
$path !==
null && strpos(
$path,
'/' ) !== false ) ? dirname(
$path ) :
false;
998 $lastDir = $getParentDir( $after );
999 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
1001 if ( !$status->isOK() ) {
1005 $objects = $status->value;
1008 foreach ( $objects as $object ) {
1009 $objectDir = $getParentDir( $object );
1011 if ( $objectDir !==
false && $objectDir !== $dir ) {
1016 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1019 $dirs[] =
"{$pDir}/";
1020 $pDir = $getParentDir( $pDir );
1021 }
while ( $pDir !==
false
1022 && strcmp( $pDir, $lastDir ) > 0
1023 && strlen( $pDir ) > strlen( $dir )
1026 $lastDir = $objectDir;
1031 if ( count( $objects ) < $limit ) {
1034 $after = end( $objects );
1053 if ( $after === INF ) {
1060 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1063 if ( !empty( $params[
'topOnly'] ) ) {
1064 if ( !empty( $params[
'adviseStat'] ) ) {
1065 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1067 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1071 if ( !empty( $params[
'adviseStat'] ) ) {
1072 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix );
1074 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
1079 if ( !$status->isOK() ) {
1083 $objects = $status->value;
1084 $files = $this->buildFileObjectListing( $objects );
1087 if ( count( $objects ) < $limit ) {
1090 $after = end( $objects );
1091 $after = is_object( $after ) ? $after->name : $after;
1104 private function buildFileObjectListing( array $objects ) {
1106 foreach ( $objects as $object ) {
1107 if ( is_object( $object ) ) {
1108 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1114 'size' => (int)$object->bytes,
1117 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1120 $names[] = [ $object->name, $stat ];
1121 } elseif ( substr( $object, -1 ) !==
'/' ) {
1123 $names[] = [ $object, null ];
1137 $this->cheapCache->setField(
$path,
'stat', $val );
1143 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1148 if ( is_array( $stat ) ) {
1149 return $stat[
'xattr'];
1152 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1158 $params[
'requireSHA1'] =
true;
1161 if ( is_array( $stat ) ) {
1162 return $stat[
'sha1'];
1165 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1174 if ( $srcRel ===
null ) {
1176 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1183 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1190 if ( $params[
'headers'] && !$this->
fileExists( $params ) ) {
1192 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1198 if ( empty( $params[
'headless'] ) ) {
1199 foreach ( $params[
'headers'] as
$header ) {
1200 $this->
header( $header );
1204 if ( empty( $params[
'allowOB'] ) ) {
1209 $handle = fopen(
'php://output',
'wb' );
1210 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1212 'container' => $srcCont,
1213 'relPath' => $srcRel,
1215 'stream' => $handle,
1216 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1219 if ( $rcode >= 200 && $rcode <= 299 ) {
1221 } elseif ( $rcode === 404 ) {
1222 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1229 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1236 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1242 $tmpFiles = array_fill_keys( $params[
'srcs'], self::RES_ERROR );
1243 foreach ( $params[
'srcs'] as
$path ) {
1245 if ( $srcRel ===
null ) {
1251 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_', $ext );
1252 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1256 'container' => $srcCont,
1257 'relPath' => $srcRel,
1259 'stream' => $handle,
1261 $tmpFiles[
$path] = $tmpFile;
1266 $latest = ( $this->isRGW || !empty( $params[
'latest'] ) );
1268 $reqs = $this->requestMultiWithAuth(
1270 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1272 foreach ( $reqs as
$path => $op ) {
1273 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1274 fclose( $op[
'stream'] );
1275 if ( $rcode >= 200 && $rcode <= 299 ) {
1277 $tmpFile = $tmpFiles[
$path];
1279 $size = $tmpFile->getSize();
1280 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1281 $tmpFiles[
$path] = self::RES_ERROR;
1282 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1283 $this->
onError(
null, __METHOD__,
1284 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1288 $stat[
'latest'] = $latest;
1289 $this->cheapCache->setField(
$path,
'stat', $stat );
1290 } elseif ( $rcode === 404 ) {
1291 $tmpFiles[
$path] = self::RES_ABSENT;
1292 $this->cheapCache->setField(
1295 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
1298 $tmpFiles[
$path] = self::RES_ERROR;
1299 $this->
onError(
null, __METHOD__,
1300 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
1310 if ( $this->canShellboxGetTempUrl ) {
1311 $urlParams = [
'src' => $params[
'src'] ];
1312 if ( $this->shellboxIpRange !==
null ) {
1317 $command->inputFileFromUrl( $boxedName,
$url );
1321 return parent::addShellboxInputFile( $command, $boxedName, $params );
1325 if ( $this->swiftTempUrlKey ==
'' &&
1326 ( $this->rgwS3AccessKey ==
'' || $this->rgwS3SecretKey !=
'' )
1328 $this->logger->debug(
"Can't get Swift file URL: no key available" );
1329 return self::TEMPURL_ERROR;
1333 if ( $srcRel ===
null ) {
1334 $this->logger->debug(
"Can't get Swift file URL: can't resolve path" );
1335 return self::TEMPURL_ERROR;
1340 $this->logger->debug(
"Can't get Swift file URL: authentication failed" );
1341 return self::TEMPURL_ERROR;
1344 $method = $params[
'method'] ??
'GET';
1345 $ttl = $params[
'ttl'] ?? 86400;
1346 $expires = time() + $ttl;
1348 if ( $this->swiftTempUrlKey !=
'' ) {
1351 $contPath = parse_url( $this->
storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1355 "{$contPath}/{$srcRel}"
1358 'temp_url_expires' => $expires,
1360 if ( isset( $params[
'ipRange'] ) ) {
1361 array_unshift( $messageParts,
"ip={$params['ipRange']}" );
1362 $query[
'temp_url_ip_range'] = $params[
'ipRange'];
1365 $signature = hash_hmac(
'sha1',
1366 implode(
"\n", $messageParts ),
1367 $this->swiftTempUrlKey
1369 $query = [
'temp_url_sig' => $signature ] + $query;
1371 return $url .
'?' . http_build_query( $query );
1374 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1375 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1377 $signature = base64_encode( hash_hmac(
1379 "{$method}\n\n\n{$expires}\n{$spath}",
1380 $this->rgwS3SecretKey,
1386 return str_replace(
'/swift/v1',
'', $this->
storageUrl( $auth ) . $spath ) .
1389 'Signature' => $signature,
1390 'Expires' => $expires,
1391 'AWSAccessKeyId' => $this->rgwS3AccessKey
1410 if ( !empty( $params[
'latest'] ) ) {
1411 $hdrs[
'x-newest'] =
'true';
1419 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1425 $httpReqsByStage = [];
1426 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1427 $reqs = $fileOpHandle->httpOp;
1428 foreach ( $reqs as $stage => $req ) {
1429 $httpReqsByStage[$stage][$index] = $req;
1435 $reqCount = count( $httpReqsByStage );
1436 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1437 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1438 foreach ( $httpReqs as $index => $httpReq ) {
1440 $fileOpHandle = $fileOpHandles[$index];
1442 $status = $statuses[$index];
1443 ( $fileOpHandle->callback )( $httpReq, $status );
1448 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1450 $stages = count( $fileOpHandle->httpOp );
1451 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1452 unset( $httpReqsByStage[$s][$index] );
1486 [ $rcode, , , , ] = $this->requestWithAuth( [
1488 'container' => $container,
1490 'x-container-read' => implode(
',',
$readUsers ),
1491 'x-container-write' => implode(
',',
$writeUsers )
1495 if ( $rcode != 204 && $rcode !== 202 ) {
1496 $status->fatal(
'backend-fail-internal', $this->name );
1497 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1498 [
'rcode' => $rcode ] );
1516 if ( $bypassCache ) {
1517 $this->containerStatCache->clear( $container );
1518 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1521 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1522 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1524 'container' => $container
1527 if ( $rcode === 204 ) {
1529 'count' => $rhdrs[
'x-container-object-count'],
1530 'bytes' => $rhdrs[
'x-container-bytes-used']
1532 if ( $bypassCache ) {
1535 $this->containerStatCache->setField( $container,
'stat', $stat );
1538 } elseif ( $rcode === 404 ) {
1539 return self::RES_ABSENT;
1541 $this->
onError(
null, __METHOD__,
1542 [
'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1544 return self::RES_ERROR;
1548 return $this->containerStatCache->getField( $container,
'stat' );
1562 if ( empty( $params[
'noAccess'] ) ) {
1564 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1565 if ( empty( $params[
'noListing'] ) ) {
1568 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1571 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1572 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1575 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1577 'container' => $container,
1579 'x-container-read' => implode(
',',
$readUsers ),
1580 'x-container-write' => implode(
',',
$writeUsers )
1584 if ( $rcode === 201 ) {
1586 } elseif ( $rcode === 202 ) {
1589 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1605 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1606 'method' =>
'DELETE',
1607 'container' => $container
1610 if ( $rcode >= 200 && $rcode <= 299 ) {
1611 $this->containerStatCache->clear( $container );
1612 } elseif ( $rcode === 404 ) {
1614 } elseif ( $rcode === 409 ) {
1615 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1617 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1635 private function objectListing(
1636 $fullCont, $type, $limit, $after =
null, $prefix =
null, $delim =
null
1640 $query = [
'limit' => $limit ];
1641 if ( $type ===
'info' ) {
1642 $query[
'format'] =
'json';
1644 if ( $after !==
null ) {
1645 $query[
'marker'] = $after;
1647 if ( $prefix !==
null ) {
1648 $query[
'prefix'] = $prefix;
1650 if ( $delim !==
null ) {
1651 $query[
'delimiter'] = $delim;
1654 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1656 'container' => $fullCont,
1660 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1661 if ( $rcode === 200 ) {
1662 if ( $type ===
'info' ) {
1663 $status->value = json_decode( trim( $rbody ) );
1665 $status->value = explode(
"\n", trim( $rbody ) );
1667 } elseif ( $rcode === 204 ) {
1668 $status->value = [];
1669 } elseif ( $rcode === 404 ) {
1670 $status->value = [];
1672 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1679 foreach ( $containerInfo as $container => $info ) {
1680 $this->containerStatCache->setField( $container,
'stat', $info );
1689 foreach ( $params[
'srcs'] as
$path ) {
1691 if ( $srcRel ===
null ) {
1693 $stats[
$path] = self::RES_ERROR;
1698 if ( $cstat === self::RES_ABSENT ) {
1699 $stats[
$path] = self::RES_ABSENT;
1701 } elseif ( $cstat === self::RES_ERROR ) {
1702 $stats[
$path] = self::RES_ERROR;
1708 'container' => $srcCont,
1709 'relPath' => $srcRel,
1715 $reqs = $this->requestMultiWithAuth(
1717 [
'maxConnsPerHost' => $params[
'concurrency'] ]
1719 foreach ( $reqs as
$path => $op ) {
1720 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1721 if ( $rcode === 200 || $rcode === 204 ) {
1723 if ( !empty( $params[
'requireSHA1'] ) ) {
1728 if ( $this->isRGW ) {
1729 $stat[
'latest'] =
true;
1731 } elseif ( $rcode === 404 ) {
1732 $stat = self::RES_ABSENT;
1734 $stat = self::RES_ERROR;
1735 $this->
onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1737 $stats[
$path] = $stat;
1757 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1758 'sha1' => $metadata[
'sha1base36'] ??
null,
1760 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1761 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1771 if ( $this->authErrorTimestamp !==
null ) {
1773 if ( $interval < 60 ) {
1774 $this->logger->debug(
1775 'rejecting request since auth failure occurred {interval} seconds ago',
1776 [
'interval' => $interval ]
1780 $this->authErrorTimestamp =
null;
1784 if ( !$this->authCreds ) {
1785 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1786 $creds = $this->srvCache->get( $cacheKey );
1788 if ( isset( $creds[
'auth_token'] )
1789 && isset( $creds[
'storage_url'] )
1790 && isset( $creds[
'expiry_time'] )
1791 && $creds[
'expiry_time'] > time()
1793 $this->setAuthCreds( $creds );
1795 $this->refreshAuthentication();
1807 private function setAuthCreds( ?array $creds ) {
1808 $this->logger->debug(
'Using auth token with expiry_time={expiry_time}',
1810 'expiry_time' => isset( $creds[
'expiry_time'] )
1811 ? gmdate(
'c', $creds[
'expiry_time'] ) :
'null'
1814 $this->authCreds = $creds;
1816 if ( $creds && str_ends_with( $creds[
'storage_url'],
'/v1' ) ) {
1817 $this->isRGW =
true;
1826 private function refreshAuthentication() {
1827 [ $rcode, , $rhdrs, $rbody, ] = $this->http->run( [
1829 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1831 'x-auth-user' => $this->swiftUser,
1832 'x-auth-key' => $this->swiftKey
1834 ], self::DEFAULT_HTTP_OPTIONS );
1836 if ( $rcode >= 200 && $rcode <= 299 ) {
1837 if ( isset( $rhdrs[
'x-auth-token-expires'] ) ) {
1838 $ttl = intval( $rhdrs[
'x-auth-token-expires'] );
1842 $expiryTime = time() + $ttl;
1844 'auth_token' => $rhdrs[
'x-auth-token'],
1845 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url'],
1846 'expiry_time' => $expiryTime,
1848 $this->srvCache->set( $this->getCredsCacheKey( $this->swiftUser ), $creds, $expiryTime );
1849 } elseif ( $rcode === 401 ) {
1850 $this->
onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1851 $this->authErrorTimestamp = time();
1854 $this->
onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode, $rbody );
1855 $this->authErrorTimestamp = time();
1858 $this->setAuthCreds( $creds );
1868 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1869 $parts = [ $creds[
'storage_url'] ];
1870 if ( ( $container ??
'' ) !==
'' ) {
1871 $parts[] = rawurlencode( $container );
1873 if ( ( $object ??
'' ) !==
'' ) {
1874 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1877 return implode(
'/', $parts );
1885 return [
'x-auth-token' => $creds[
'auth_token'] ];
1894 private function getCredsCacheKey( $username ) {
1895 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1912 private function requestWithAuth( array $req, array $options = [] ) {
1913 return $this->requestMultiWithAuth( [ $req ], $options )[0][
'response'];
1925 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1926 $remainingTries = 2;
1930 foreach ( $reqs as &$req ) {
1931 if ( !isset( $req[
'response'] ) ) {
1932 $req[
'response'] = $this->getAuthFailureResponse();
1937 foreach ( $reqs as &$req ) {
1938 '@phan-var array $req';
1939 if ( isset( $req[
'response'] ) ) {
1942 if ( $req[
'response'][
'code'] !== 401 ) {
1946 $req[
'headers'] = $this->
authTokenHeaders( $auth ) + ( $req[
'headers'] ?? [] );
1947 $req[
'url'] = $this->
storageUrl( $auth, $req[
'container'], $req[
'relPath'] ??
null );
1950 $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS );
1951 if ( --$remainingTries > 0 ) {
1953 foreach ( $reqs as $req ) {
1954 if ( $req[
'response'][
'code'] === 401 ) {
1955 $auth = $this->refreshAuthentication();
1973 private function getAuthFailureResponse() {
1983 'error' => self::AUTH_FAILURE_ERROR,
1984 4 => self::AUTH_FAILURE_ERROR
1995 private function isAuthFailureResponse( $code, $error ) {
1996 return $code === 0 && $error === self::AUTH_FAILURE_ERROR;
2011 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'', $body =
'' ) {
2012 if ( $this->isAuthFailureResponse( $code, $err ) ) {
2014 $status->fatal(
'backend-fail-connect', $this->name );
2020 $status->fatal(
'backend-fail-internal', $this->name );
2022 $msg =
"HTTP {code} ({desc}) in '{func}'";
2027 'req_params' => $params,
2031 $msgParams[
'err'] = $err;
2033 if ( $code == 502 ) {
2034 $msg .=
' ({truncatedBody})';
2035 $msgParams[
'truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
2037 $this->logger->error( $msg, $msgParams );
2042class_alias( SwiftFileBackend::class,
'SwiftFileBackend' );
Resource locking handling.
Store key-value entries in a size-limited in-memory LRU cache.
Generic operation result class Has warning/error list, boolean status and arbitrary value.