32use Psr\Log\LoggerInterface;
35use Wikimedia\AtEase\AtEase;
43use Wikimedia\RequestTimeout\TimeoutException;
55 private const DEFAULT_HTTP_OPTIONS = [
'httpVersion' =>
'v1.1' ];
56 private const AUTH_FAILURE_ERROR =
'Could not connect due to prior authentication failure';
138 parent::__construct( $config );
140 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
141 $this->swiftUser = $config[
'swiftUser'];
142 $this->swiftKey = $config[
'swiftKey'];
144 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
145 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
146 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
147 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
148 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
149 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
153 foreach ( [
'connTimeout',
'reqTimeout' ] as $optionName ) {
154 if ( isset( $config[$optionName] ) ) {
155 $httpOptions[$optionName] = $config[$optionName];
159 $this->http->setLogger( $this->logger );
162 if ( isset( $config[
'wanCache'] ) && $config[
'wanCache'] instanceof
WANObjectCache ) {
163 $this->memCache = $config[
'wanCache'];
166 $this->containerStatCache =
new MapCacheLRU( 300 );
168 if ( !empty( $config[
'cacheAuthInfo'] ) && isset( $config[
'srvCache'] ) ) {
169 $this->srvCache = $config[
'srvCache'];
173 $this->readUsers = $config[
'readUsers'] ?? [];
174 $this->writeUsers = $config[
'writeUsers'] ?? [];
175 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
176 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
181 $this->maxFileSize = 5 * 1024 * 1024 * 1024;
186 $this->http->setLogger(
$logger );
191 self::ATTR_UNICODE_PATHS |
198 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
200 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
204 return $relStoragePath;
209 if ( $rel ===
null ) {
226 $contentHeaders = [];
228 foreach ( $headers as
$name => $value ) {
230 if (
$name ===
'x-delete-at' && is_numeric( $value ) ) {
232 $contentHeaders[
$name] = $value;
233 } elseif (
$name ===
'x-delete-after' && is_numeric( $value ) ) {
235 $contentHeaders[
$name] = $value;
236 } elseif ( preg_match(
'/^(x-)?content-(?!length$)/',
$name ) ) {
238 $contentHeaders[
$name] = $value;
239 } elseif (
$name ===
'content-type' && strlen( $value ) ) {
241 $contentHeaders[
$name] = $value;
245 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
248 $offset = $maxLength - strlen( $contentHeaders[
'content-disposition'] );
250 $pos = strrpos( $contentHeaders[
'content-disposition'],
';', $offset );
251 $contentHeaders[
'content-disposition'] = $pos ===
false
253 : trim( substr( $contentHeaders[
'content-disposition'], 0, $pos ) );
257 return $contentHeaders;
266 $metadataHeaders = [];
267 foreach ( $headers as
$name => $value ) {
269 if ( strpos(
$name,
'x-object-meta-' ) === 0 ) {
270 $metadataHeaders[
$name] = $value;
274 return $metadataHeaders;
283 $prefixLen = strlen(
'x-object-meta-' );
287 $metadata[substr(
$name, $prefixLen )] = $value;
297 if ( $dstRel ===
null ) {
298 $status->fatal(
'backend-fail-invalidpath',
$params[
'dst'] );
306 $mutableHeaders[
'content-type']
311 'container' => $dstCont,
312 'relPath' => $dstRel,
313 'headers' => array_merge(
316 'etag' => md5(
$params[
'content'] ),
317 'content-length' => strlen(
$params[
'content'] ),
318 'x-object-meta-sha1base36' =>
325 $method = __METHOD__;
326 $handler =
function ( array $request,
StatusValue $status ) use ( $method,
$params ) {
327 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
328 if ( $rcode === 201 || $rcode === 202 ) {
330 } elseif ( $rcode === 412 ) {
331 $status->fatal(
'backend-fail-contenttype',
$params[
'dst'] );
333 $this->
onError( $status, $method,
$params, $rerr, $rcode, $rdesc, $rbody );
336 return SwiftFileOpHandle::CONTINUE_IF_OK;
340 if ( !empty(
$params[
'async'] ) ) {
341 $status->value = $opHandle;
353 if ( $dstRel ===
null ) {
354 $status->fatal(
'backend-fail-invalidpath',
$params[
'dst'] );
362 AtEase::suppressWarnings();
363 $srcHandle = fopen(
$params[
'src'],
'rb' );
364 AtEase::restoreWarnings();
365 if ( $srcHandle ===
false ) {
366 $status->fatal(
'backend-fail-notexists',
$params[
'src'] );
372 $srcSize = fstat( $srcHandle )[
'size'];
373 $md5Context = hash_init(
'md5' );
374 $sha1Context = hash_init(
'sha1' );
376 while ( !feof( $srcHandle ) ) {
377 $buffer = (string)fread( $srcHandle, 131_072 );
378 hash_update( $md5Context, $buffer );
379 hash_update( $sha1Context, $buffer );
380 $hashDigestSize += strlen( $buffer );
383 rewind( $srcHandle );
385 if ( $hashDigestSize !== $srcSize ) {
386 $status->fatal(
'backend-fail-hash',
$params[
'src'] );
394 $mutableHeaders[
'content-type']
399 'container' => $dstCont,
400 'relPath' => $dstRel,
401 'headers' => array_merge(
404 'content-length' => $srcSize,
405 'etag' => hash_final( $md5Context ),
406 'x-object-meta-sha1base36' =>
407 \
Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
413 $method = __METHOD__;
414 $handler =
function ( array $request,
StatusValue $status ) use ( $method,
$params ) {
415 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
416 if ( $rcode === 201 || $rcode === 202 ) {
418 } elseif ( $rcode === 412 ) {
419 $status->fatal(
'backend-fail-contenttype',
$params[
'dst'] );
421 $this->
onError( $status, $method,
$params, $rerr, $rcode, $rdesc, $rbody );
424 return SwiftFileOpHandle::CONTINUE_IF_OK;
428 $opHandle->resourcesToClose[] = $srcHandle;
430 if ( !empty(
$params[
'async'] ) ) {
431 $status->value = $opHandle;
443 if ( $srcRel ===
null ) {
444 $status->fatal(
'backend-fail-invalidpath',
$params[
'src'] );
450 if ( $dstRel ===
null ) {
451 $status->fatal(
'backend-fail-invalidpath',
$params[
'dst'] );
458 'container' => $dstCont,
459 'relPath' => $dstRel,
460 'headers' => array_merge(
463 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
464 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
469 $method = __METHOD__;
470 $handler =
function ( array $request,
StatusValue $status ) use ( $method,
$params ) {
471 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
472 if ( $rcode === 201 ) {
474 } elseif ( $rcode === 404 ) {
475 if ( empty(
$params[
'ignoreMissingSource'] ) ) {
476 $status->fatal(
'backend-fail-copy',
$params[
'src'],
$params[
'dst'] );
479 $this->
onError( $status, $method,
$params, $rerr, $rcode, $rdesc, $rbody );
482 return SwiftFileOpHandle::CONTINUE_IF_OK;
486 if ( !empty(
$params[
'async'] ) ) {
487 $status->value = $opHandle;
499 if ( $srcRel ===
null ) {
500 $status->fatal(
'backend-fail-invalidpath',
$params[
'src'] );
506 if ( $dstRel ===
null ) {
507 $status->fatal(
'backend-fail-invalidpath',
$params[
'dst'] );
514 'container' => $dstCont,
515 'relPath' => $dstRel,
516 'headers' => array_merge(
519 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
520 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
524 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
526 'method' =>
'DELETE',
527 'container' => $srcCont,
528 'relPath' => $srcRel,
533 $method = __METHOD__;
534 $handler =
function ( array $request,
StatusValue $status ) use ( $method,
$params ) {
535 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
536 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
538 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
540 } elseif ( $rcode === 404 ) {
541 if ( empty(
$params[
'ignoreMissingSource'] ) ) {
542 $status->fatal(
'backend-fail-move',
$params[
'src'],
$params[
'dst'] );
545 return SwiftFileOpHandle::CONTINUE_NO;
548 $this->
onError( $status, $method,
$params, $rerr, $rcode, $rdesc, $rbody );
551 return SwiftFileOpHandle::CONTINUE_IF_OK;
555 if ( !empty(
$params[
'async'] ) ) {
556 $status->value = $opHandle;
568 if ( $srcRel ===
null ) {
569 $status->fatal(
'backend-fail-invalidpath',
$params[
'src'] );
575 'method' =>
'DELETE',
576 'container' => $srcCont,
577 'relPath' => $srcRel,
581 $method = __METHOD__;
582 $handler =
function ( array $request,
StatusValue $status ) use ( $method,
$params ) {
583 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
584 if ( $rcode === 204 ) {
586 } elseif ( $rcode === 404 ) {
587 if ( empty(
$params[
'ignoreMissingSource'] ) ) {
588 $status->fatal(
'backend-fail-delete',
$params[
'src'] );
591 $this->
onError( $status, $method,
$params, $rerr, $rcode, $rdesc, $rbody );
594 return SwiftFileOpHandle::CONTINUE_IF_OK;
598 if ( !empty(
$params[
'async'] ) ) {
599 $status->value = $opHandle;
611 if ( $srcRel ===
null ) {
612 $status->fatal(
'backend-fail-invalidpath',
$params[
'src'] );
618 $stat = $this->
getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
619 if ( $stat && !isset( $stat[
'xattr'] ) ) {
620 $stat = $this->
doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
623 $status->fatal(
'backend-fail-describe',
$params[
'src'] );
631 $oldMetadataHeaders = [];
632 foreach ( $stat[
'xattr'][
'metadata'] as
$name => $value ) {
633 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
636 $oldContentHeaders = $stat[
'xattr'][
'headers'];
640 'container' => $srcCont,
641 'relPath' => $srcRel,
642 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
645 $method = __METHOD__;
646 $handler =
function ( array $request,
StatusValue $status ) use ( $method,
$params ) {
647 [ $rcode, $rdesc, , $rbody, $rerr ] = $request[
'response'];
648 if ( $rcode === 202 ) {
650 } elseif ( $rcode === 404 ) {
651 $status->fatal(
'backend-fail-describe',
$params[
'src'] );
653 $this->
onError( $status, $method,
$params, $rerr, $rcode, $rdesc, $rbody );
658 if ( !empty(
$params[
'async'] ) ) {
659 $status->value = $opHandle;
675 if ( is_array( $stat ) ) {
677 } elseif ( $stat === self::RES_ERROR ) {
678 $status->fatal(
'backend-fail-internal', $this->name );
679 $this->logger->error( __METHOD__ .
': cannot get container stat' );
691 if ( empty(
$params[
'noAccess'] ) ) {
696 if ( is_array( $stat ) ) {
697 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
698 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
705 } elseif ( $stat === self::RES_ABSENT ) {
706 $status->fatal(
'backend-fail-usable',
$params[
'dir'] );
708 $status->fatal(
'backend-fail-internal', $this->name );
709 $this->logger->error( __METHOD__ .
': cannot get container stat' );
717 if ( empty(
$params[
'access'] ) ) {
722 if ( is_array( $stat ) ) {
723 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
724 if ( !empty(
$params[
'listing'] ) ) {
727 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
735 } elseif ( $stat === self::RES_ABSENT ) {
736 $status->fatal(
'backend-fail-usable',
$params[
'dir'] );
738 $status->fatal(
'backend-fail-internal', $this->name );
739 $this->logger->error( __METHOD__ .
': cannot get container stat' );
755 if ( $stat === self::RES_ABSENT ) {
757 } elseif ( $stat === self::RES_ERROR ) {
758 $status->fatal(
'backend-fail-internal', $this->name );
759 $this->logger->error( __METHOD__ .
': cannot get container stat' );
760 } elseif ( is_array( $stat ) && $stat[
'count'] == 0 ) {
774 return reset( $stats );
791 return $timestamp->getTimestamp( $format );
792 }
catch ( TimeoutException $e ) {
794 }
catch ( Exception $e ) {
807 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
813 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
814 [
'path' =>
$path ] );
816 $objHdrs[
'x-object-meta-sha1base36'] =
false;
826 if ( $status->isOK() ) {
829 $hash = $tmpFile->getSha1Base36();
830 if ( $hash !==
false ) {
831 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
833 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
835 [ $rcode ] = $this->requestWithAuth( [
837 'container' => $srcCont,
838 'relPath' => $srcRel,
839 'headers' => $postHeaders
841 if ( $rcode >= 200 && $rcode <= 299 ) {
850 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
851 [
'path' =>
$path ] );
857 $ep = array_diff_key(
$params, [
'srcs' => 1 ] );
863 $contents = array_fill_keys(
$params[
'srcs'], self::RES_ERROR );
866 if ( $srcRel ===
null ) {
870 $handle = fopen(
'php://temp',
'wb' );
874 'container' => $srcCont,
875 'relPath' => $srcRel,
882 $reqs = $this->requestMultiWithAuth(
884 [
'maxConnsPerHost' =>
$params[
'concurrency'] ]
886 foreach ( $reqs as
$path => $op ) {
887 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
888 if ( $rcode >= 200 && $rcode <= 299 ) {
889 rewind( $op[
'stream'] );
890 $content = (string)stream_get_contents( $op[
'stream'] );
891 $size = strlen( $content );
893 if ( $size === (
int)$rhdrs[
'content-length'] ) {
894 $contents[
$path] = $content;
896 $contents[
$path] = self::RES_ERROR;
897 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
898 $this->
onError(
null, __METHOD__,
899 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
901 } elseif ( $rcode === 404 ) {
902 $contents[
$path] = self::RES_ABSENT;
904 $contents[
$path] = self::RES_ERROR;
905 $this->
onError(
null, __METHOD__,
906 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
908 fclose( $op[
'stream'] );
915 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
916 $status = $this->objectListing( $fullCont,
'names', 1,
null, $prefix );
917 if ( $status->isOK() ) {
918 return ( count( $status->value ) ) > 0;
921 return self::RES_ERROR;
959 if ( $after === INF ) {
966 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
968 if ( !empty(
$params[
'topOnly'] ) ) {
969 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
970 if ( !$status->isOK() ) {
973 $objects = $status->value;
975 foreach ( $objects as $object ) {
976 if ( substr( $object, -1 ) ===
'/' ) {
982 $getParentDir =
static function (
$path ) {
983 return (
$path !==
null && strpos(
$path,
'/' ) !== false ) ? dirname(
$path ) :
false;
987 $lastDir = $getParentDir( $after );
988 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
990 if ( !$status->isOK() ) {
994 $objects = $status->value;
997 foreach ( $objects as $object ) {
998 $objectDir = $getParentDir( $object );
1000 if ( $objectDir !==
false && $objectDir !== $dir ) {
1005 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1008 $dirs[] =
"{$pDir}/";
1009 $pDir = $getParentDir( $pDir );
1010 }
while ( $pDir !==
false
1011 && strcmp( $pDir, $lastDir ) > 0
1012 && strlen( $pDir ) > strlen( $dir )
1015 $lastDir = $objectDir;
1020 if ( count( $objects ) < $limit ) {
1023 $after = end( $objects );
1042 if ( $after === INF ) {
1049 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1052 if ( !empty(
$params[
'topOnly'] ) ) {
1053 if ( !empty(
$params[
'adviseStat'] ) ) {
1054 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1056 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1060 if ( !empty(
$params[
'adviseStat'] ) ) {
1061 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix );
1063 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
1068 if ( !$status->isOK() ) {
1072 $objects = $status->value;
1073 $files = $this->buildFileObjectListing( $objects );
1076 if ( count( $objects ) < $limit ) {
1079 $after = end( $objects );
1080 $after = is_object( $after ) ? $after->name : $after;
1093 private function buildFileObjectListing( array $objects ) {
1095 foreach ( $objects as $object ) {
1096 if ( is_object( $object ) ) {
1097 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1103 'size' => (int)$object->bytes,
1106 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1109 $names[] = [ $object->name, $stat ];
1110 } elseif ( substr( $object, -1 ) !==
'/' ) {
1112 $names[] = [ $object, null ];
1126 $this->cheapCache->setField(
$path,
'stat', $val );
1132 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1137 if ( is_array( $stat ) ) {
1138 return $stat[
'xattr'];
1141 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1147 $params[
'requireSHA1'] =
true;
1150 if ( is_array( $stat ) ) {
1151 return $stat[
'sha1'];
1154 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1163 if ( $srcRel ===
null ) {
1165 $status->fatal(
'backend-fail-invalidpath',
$params[
'src'] );
1172 $status->fatal(
'backend-fail-stream',
$params[
'src'] );
1181 $status->fatal(
'backend-fail-stream',
$params[
'src'] );
1187 if ( empty(
$params[
'headless'] ) ) {
1189 $this->
header( $header );
1193 if ( empty(
$params[
'allowOB'] ) ) {
1198 $handle = fopen(
'php://output',
'wb' );
1199 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1201 'container' => $srcCont,
1202 'relPath' => $srcRel,
1204 'stream' => $handle,
1205 'flags' => [
'relayResponseHeaders' => empty(
$params[
'headless'] ) ]
1208 if ( $rcode >= 200 && $rcode <= 299 ) {
1210 } elseif ( $rcode === 404 ) {
1211 $status->fatal(
'backend-fail-stream',
$params[
'src'] );
1218 $this->
onError( $status, __METHOD__,
$params, $rerr, $rcode, $rdesc, $rbody );
1225 $ep = array_diff_key(
$params, [
'srcs' => 1 ] );
1231 $tmpFiles = array_fill_keys(
$params[
'srcs'], self::RES_ERROR );
1234 if ( $srcRel ===
null ) {
1240 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_', $ext );
1241 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1245 'container' => $srcCont,
1246 'relPath' => $srcRel,
1248 'stream' => $handle,
1250 $tmpFiles[
$path] = $tmpFile;
1255 $latest = ( $this->isRGW || !empty(
$params[
'latest'] ) );
1257 $reqs = $this->requestMultiWithAuth(
1259 [
'maxConnsPerHost' =>
$params[
'concurrency'] ]
1261 foreach ( $reqs as
$path => $op ) {
1262 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1263 fclose( $op[
'stream'] );
1264 if ( $rcode >= 200 && $rcode <= 299 ) {
1266 $tmpFile = $tmpFiles[
$path];
1268 $size = $tmpFile->getSize();
1269 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1270 $tmpFiles[
$path] = self::RES_ERROR;
1271 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1272 $this->
onError(
null, __METHOD__,
1273 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1277 $stat[
'latest'] = $latest;
1278 $this->cheapCache->setField(
$path,
'stat', $stat );
1279 } elseif ( $rcode === 404 ) {
1280 $tmpFiles[
$path] = self::RES_ABSENT;
1281 $this->cheapCache->setField(
1284 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
1287 $tmpFiles[
$path] = self::RES_ERROR;
1288 $this->
onError(
null, __METHOD__,
1289 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
1297 if ( $this->swiftTempUrlKey !=
'' ||
1298 ( $this->rgwS3AccessKey !=
'' && $this->rgwS3SecretKey !=
'' )
1301 if ( $srcRel ===
null ) {
1302 return self::TEMPURL_ERROR;
1307 return self::TEMPURL_ERROR;
1310 $ttl =
$params[
'ttl'] ?? 86400;
1311 $expires = time() + $ttl;
1313 if ( $this->swiftTempUrlKey !=
'' ) {
1316 $contPath = parse_url( $this->
storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1317 $signature = hash_hmac(
'sha1',
1318 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1319 $this->swiftTempUrlKey
1322 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1325 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1326 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1328 $signature = base64_encode( hash_hmac(
1330 "GET\n\n\n{$expires}\n{$spath}",
1331 $this->rgwS3SecretKey,
1337 return str_replace(
'/swift/v1',
'', $this->
storageUrl( $auth ) . $spath ) .
1340 'Signature' => $signature,
1341 'Expires' => $expires,
1342 'AWSAccessKeyId' => $this->rgwS3AccessKey
1347 return self::TEMPURL_ERROR;
1364 if ( !empty(
$params[
'latest'] ) ) {
1365 $hdrs[
'x-newest'] =
'true';
1373 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1379 $httpReqsByStage = [];
1380 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1381 $reqs = $fileOpHandle->httpOp;
1382 foreach ( $reqs as $stage => $req ) {
1383 $httpReqsByStage[$stage][$index] = $req;
1389 $reqCount = count( $httpReqsByStage );
1390 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1391 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1392 foreach ( $httpReqs as $index => $httpReq ) {
1394 $fileOpHandle = $fileOpHandles[$index];
1396 $status = $statuses[$index];
1397 ( $fileOpHandle->callback )( $httpReq, $status );
1402 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1404 $stages = count( $fileOpHandle->httpOp );
1405 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1406 unset( $httpReqsByStage[$s][$index] );
1440 [ $rcode, , , , ] = $this->requestWithAuth( [
1442 'container' => $container,
1444 'x-container-read' => implode(
',',
$readUsers ),
1445 'x-container-write' => implode(
',',
$writeUsers )
1449 if ( $rcode != 204 && $rcode !== 202 ) {
1450 $status->fatal(
'backend-fail-internal', $this->name );
1451 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1452 [
'rcode' => $rcode ] );
1470 if ( $bypassCache ) {
1471 $this->containerStatCache->clear( $container );
1472 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1475 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1476 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1478 'container' => $container
1481 if ( $rcode === 204 ) {
1483 'count' => $rhdrs[
'x-container-object-count'],
1484 'bytes' => $rhdrs[
'x-container-bytes-used']
1486 if ( $bypassCache ) {
1489 $this->containerStatCache->setField( $container,
'stat', $stat );
1492 } elseif ( $rcode === 404 ) {
1493 return self::RES_ABSENT;
1495 $this->
onError(
null, __METHOD__,
1496 [
'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1498 return self::RES_ERROR;
1502 return $this->containerStatCache->getField( $container,
'stat' );
1516 if ( empty(
$params[
'noAccess'] ) ) {
1518 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1519 if ( empty(
$params[
'noListing'] ) ) {
1522 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1525 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1526 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1529 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1531 'container' => $container,
1533 'x-container-read' => implode(
',',
$readUsers ),
1534 'x-container-write' => implode(
',',
$writeUsers )
1538 if ( $rcode === 201 ) {
1540 } elseif ( $rcode === 202 ) {
1543 $this->
onError( $status, __METHOD__,
$params, $rerr, $rcode, $rdesc, $rbody );
1559 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1560 'method' =>
'DELETE',
1561 'container' => $container
1564 if ( $rcode >= 200 && $rcode <= 299 ) {
1565 $this->containerStatCache->clear( $container );
1566 } elseif ( $rcode === 404 ) {
1568 } elseif ( $rcode === 409 ) {
1569 $this->
onError( $status, __METHOD__,
$params, $rerr, $rcode, $rdesc );
1571 $this->
onError( $status, __METHOD__,
$params, $rerr, $rcode, $rdesc, $rbody );
1589 private function objectListing(
1590 $fullCont, $type, $limit, $after =
null, $prefix =
null, $delim =
null
1594 $query = [
'limit' => $limit ];
1595 if ( $type ===
'info' ) {
1596 $query[
'format'] =
'json';
1598 if ( $after !==
null ) {
1599 $query[
'marker'] = $after;
1601 if ( $prefix !==
null ) {
1602 $query[
'prefix'] = $prefix;
1604 if ( $delim !==
null ) {
1605 $query[
'delimiter'] = $delim;
1608 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1610 'container' => $fullCont,
1614 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1615 if ( $rcode === 200 ) {
1616 if ( $type ===
'info' ) {
1617 $status->value = FormatJson::decode( trim( $rbody ) );
1619 $status->value = explode(
"\n", trim( $rbody ) );
1621 } elseif ( $rcode === 204 ) {
1622 $status->value = [];
1623 } elseif ( $rcode === 404 ) {
1624 $status->value = [];
1626 $this->
onError( $status, __METHOD__,
$params, $rerr, $rcode, $rdesc, $rbody );
1633 foreach ( $containerInfo as $container => $info ) {
1634 $this->containerStatCache->setField( $container,
'stat', $info );
1645 if ( $srcRel ===
null ) {
1647 $stats[
$path] = self::RES_ERROR;
1652 if ( $cstat === self::RES_ABSENT ) {
1653 $stats[
$path] = self::RES_ABSENT;
1655 } elseif ( $cstat === self::RES_ERROR ) {
1656 $stats[
$path] = self::RES_ERROR;
1662 'container' => $srcCont,
1663 'relPath' => $srcRel,
1669 $reqs = $this->requestMultiWithAuth(
1671 [
'maxConnsPerHost' =>
$params[
'concurrency'] ]
1673 foreach ( $reqs as
$path => $op ) {
1674 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op[
'response'];
1675 if ( $rcode === 200 || $rcode === 204 ) {
1677 if ( !empty(
$params[
'requireSHA1'] ) ) {
1682 if ( $this->isRGW ) {
1683 $stat[
'latest'] =
true;
1685 } elseif ( $rcode === 404 ) {
1686 $stat = self::RES_ABSENT;
1688 $stat = self::RES_ERROR;
1689 $this->
onError(
null, __METHOD__,
$params, $rerr, $rcode, $rdesc, $rbody );
1691 $stats[
$path] = $stat;
1711 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1712 'sha1' => $metadata[
'sha1base36'] ??
null,
1714 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1715 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1725 if ( $this->authErrorTimestamp !==
null ) {
1727 if ( $interval < 60 ) {
1728 $this->logger->debug(
1729 'rejecting request since auth failure occurred {interval} seconds ago',
1730 [
'interval' => $interval ]
1734 $this->authErrorTimestamp =
null;
1738 if ( !$this->authCreds ) {
1739 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1740 $creds = $this->srvCache->get( $cacheKey );
1742 if ( isset( $creds[
'auth_token'] )
1743 && isset( $creds[
'storage_url'] )
1744 && isset( $creds[
'expiry_time'] )
1745 && $creds[
'expiry_time'] > time()
1747 $this->setAuthCreds( $creds );
1749 $this->refreshAuthentication();
1761 private function setAuthCreds( ?array $creds ) {
1762 $this->logger->debug(
'Using auth token with expiry_time={expiry_time}',
1764 'expiry_time' => isset( $creds[
'expiry_time'] )
1765 ? gmdate(
'c', $creds[
'expiry_time'] ) :
'null'
1768 $this->authCreds = $creds;
1770 if ( $creds && str_ends_with( $creds[
'storage_url'],
'/v1' ) ) {
1771 $this->isRGW =
true;
1780 private function refreshAuthentication() {
1781 [ $rcode, , $rhdrs, $rbody, ] = $this->http->run( [
1783 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1785 'x-auth-user' => $this->swiftUser,
1786 'x-auth-key' => $this->swiftKey
1788 ], self::DEFAULT_HTTP_OPTIONS );
1790 if ( $rcode >= 200 && $rcode <= 299 ) {
1791 if ( isset( $rhdrs[
'x-auth-token-expires'] ) ) {
1792 $ttl = intval( $rhdrs[
'x-auth-token-expires'] );
1796 $expiryTime = time() + $ttl;
1798 'auth_token' => $rhdrs[
'x-auth-token'],
1799 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url'],
1800 'expiry_time' => $expiryTime,
1802 $this->srvCache->set( $this->getCredsCacheKey( $this->swiftUser ), $creds, $expiryTime );
1803 } elseif ( $rcode === 401 ) {
1804 $this->
onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1805 $this->authErrorTimestamp = time();
1808 $this->
onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode, $rbody );
1809 $this->authErrorTimestamp = time();
1812 $this->setAuthCreds( $creds );
1822 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1823 $parts = [ $creds[
'storage_url'] ];
1824 if ( strlen( $container ??
'' ) ) {
1825 $parts[] = rawurlencode( $container );
1827 if ( strlen( $object ??
'' ) ) {
1828 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1831 return implode(
'/', $parts );
1839 return [
'x-auth-token' => $creds[
'auth_token'] ];
1848 private function getCredsCacheKey( $username ) {
1849 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1866 private function requestWithAuth( array $req, array $options = [] ) {
1867 return $this->requestMultiWithAuth( [ $req ], $options )[0][
'response'];
1879 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1880 $remainingTries = 2;
1884 foreach ( $reqs as &$req ) {
1885 if ( !isset( $req[
'response'] ) ) {
1886 $req[
'response'] = $this->getAuthFailureResponse();
1891 foreach ( $reqs as &$req ) {
1892 '@phan-var array $req';
1893 if ( isset( $req[
'response'] ) ) {
1896 if ( $req[
'response'][
'code'] !== 401 ) {
1900 $req[
'headers'] = $this->
authTokenHeaders( $auth ) + ( $req[
'headers'] ?? [] );
1901 $req[
'url'] = $this->
storageUrl( $auth, $req[
'container'], $req[
'relPath'] ??
null );
1904 $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS );
1905 if ( --$remainingTries > 0 ) {
1907 foreach ( $reqs as $req ) {
1908 if ( $req[
'response'][
'code'] === 401 ) {
1909 $auth = $this->refreshAuthentication();
1927 private function getAuthFailureResponse() {
1937 'error' => self::AUTH_FAILURE_ERROR,
1938 4 => self::AUTH_FAILURE_ERROR
1949 private function isAuthFailureResponse( $code, $error ) {
1950 return $code === 0 && $error === self::AUTH_FAILURE_ERROR;
1965 public function onError( $status, $func, array
$params, $err =
'', $code = 0, $desc =
'', $body =
'' ) {
1966 if ( $this->isAuthFailureResponse( $code, $err ) ) {
1968 $status->fatal(
'backend-fail-connect', $this->name );
1974 $status->fatal(
'backend-fail-internal', $this->name );
1976 $msg =
"HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1981 'req_params' => FormatJson::encode(
$params ),
1985 $msgParams[
'err'] = $err;
1987 if ( $code == 502 ) {
1988 $msg .=
' ({truncatedBody})';
1989 $msgParams[
'truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
1991 $this->logger->error( $msg, $msgParams );
1996class_alias( SwiftFileBackend::class,
'SwiftFileBackend' );
array $params
The job parameters.
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.