25use Wikimedia\AtEase\AtEase;
119 parent::__construct( $config );
121 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
122 $this->swiftUser = $config[
'swiftUser'];
123 $this->swiftKey = $config[
'swiftKey'];
125 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
126 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
127 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
128 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
129 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
130 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
134 foreach ( [
'connTimeout',
'reqTimeout' ] as $optionName ) {
135 if ( isset( $config[$optionName] ) ) {
136 $httpOptions[$optionName] = $config[$optionName];
142 if ( isset( $config[
'wanCache'] ) && $config[
'wanCache'] instanceof
WANObjectCache ) {
143 $this->memCache = $config[
'wanCache'];
146 $this->containerStatCache =
new MapCacheLRU( 300 );
148 if ( !empty( $config[
'cacheAuthInfo'] ) && isset( $config[
'srvCache'] ) ) {
149 $this->srvCache = $config[
'srvCache'];
153 $this->readUsers = $config[
'readUsers'] ?? [];
154 $this->writeUsers = $config[
'writeUsers'] ?? [];
155 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
156 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
161 self::ATTR_UNICODE_PATHS |
168 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
170 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
174 return $relStoragePath;
179 if ( $rel ===
null ) {
196 $contentHeaders = [];
198 foreach ( $headers as
$name => $value ) {
200 if ( !preg_match(
'/^(x-)?content-(?!length$)/',
$name ) ) {
203 } elseif (
$name ===
'content-type' && !strlen( $value ) ) {
207 $contentHeaders[
$name] = $value;
210 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
213 foreach ( explode(
';', $contentHeaders[
'content-disposition'] ) as $part ) {
214 $part = trim( $part );
215 $new = ( $disposition ===
'' ) ? $part :
"{$disposition};{$part}";
216 if ( strlen( $new ) <= 255 ) {
222 $contentHeaders[
'content-disposition'] = $disposition;
225 return $contentHeaders;
234 $metadataHeaders = [];
235 foreach ( $headers as
$name => $value ) {
237 if ( strpos(
$name,
'x-object-meta-' ) === 0 ) {
238 $metadataHeaders[
$name] = $value;
242 return $metadataHeaders;
251 $prefixLen = strlen(
'x-object-meta-' );
255 $metadata[substr(
$name, $prefixLen )] = $value;
265 if ( $dstRel ===
null ) {
266 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
274 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
275 ?? $this->
getContentType( $params[
'dst'], $params[
'content'],
null );
279 'url' => [ $dstCont, $dstRel ],
280 'headers' => array_merge(
283 'etag' => md5( $params[
'content'] ),
284 'content-length' => strlen( $params[
'content'] ),
285 'x-object-meta-sha1base36' =>
286 Wikimedia\base_convert( sha1( $params[
'content'] ), 16, 36, 31 )
289 'body' => $params[
'content']
292 $method = __METHOD__;
293 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
294 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
295 if ( $rcode === 201 || $rcode === 202 ) {
297 } elseif ( $rcode === 412 ) {
298 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
300 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
303 return SwiftFileOpHandle::CONTINUE_IF_OK;
307 if ( !empty( $params[
'async'] ) ) {
308 $status->value = $opHandle;
320 if ( $dstRel ===
null ) {
321 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
329 AtEase::suppressWarnings();
330 $srcHandle = fopen( $params[
'src'],
'rb' );
331 AtEase::restoreWarnings();
332 if ( $srcHandle ===
false ) {
333 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
339 $srcSize = fstat( $srcHandle )[
'size'];
340 $md5Context = hash_init(
'md5' );
341 $sha1Context = hash_init(
'sha1' );
343 while ( !feof( $srcHandle ) ) {
344 $buffer = (string)fread( $srcHandle, 131072 );
345 hash_update( $md5Context, $buffer );
346 hash_update( $sha1Context, $buffer );
347 $hashDigestSize += strlen( $buffer );
350 rewind( $srcHandle );
352 if ( $hashDigestSize !== $srcSize ) {
353 $status->fatal(
'backend-fail-hash', $params[
'src'] );
361 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
366 'url' => [ $dstCont, $dstRel ],
367 'headers' => array_merge(
370 'content-length' => $srcSize,
371 'etag' => hash_final( $md5Context ),
372 'x-object-meta-sha1base36' =>
373 Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
379 $method = __METHOD__;
380 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
381 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
382 if ( $rcode === 201 || $rcode === 202 ) {
384 } elseif ( $rcode === 412 ) {
385 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
387 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
390 return SwiftFileOpHandle::CONTINUE_IF_OK;
394 $opHandle->resourcesToClose[] = $srcHandle;
396 if ( !empty( $params[
'async'] ) ) {
397 $status->value = $opHandle;
409 if ( $srcRel ===
null ) {
410 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
416 if ( $dstRel ===
null ) {
417 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
424 'url' => [ $dstCont, $dstRel ],
425 'headers' => array_merge(
428 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
429 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
434 $method = __METHOD__;
435 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
436 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
437 if ( $rcode === 201 ) {
439 } elseif ( $rcode === 404 ) {
440 if ( empty( $params[
'ignoreMissingSource'] ) ) {
441 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
444 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
447 return SwiftFileOpHandle::CONTINUE_IF_OK;
451 if ( !empty( $params[
'async'] ) ) {
452 $status->value = $opHandle;
464 if ( $srcRel ===
null ) {
465 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
471 if ( $dstRel ===
null ) {
472 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
479 'url' => [ $dstCont, $dstRel ],
480 'headers' => array_merge(
483 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
484 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
488 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
490 'method' =>
'DELETE',
491 'url' => [ $srcCont, $srcRel ],
496 $method = __METHOD__;
497 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
498 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
499 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
501 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
503 } elseif ( $rcode === 404 ) {
504 if ( empty( $params[
'ignoreMissingSource'] ) ) {
505 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
508 return SwiftFileOpHandle::CONTINUE_NO;
511 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
514 return SwiftFileOpHandle::CONTINUE_IF_OK;
518 if ( !empty( $params[
'async'] ) ) {
519 $status->value = $opHandle;
531 if ( $srcRel ===
null ) {
532 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
538 'method' =>
'DELETE',
539 'url' => [ $srcCont, $srcRel ],
543 $method = __METHOD__;
544 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
545 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
546 if ( $rcode === 204 ) {
548 } elseif ( $rcode === 404 ) {
549 if ( empty( $params[
'ignoreMissingSource'] ) ) {
550 $status->fatal(
'backend-fail-delete', $params[
'src'] );
553 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
556 return SwiftFileOpHandle::CONTINUE_IF_OK;
560 if ( !empty( $params[
'async'] ) ) {
561 $status->value = $opHandle;
573 if ( $srcRel ===
null ) {
574 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
580 $stat = $this->
getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
581 if ( $stat && !isset( $stat[
'xattr'] ) ) {
582 $stat = $this->
doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
585 $status->fatal(
'backend-fail-describe', $params[
'src'] );
593 $oldMetadataHeaders = [];
594 foreach ( $stat[
'xattr'][
'metadata'] as
$name => $value ) {
595 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
598 $oldContentHeaders = $stat[
'xattr'][
'headers'];
602 'url' => [ $srcCont, $srcRel ],
603 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
606 $method = __METHOD__;
607 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
608 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
609 if ( $rcode === 202 ) {
611 } elseif ( $rcode === 404 ) {
612 $status->fatal(
'backend-fail-describe', $params[
'src'] );
614 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
619 if ( !empty( $params[
'async'] ) ) {
620 $status->value = $opHandle;
633 if ( is_array( $stat ) ) {
635 } elseif ( $stat === self::$RES_ERROR ) {
636 $status->fatal(
'backend-fail-internal', $this->name );
637 $this->logger->error( __METHOD__ .
': cannot get container stat' );
643 if ( $stat ===
false ) {
644 $params[
'op'] =
'prepare';
653 if ( empty( $params[
'noAccess'] ) ) {
658 if ( is_array( $stat ) ) {
659 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
660 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
667 } elseif ( $stat ===
false ) {
668 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
670 $status->fatal(
'backend-fail-internal', $this->name );
671 $this->logger->error( __METHOD__ .
': cannot get container stat' );
681 if ( is_array( $stat ) ) {
682 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
683 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
691 } elseif ( $stat ===
false ) {
692 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
694 $status->fatal(
'backend-fail-internal', $this->name );
695 $this->logger->error( __METHOD__ .
': cannot get container stat' );
711 if ( $stat ===
false ) {
713 } elseif ( !is_array( $stat ) ) {
714 $status->fatal(
'backend-fail-internal', $this->name );
715 $this->logger->error( __METHOD__ .
': cannot get container stat' );
721 if ( $stat[
'count'] == 0 ) {
722 $params[
'op'] =
'clean';
730 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
731 unset( $params[
'src'] );
734 return reset( $stats );
751 return $timestamp->getTimestamp( $format );
752 }
catch ( Exception $e ) {
765 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
771 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
772 [
'path' =>
$path ] );
774 $objHdrs[
'x-object-meta-sha1base36'] =
false;
789 if ( $status->isOK() ) {
792 $hash = $tmpFile->getSha1Base36();
793 if ( $hash !==
false ) {
794 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
796 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
798 list( $rcode ) = $this->http->run( [
800 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
803 if ( $rcode >= 200 && $rcode <= 299 ) {
812 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
813 [
'path' =>
$path ] );
821 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
827 $contents = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
828 foreach ( $params[
'srcs'] as
$path ) {
830 if ( $srcRel ===
null || !$auth ) {
834 $handle = fopen(
'php://temp',
'wb' );
838 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
846 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
847 $reqs = $this->http->runMulti( $reqs, $opts );
848 foreach ( $reqs as
$path => $op ) {
849 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
850 if ( $rcode >= 200 && $rcode <= 299 ) {
851 rewind( $op[
'stream'] );
852 $content = (string)stream_get_contents( $op[
'stream'] );
855 if ( $size === (
int)$rhdrs[
'content-length'] ) {
859 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
860 $this->
onError(
null, __METHOD__,
861 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
863 } elseif ( $rcode === 404 ) {
867 $this->
onError(
null, __METHOD__,
868 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
870 fclose( $op[
'stream'] );
877 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
878 $status = $this->
objectListing( $fullCont,
'names', 1,
null, $prefix );
879 if ( $status->isOK() ) {
880 return ( count( $status->value ) ) > 0;
921 if ( $after === INF ) {
928 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
930 if ( !empty( $params[
'topOnly'] ) ) {
931 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
932 if ( !$status->isOK() ) {
935 $objects = $status->value;
937 foreach ( $objects as $object ) {
938 if ( substr( $object, -1 ) ===
'/' ) {
944 $getParentDir =
function (
$path ) {
945 return ( strpos(
$path,
'/' ) !== false ) ? dirname(
$path ) :
false;
949 $lastDir = $getParentDir( $after );
950 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix );
952 if ( !$status->isOK() ) {
956 $objects = $status->value;
959 foreach ( $objects as $object ) {
960 $objectDir = $getParentDir( $object );
962 if ( $objectDir !==
false && $objectDir !== $dir ) {
967 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
970 $dirs[] =
"{$pDir}/";
971 $pDir = $getParentDir( $pDir );
972 }
while ( $pDir !==
false
973 && strcmp( $pDir, $lastDir ) > 0
974 && strlen( $pDir ) > strlen( $dir )
977 $lastDir = $objectDir;
982 if ( count( $objects ) < $limit ) {
985 $after = end( $objects );
1004 if ( $after === INF ) {
1011 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1014 if ( !empty( $params[
'topOnly'] ) ) {
1015 if ( !empty( $params[
'adviseStat'] ) ) {
1016 $status = $this->
objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1018 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1022 if ( !empty( $params[
'adviseStat'] ) ) {
1023 $status = $this->
objectListing( $fullCont,
'info', $limit, $after, $prefix );
1025 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix );
1030 if ( !$status->isOK() ) {
1034 $objects = $status->value;
1038 if ( count( $objects ) < $limit ) {
1041 $after = end( $objects );
1042 $after = is_object( $after ) ? $after->name : $after;
1057 foreach ( $objects as $object ) {
1058 if ( is_object( $object ) ) {
1059 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1065 'size' => (int)$object->bytes,
1068 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1071 $names[] = [ $object->name, $stat ];
1072 } elseif ( substr( $object, -1 ) !==
'/' ) {
1074 $names[] = [ $object, null ];
1088 $this->cheapCache->setField(
$path,
'stat', $val );
1094 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1099 if ( is_array( $stat ) ) {
1100 return $stat[
'xattr'];
1109 $params[
'requireSHA1'] =
true;
1112 if ( is_array( $stat ) ) {
1113 return $stat[
'sha1'];
1125 if ( $srcRel ===
null ) {
1127 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1135 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1142 if ( $params[
'headers'] && !$this->
fileExists( $params ) ) {
1144 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1150 foreach ( $params[
'headers'] as
$header ) {
1154 if ( empty( $params[
'allowOB'] ) ) {
1159 $handle = fopen(
'php://output',
'wb' );
1160 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1162 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1165 'stream' => $handle,
1166 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1169 if ( $rcode >= 200 && $rcode <= 299 ) {
1171 } elseif ( $rcode === 404 ) {
1172 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1179 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1188 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1194 $tmpFiles = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
1195 foreach ( $params[
'srcs'] as
$path ) {
1197 if ( $srcRel ===
null || !$auth ) {
1203 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_',
$ext );
1204 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1208 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1211 'stream' => $handle,
1213 $tmpFiles[
$path] = $tmpFile;
1218 $latest = ( $this->isRGW || !empty( $params[
'latest'] ) );
1220 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
1221 $reqs = $this->http->runMulti( $reqs, $opts );
1222 foreach ( $reqs as
$path => $op ) {
1223 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1224 fclose( $op[
'stream'] );
1225 if ( $rcode >= 200 && $rcode <= 299 ) {
1227 $tmpFile = $tmpFiles[
$path];
1229 $size = $tmpFile->getSize();
1230 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1232 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1233 $this->
onError(
null, __METHOD__,
1234 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1238 $stat[
'latest'] = $latest;
1239 $this->cheapCache->setField(
$path,
'stat', $stat );
1240 } elseif ( $rcode === 404 ) {
1242 $this->cheapCache->setField(
1249 $this->
onError(
null, __METHOD__,
1250 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1258 if ( $this->swiftTempUrlKey !=
'' ||
1259 ( $this->rgwS3AccessKey !=
'' && $this->rgwS3SecretKey !=
'' )
1262 if ( $srcRel ===
null ) {
1263 return self::TEMPURL_ERROR;
1268 return self::TEMPURL_ERROR;
1271 $ttl = $params[
'ttl'] ?? 86400;
1272 $expires = time() + $ttl;
1274 if ( $this->swiftTempUrlKey !=
'' ) {
1275 $url = $this->
storageUrl( $auth, $srcCont, $srcRel );
1277 $contPath = parse_url( $this->
storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1278 $signature = hash_hmac(
'sha1',
1279 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1280 $this->swiftTempUrlKey
1283 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1286 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1287 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1289 $signature = base64_encode( hash_hmac(
1291 "GET\n\n\n{$expires}\n{$spath}",
1292 $this->rgwS3SecretKey,
1298 return str_replace(
'/swift/v1',
'', $this->
storageUrl( $auth ) . $spath ) .
1301 'Signature' => $signature,
1302 'Expires' => $expires,
1303 'AWSAccessKeyId' => $this->rgwS3AccessKey
1308 return self::TEMPURL_ERROR;
1325 if ( !empty( $params[
'latest'] ) ) {
1326 $hdrs[
'x-newest'] =
'true';
1334 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1341 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1342 $statuses[$index] = $this->
newStatus(
'backend-fail-connect', $this->name );
1349 $httpReqsByStage = [];
1350 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1351 $reqs = $fileOpHandle->httpOp;
1353 foreach ( $reqs as $stage => &$req ) {
1354 list( $container, $relPath ) = $req[
'url'];
1355 $req[
'url'] = $this->
storageUrl( $auth, $container, $relPath );
1356 $req[
'headers'] = $req[
'headers'] ?? [];
1358 $httpReqsByStage[$stage][$index] = $req;
1364 $reqCount = count( $httpReqsByStage );
1365 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1366 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1367 foreach ( $httpReqs as $index => $httpReq ) {
1369 $fileOpHandle = $fileOpHandles[$index];
1371 $status = $statuses[$index];
1372 ( $fileOpHandle->callback )( $httpReq, $status );
1377 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1379 $stages = count( $fileOpHandle->httpOp );
1380 for (
$s = ( $stage + 1 );
$s < $stages; ++
$s ) {
1381 unset( $httpReqsByStage[
$s][$index] );
1417 $status->fatal(
'backend-fail-connect', $this->name );
1422 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1424 'url' => $this->
storageUrl( $auth, $container ),
1426 'x-container-read' => implode(
',',
$readUsers ),
1427 'x-container-write' => implode(
',',
$writeUsers )
1431 if ( $rcode != 204 && $rcode !== 202 ) {
1432 $status->fatal(
'backend-fail-internal', $this->name );
1433 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1434 [
'rcode' => $rcode ] );
1452 if ( $bypassCache ) {
1453 $this->containerStatCache->clear( $container );
1454 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1457 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1463 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1465 'url' => $this->
storageUrl( $auth, $container ),
1469 if ( $rcode === 204 ) {
1471 'count' => $rhdrs[
'x-container-object-count'],
1472 'bytes' => $rhdrs[
'x-container-bytes-used']
1474 if ( $bypassCache ) {
1477 $this->containerStatCache->setField( $container,
'stat', $stat );
1480 } elseif ( $rcode === 404 ) {
1483 $this->
onError(
null, __METHOD__,
1484 [
'cont' => $container ], $rerr, $rcode, $rdesc );
1490 return $this->containerStatCache->getField( $container,
'stat' );
1505 $status->fatal(
'backend-fail-connect', $this->name );
1511 if ( empty( $params[
'noAccess'] ) ) {
1513 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1514 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1517 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1518 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1521 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1523 'url' => $this->
storageUrl( $auth, $container ),
1525 'x-container-read' => implode(
',',
$readUsers ),
1526 'x-container-write' => implode(
',',
$writeUsers )
1530 if ( $rcode === 201 ) {
1532 } elseif ( $rcode === 202 ) {
1535 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1553 $status->fatal(
'backend-fail-connect', $this->name );
1558 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1559 'method' =>
'DELETE',
1560 'url' => $this->
storageUrl( $auth, $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 );
1572 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1591 $fullCont,
$type, $limit, $after =
null, $prefix =
null, $delim =
null
1597 $status->fatal(
'backend-fail-connect', $this->name );
1602 $query = [
'limit' => $limit ];
1603 if (
$type ===
'info' ) {
1604 $query[
'format'] =
'json';
1606 if ( $after !==
null ) {
1607 $query[
'marker'] = $after;
1609 if ( $prefix !==
null ) {
1610 $query[
'prefix'] = $prefix;
1612 if ( $delim !==
null ) {
1613 $query[
'delimiter'] = $delim;
1616 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1618 'url' => $this->
storageUrl( $auth, $fullCont ),
1623 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1624 if ( $rcode === 200 ) {
1625 if (
$type ===
'info' ) {
1626 $status->value = FormatJson::decode( trim( $rbody ) );
1628 $status->value = explode(
"\n", trim( $rbody ) );
1630 } elseif ( $rcode === 204 ) {
1631 $status->value = [];
1632 } elseif ( $rcode === 404 ) {
1633 $status->value = [];
1635 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1642 foreach ( $containerInfo as $container => $info ) {
1643 $this->containerStatCache->setField( $container,
'stat', $info );
1654 foreach ( $params[
'srcs'] as
$path ) {
1656 if ( $srcRel ===
null || !$auth ) {
1662 if ( $cstat === self::$RES_ABSENT ) {
1665 } elseif ( !is_array( $cstat ) ) {
1672 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1678 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
1679 $reqs = $this->http->runMulti( $reqs, $opts );
1680 foreach ( $reqs as
$path => $op ) {
1681 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1682 if ( $rcode === 200 || $rcode === 204 ) {
1684 if ( !empty( $params[
'requireSHA1'] ) ) {
1689 if ( $this->isRGW ) {
1690 $stat[
'latest'] =
true;
1692 } elseif ( $rcode === 404 ) {
1696 $this->
onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1698 $stats[
$path] = $stat;
1718 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1719 'sha1' => $metadata[
'sha1base36'] ??
null,
1721 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1722 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1730 if ( $this->authErrorTimestamp !==
null ) {
1731 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1734 $this->authErrorTimestamp =
null;
1740 if ( !$this->authCreds || $reAuth ) {
1741 $this->authSessionTimestamp = 0;
1743 $creds = $this->srvCache->get( $cacheKey );
1745 if ( isset( $creds[
'auth_token'] ) && isset( $creds[
'storage_url'] ) ) {
1746 $this->authCreds = $creds;
1748 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1750 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1752 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1754 'x-auth-user' => $this->swiftUser,
1755 'x-auth-key' => $this->swiftKey
1759 if ( $rcode >= 200 && $rcode <= 299 ) {
1760 $this->authCreds = [
1761 'auth_token' => $rhdrs[
'x-auth-token'],
1762 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url']
1765 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1766 $this->authSessionTimestamp = time();
1767 } elseif ( $rcode === 401 ) {
1768 $this->
onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1769 $this->authErrorTimestamp = time();
1773 $this->
onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode );
1774 $this->authErrorTimestamp = time();
1780 if ( substr( $this->authCreds[
'storage_url'], -3 ) ===
'/v1' ) {
1781 $this->isRGW =
true;
1794 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1795 $parts = [ $creds[
'storage_url'] ];
1796 if ( strlen( $container ) ) {
1797 $parts[] = rawurlencode( $container );
1799 if ( strlen( $object ) ) {
1800 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1803 return implode(
'/', $parts );
1811 return [
'x-auth-token' => $creds[
'auth_token'] ];
1821 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1835 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'' ) {
1837 $status->fatal(
'backend-fail-internal', $this->name );
1839 if ( $code == 401 ) {
1842 $msg =
"HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1847 'req_params' => FormatJson::encode( $params ),
1851 $msgParams[
'err'] = $err;
1853 $this->logger->error( $msg, $msgParams );
Class representing a cache/ephemeral data store.
A BagOStuff object with no objects in it.
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.
static string $ABSENT_NORMAL
File does not exist according to a normal stat query.
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 Stable to override.
static false $RES_ABSENT
Idiom for "no result due to missing file" (since 1.34)
static null $RES_ERROR
Idiom for "no result due to I/O errors" (since 1.34)
fileExists(array $params)
Check if a file exists at a storage path in the backend.
getLocalCopy(array $params)
Get a local copy on disk of the file at a storage path in the backend.
string $name
Unique backend name.
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
scopedProfileSection( $section)
newStatus(... $args)
Yields the result of the status wrapper callback on either:
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
Library for creating and parsing MW-style timestamps.
Handles a simple LRU key/value map with a maximum number of entries.
Class to handle multiple HTTP requests.
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 Stable to override.
doGetFileSha1base36(array $params)
array $writeUsers
Additional users (account:user) with write permissions on public containers.
__construct(array $config)
doGetFileXAttributes(array $params)
onError( $status, $func, array $params, $err='', $code=0, $desc='')
Log an unexpected exception for this backend.
authTokenHeaders(array $creds)
getStatFromHeaders(array $rhdrs)
string $swiftStorageUrl
Override of storage base URL.
createContainer( $container, array $params)
Create a Swift container.
doCopyInternal(array $params)
getCredsCacheKey( $username)
Get the cache key for a container.
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)
int $authErrorTimestamp
UNIX timestamp.
int $authSessionTimestamp
UNIX timestamp.
loadListingStatInternal( $path, array $val)
Do not call this function outside of SwiftFileBackendFileList.
doPrepareInternal( $fullCont, $dir, array $params)
doSecureInternal( $fullCont, $dir, array $params)
getFileListInternal( $fullCont, $dir, array $params)
getMetadataFromHeaders(array $headers)
doMoveInternal(array $params)
buildFileObjectListing(array $objects)
Build a list of file objects, filtering out any directories and extracting any stat info if provided ...
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 Stable to override.
deleteContainer( $container, array $params)
Delete a Swift container.
doGetFileStat(array $params)
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)
objectListing( $fullCont, $type, $limit, $after=null, $prefix=null, $delim=null)
Get a list of objects under a container.
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 array, possibly from process cache.
Multi-datacenter aware caching interface.
if(!is_readable( $file)) $ext