25use Wikimedia\AtEase\AtEase;
115 parent::__construct( $config );
117 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
118 $this->swiftUser = $config[
'swiftUser'];
119 $this->swiftKey = $config[
'swiftKey'];
121 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
122 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
123 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
124 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
125 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
126 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
130 if ( isset( $config[
'wanCache'] ) && $config[
'wanCache'] instanceof
WANObjectCache ) {
131 $this->memCache = $config[
'wanCache'];
134 $this->containerStatCache =
new MapCacheLRU( 300 );
136 if ( !empty( $config[
'cacheAuthInfo'] ) && isset( $config[
'srvCache'] ) ) {
137 $this->srvCache = $config[
'srvCache'];
141 $this->readUsers = $config[
'readUsers'] ?? [];
142 $this->writeUsers = $config[
'writeUsers'] ?? [];
143 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
144 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
149 self::ATTR_UNICODE_PATHS |
156 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
158 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
162 return $relStoragePath;
167 if ( $rel ===
null ) {
184 $contentHeaders = [];
186 foreach ( $headers as
$name => $value ) {
188 if ( !preg_match(
'/^(x-)?content-(?!length$)/',
$name ) ) {
191 } elseif (
$name ===
'content-type' && !strlen( $value ) ) {
195 $contentHeaders[
$name] = $value;
198 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
201 foreach ( explode(
';', $contentHeaders[
'content-disposition'] ) as $part ) {
202 $part = trim( $part );
203 $new = ( $disposition ===
'' ) ? $part :
"{$disposition};{$part}";
204 if ( strlen( $new ) <= 255 ) {
210 $contentHeaders[
'content-disposition'] = $disposition;
213 return $contentHeaders;
222 $metadataHeaders = [];
223 foreach ( $headers as
$name => $value ) {
225 if ( strpos(
$name,
'x-object-meta-' ) === 0 ) {
226 $metadataHeaders[
$name] = $value;
230 return $metadataHeaders;
239 $prefixLen = strlen(
'x-object-meta-' );
243 $metadata[substr(
$name, $prefixLen )] = $value;
253 if ( $dstRel ===
null ) {
254 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
262 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
263 ?? $this->
getContentType( $params[
'dst'], $params[
'content'],
null );
267 'url' => [ $dstCont, $dstRel ],
268 'headers' => array_merge(
271 'etag' => md5( $params[
'content'] ),
272 'content-length' => strlen( $params[
'content'] ),
273 'x-object-meta-sha1base36' =>
274 Wikimedia\base_convert( sha1( $params[
'content'] ), 16, 36, 31 )
277 'body' => $params[
'content']
280 $method = __METHOD__;
281 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
282 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
283 if ( $rcode === 201 || $rcode === 202 ) {
285 } elseif ( $rcode === 412 ) {
286 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
288 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
291 return SwiftFileOpHandle::CONTINUE_IF_OK;
295 if ( !empty( $params[
'async'] ) ) {
296 $status->value = $opHandle;
308 if ( $dstRel ===
null ) {
309 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
317 AtEase::suppressWarnings();
318 $srcHandle = fopen( $params[
'src'],
'rb' );
319 AtEase::restoreWarnings();
320 if ( $srcHandle ===
false ) {
321 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
327 $srcSize = fstat( $srcHandle )[
'size'];
328 $md5Context = hash_init(
'md5' );
329 $sha1Context = hash_init(
'sha1' );
331 while ( !feof( $srcHandle ) ) {
332 $buffer = (string)fread( $srcHandle, 131072 );
333 hash_update( $md5Context, $buffer );
334 hash_update( $sha1Context, $buffer );
335 $hashDigestSize += strlen( $buffer );
338 rewind( $srcHandle );
340 if ( $hashDigestSize !== $srcSize ) {
341 $status->fatal(
'backend-fail-hash', $params[
'src'] );
349 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
354 'url' => [ $dstCont, $dstRel ],
355 'headers' => array_merge(
358 'content-length' => $srcSize,
359 'etag' => hash_final( $md5Context ),
360 'x-object-meta-sha1base36' =>
361 Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
367 $method = __METHOD__;
368 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
369 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
370 if ( $rcode === 201 || $rcode === 202 ) {
372 } elseif ( $rcode === 412 ) {
373 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
375 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
378 return SwiftFileOpHandle::CONTINUE_IF_OK;
382 $opHandle->resourcesToClose[] = $srcHandle;
384 if ( !empty( $params[
'async'] ) ) {
385 $status->value = $opHandle;
397 if ( $srcRel ===
null ) {
398 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
404 if ( $dstRel ===
null ) {
405 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
412 'url' => [ $dstCont, $dstRel ],
413 'headers' => array_merge(
416 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
417 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
422 $method = __METHOD__;
423 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
424 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
425 if ( $rcode === 201 ) {
427 } elseif ( $rcode === 404 ) {
428 if ( empty( $params[
'ignoreMissingSource'] ) ) {
429 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
432 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
435 return SwiftFileOpHandle::CONTINUE_IF_OK;
439 if ( !empty( $params[
'async'] ) ) {
440 $status->value = $opHandle;
452 if ( $srcRel ===
null ) {
453 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
459 if ( $dstRel ===
null ) {
460 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
467 'url' => [ $dstCont, $dstRel ],
468 'headers' => array_merge(
471 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
472 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
476 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
478 'method' =>
'DELETE',
479 'url' => [ $srcCont, $srcRel ],
484 $method = __METHOD__;
485 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
486 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
487 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
489 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
491 } elseif ( $rcode === 404 ) {
492 if ( empty( $params[
'ignoreMissingSource'] ) ) {
493 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
496 return SwiftFileOpHandle::CONTINUE_NO;
499 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
502 return SwiftFileOpHandle::CONTINUE_IF_OK;
506 if ( !empty( $params[
'async'] ) ) {
507 $status->value = $opHandle;
519 if ( $srcRel ===
null ) {
520 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
526 'method' =>
'DELETE',
527 'url' => [ $srcCont, $srcRel ],
531 $method = __METHOD__;
532 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
533 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
534 if ( $rcode === 204 ) {
536 } elseif ( $rcode === 404 ) {
537 if ( empty( $params[
'ignoreMissingSource'] ) ) {
538 $status->fatal(
'backend-fail-delete', $params[
'src'] );
541 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
544 return SwiftFileOpHandle::CONTINUE_IF_OK;
548 if ( !empty( $params[
'async'] ) ) {
549 $status->value = $opHandle;
561 if ( $srcRel ===
null ) {
562 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
568 $stat = $this->
getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
569 if ( $stat && !isset( $stat[
'xattr'] ) ) {
570 $stat = $this->
doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
573 $status->fatal(
'backend-fail-describe', $params[
'src'] );
581 $oldMetadataHeaders = [];
582 foreach ( $stat[
'xattr'][
'metadata'] as
$name => $value ) {
583 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
586 $oldContentHeaders = $stat[
'xattr'][
'headers'];
590 'url' => [ $srcCont, $srcRel ],
591 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
594 $method = __METHOD__;
595 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
596 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
597 if ( $rcode === 202 ) {
599 } elseif ( $rcode === 404 ) {
600 $status->fatal(
'backend-fail-describe', $params[
'src'] );
602 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
607 if ( !empty( $params[
'async'] ) ) {
608 $status->value = $opHandle;
621 if ( is_array( $stat ) ) {
623 } elseif ( $stat === self::$RES_ERROR ) {
624 $status->fatal(
'backend-fail-internal', $this->name );
625 $this->logger->error( __METHOD__ .
': cannot get container stat' );
631 if ( $stat ===
false ) {
632 $params[
'op'] =
'prepare';
641 if ( empty( $params[
'noAccess'] ) ) {
646 if ( is_array( $stat ) ) {
647 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
648 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
655 } elseif ( $stat ===
false ) {
656 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
658 $status->fatal(
'backend-fail-internal', $this->name );
659 $this->logger->error( __METHOD__ .
': cannot get container stat' );
669 if ( is_array( $stat ) ) {
670 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
671 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
679 } elseif ( $stat ===
false ) {
680 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
682 $status->fatal(
'backend-fail-internal', $this->name );
683 $this->logger->error( __METHOD__ .
': cannot get container stat' );
699 if ( $stat ===
false ) {
701 } elseif ( !is_array( $stat ) ) {
702 $status->fatal(
'backend-fail-internal', $this->name );
703 $this->logger->error( __METHOD__ .
': cannot get container stat' );
709 if ( $stat[
'count'] == 0 ) {
710 $params[
'op'] =
'clean';
718 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
719 unset( $params[
'src'] );
722 return reset( $stats );
739 return $timestamp->getTimestamp( $format );
740 }
catch ( Exception $e ) {
753 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
759 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
760 [
'path' =>
$path ] );
762 $objHdrs[
'x-object-meta-sha1base36'] =
false;
777 if ( $status->isOK() ) {
780 $hash = $tmpFile->getSha1Base36();
781 if ( $hash !==
false ) {
782 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
784 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
786 list( $rcode ) = $this->http->run( [
788 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
791 if ( $rcode >= 200 && $rcode <= 299 ) {
800 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
801 [
'path' =>
$path ] );
809 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
815 $contents = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
816 foreach ( $params[
'srcs'] as
$path ) {
818 if ( $srcRel ===
null || !$auth ) {
822 $handle = fopen(
'php://temp',
'wb' );
826 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
834 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
835 $reqs = $this->http->runMulti( $reqs, $opts );
836 foreach ( $reqs as
$path => $op ) {
837 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
838 if ( $rcode >= 200 && $rcode <= 299 ) {
839 rewind( $op[
'stream'] );
840 $content = (string)stream_get_contents( $op[
'stream'] );
843 if ( $size === (
int)$rhdrs[
'content-length'] ) {
847 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
848 $this->
onError(
null, __METHOD__,
849 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
851 } elseif ( $rcode === 404 ) {
855 $this->
onError(
null, __METHOD__,
856 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
858 fclose( $op[
'stream'] );
865 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
866 $status = $this->
objectListing( $fullCont,
'names', 1,
null, $prefix );
867 if ( $status->isOK() ) {
868 return ( count( $status->value ) ) > 0;
909 if ( $after === INF ) {
916 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
918 if ( !empty( $params[
'topOnly'] ) ) {
919 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
920 if ( !$status->isOK() ) {
923 $objects = $status->value;
925 foreach ( $objects as $object ) {
926 if ( substr( $object, -1 ) ===
'/' ) {
932 $getParentDir =
function (
$path ) {
933 return ( strpos(
$path,
'/' ) !== false ) ? dirname(
$path ) :
false;
937 $lastDir = $getParentDir( $after );
938 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix );
940 if ( !$status->isOK() ) {
944 $objects = $status->value;
947 foreach ( $objects as $object ) {
948 $objectDir = $getParentDir( $object );
950 if ( $objectDir !==
false && $objectDir !== $dir ) {
955 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
958 $dirs[] =
"{$pDir}/";
959 $pDir = $getParentDir( $pDir );
960 }
while ( $pDir !==
false
961 && strcmp( $pDir, $lastDir ) > 0
962 && strlen( $pDir ) > strlen( $dir )
965 $lastDir = $objectDir;
970 if ( count( $objects ) < $limit ) {
973 $after = end( $objects );
992 if ( $after === INF ) {
999 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1002 if ( !empty( $params[
'topOnly'] ) ) {
1003 if ( !empty( $params[
'adviseStat'] ) ) {
1004 $status = $this->
objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1006 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1010 if ( !empty( $params[
'adviseStat'] ) ) {
1011 $status = $this->
objectListing( $fullCont,
'info', $limit, $after, $prefix );
1013 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix );
1018 if ( !$status->isOK() ) {
1022 $objects = $status->value;
1026 if ( count( $objects ) < $limit ) {
1029 $after = end( $objects );
1030 $after = is_object( $after ) ? $after->name : $after;
1045 foreach ( $objects as $object ) {
1046 if ( is_object( $object ) ) {
1047 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1053 'size' => (int)$object->bytes,
1056 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1059 $names[] = [ $object->name, $stat ];
1060 } elseif ( substr( $object, -1 ) !==
'/' ) {
1062 $names[] = [ $object, null ];
1076 $this->cheapCache->setField(
$path,
'stat', $val );
1082 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1087 if ( is_array( $stat ) ) {
1088 return $stat[
'xattr'];
1097 $params[
'requireSHA1'] =
true;
1100 if ( is_array( $stat ) ) {
1101 return $stat[
'sha1'];
1113 if ( $srcRel ===
null ) {
1115 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1123 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1130 if ( $params[
'headers'] && !$this->
fileExists( $params ) ) {
1132 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1138 foreach ( $params[
'headers'] as
$header ) {
1142 if ( empty( $params[
'allowOB'] ) ) {
1147 $handle = fopen(
'php://output',
'wb' );
1148 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1150 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1153 'stream' => $handle,
1154 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1157 if ( $rcode >= 200 && $rcode <= 299 ) {
1159 } elseif ( $rcode === 404 ) {
1160 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1167 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1176 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1182 $tmpFiles = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
1183 foreach ( $params[
'srcs'] as
$path ) {
1185 if ( $srcRel ===
null || !$auth ) {
1191 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_',
$ext );
1192 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1196 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1199 'stream' => $handle,
1201 $tmpFiles[
$path] = $tmpFile;
1206 $latest = ( $this->isRGW || !empty( $params[
'latest'] ) );
1208 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
1209 $reqs = $this->http->runMulti( $reqs, $opts );
1210 foreach ( $reqs as
$path => $op ) {
1211 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1212 fclose( $op[
'stream'] );
1213 if ( $rcode >= 200 && $rcode <= 299 ) {
1215 $tmpFile = $tmpFiles[
$path];
1217 $size = $tmpFile->getSize();
1218 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1220 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1221 $this->
onError(
null, __METHOD__,
1222 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1226 $stat[
'latest'] = $latest;
1227 $this->cheapCache->setField(
$path,
'stat', $stat );
1228 } elseif ( $rcode === 404 ) {
1230 $this->cheapCache->setField(
1237 $this->
onError(
null, __METHOD__,
1238 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1246 if ( $this->swiftTempUrlKey !=
'' ||
1247 ( $this->rgwS3AccessKey !=
'' && $this->rgwS3SecretKey !=
'' )
1250 if ( $srcRel ===
null ) {
1251 return self::TEMPURL_ERROR;
1256 return self::TEMPURL_ERROR;
1259 $ttl = $params[
'ttl'] ?? 86400;
1260 $expires = time() + $ttl;
1262 if ( $this->swiftTempUrlKey !=
'' ) {
1263 $url = $this->
storageUrl( $auth, $srcCont, $srcRel );
1265 $contPath = parse_url( $this->
storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1266 $signature = hash_hmac(
'sha1',
1267 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1268 $this->swiftTempUrlKey
1271 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1274 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1275 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1277 $signature = base64_encode( hash_hmac(
1279 "GET\n\n\n{$expires}\n{$spath}",
1280 $this->rgwS3SecretKey,
1286 return str_replace(
'/swift/v1',
'', $this->
storageUrl( $auth ) . $spath ) .
1289 'Signature' => $signature,
1290 'Expires' => $expires,
1291 'AWSAccessKeyId' => $this->rgwS3AccessKey
1296 return self::TEMPURL_ERROR;
1313 if ( !empty( $params[
'latest'] ) ) {
1314 $hdrs[
'x-newest'] =
'true';
1322 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1329 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1330 $statuses[$index] = $this->
newStatus(
'backend-fail-connect', $this->name );
1337 $httpReqsByStage = [];
1338 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1339 $reqs = $fileOpHandle->httpOp;
1341 foreach ( $reqs as $stage => &$req ) {
1342 list( $container, $relPath ) = $req[
'url'];
1343 $req[
'url'] = $this->
storageUrl( $auth, $container, $relPath );
1344 $req[
'headers'] = $req[
'headers'] ?? [];
1346 $httpReqsByStage[$stage][$index] = $req;
1352 $reqCount = count( $httpReqsByStage );
1353 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1354 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1355 foreach ( $httpReqs as $index => $httpReq ) {
1357 $fileOpHandle = $fileOpHandles[$index];
1359 $status = $statuses[$index];
1360 ( $fileOpHandle->callback )( $httpReq, $status );
1365 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1367 $stages = count( $fileOpHandle->httpOp );
1368 for (
$s = ( $stage + 1 );
$s < $stages; ++
$s ) {
1369 unset( $httpReqsByStage[
$s][$index] );
1405 $status->fatal(
'backend-fail-connect', $this->name );
1410 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1412 'url' => $this->
storageUrl( $auth, $container ),
1414 'x-container-read' => implode(
',',
$readUsers ),
1415 'x-container-write' => implode(
',',
$writeUsers )
1419 if ( $rcode != 204 && $rcode !== 202 ) {
1420 $status->fatal(
'backend-fail-internal', $this->name );
1421 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1422 [
'rcode' => $rcode ] );
1440 if ( $bypassCache ) {
1441 $this->containerStatCache->clear( $container );
1442 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1445 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1451 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1453 'url' => $this->
storageUrl( $auth, $container ),
1457 if ( $rcode === 204 ) {
1459 'count' => $rhdrs[
'x-container-object-count'],
1460 'bytes' => $rhdrs[
'x-container-bytes-used']
1462 if ( $bypassCache ) {
1465 $this->containerStatCache->setField( $container,
'stat', $stat );
1468 } elseif ( $rcode === 404 ) {
1471 $this->
onError(
null, __METHOD__,
1472 [
'cont' => $container ], $rerr, $rcode, $rdesc );
1478 return $this->containerStatCache->getField( $container,
'stat' );
1493 $status->fatal(
'backend-fail-connect', $this->name );
1499 if ( empty( $params[
'noAccess'] ) ) {
1501 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1502 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1505 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1506 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1509 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1511 'url' => $this->
storageUrl( $auth, $container ),
1513 'x-container-read' => implode(
',',
$readUsers ),
1514 'x-container-write' => implode(
',',
$writeUsers )
1518 if ( $rcode === 201 ) {
1520 } elseif ( $rcode === 202 ) {
1523 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1541 $status->fatal(
'backend-fail-connect', $this->name );
1546 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1547 'method' =>
'DELETE',
1548 'url' => $this->
storageUrl( $auth, $container ),
1552 if ( $rcode >= 200 && $rcode <= 299 ) {
1553 $this->containerStatCache->clear( $container );
1554 } elseif ( $rcode === 404 ) {
1556 } elseif ( $rcode === 409 ) {
1557 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1559 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1578 $fullCont,
$type, $limit, $after =
null, $prefix =
null, $delim =
null
1584 $status->fatal(
'backend-fail-connect', $this->name );
1589 $query = [
'limit' => $limit ];
1590 if (
$type ===
'info' ) {
1591 $query[
'format'] =
'json';
1593 if ( $after !==
null ) {
1594 $query[
'marker'] = $after;
1596 if ( $prefix !==
null ) {
1597 $query[
'prefix'] = $prefix;
1599 if ( $delim !==
null ) {
1600 $query[
'delimiter'] = $delim;
1603 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1605 'url' => $this->
storageUrl( $auth, $fullCont ),
1610 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1611 if ( $rcode === 200 ) {
1612 if (
$type ===
'info' ) {
1613 $status->value = FormatJson::decode( trim( $rbody ) );
1615 $status->value = explode(
"\n", trim( $rbody ) );
1617 } elseif ( $rcode === 204 ) {
1618 $status->value = [];
1619 } elseif ( $rcode === 404 ) {
1620 $status->value = [];
1622 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1629 foreach ( $containerInfo as $container => $info ) {
1630 $this->containerStatCache->setField( $container,
'stat', $info );
1641 foreach ( $params[
'srcs'] as
$path ) {
1643 if ( $srcRel ===
null || !$auth ) {
1649 if ( $cstat === self::$RES_ABSENT ) {
1652 } elseif ( !is_array( $cstat ) ) {
1659 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1665 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
1666 $reqs = $this->http->runMulti( $reqs, $opts );
1667 foreach ( $reqs as
$path => $op ) {
1668 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1669 if ( $rcode === 200 || $rcode === 204 ) {
1671 if ( !empty( $params[
'requireSHA1'] ) ) {
1676 if ( $this->isRGW ) {
1677 $stat[
'latest'] =
true;
1679 } elseif ( $rcode === 404 ) {
1683 $this->
onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1685 $stats[
$path] = $stat;
1705 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1706 'sha1' => $metadata[
'sha1base36'] ??
null,
1708 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1709 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1717 if ( $this->authErrorTimestamp !==
null ) {
1718 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1721 $this->authErrorTimestamp =
null;
1727 if ( !$this->authCreds || $reAuth ) {
1728 $this->authSessionTimestamp = 0;
1730 $creds = $this->srvCache->get( $cacheKey );
1732 if ( isset( $creds[
'auth_token'] ) && isset( $creds[
'storage_url'] ) ) {
1733 $this->authCreds = $creds;
1735 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1737 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1739 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1741 'x-auth-user' => $this->swiftUser,
1742 'x-auth-key' => $this->swiftKey
1746 if ( $rcode >= 200 && $rcode <= 299 ) {
1747 $this->authCreds = [
1748 'auth_token' => $rhdrs[
'x-auth-token'],
1749 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url']
1752 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1753 $this->authSessionTimestamp = time();
1754 } elseif ( $rcode === 401 ) {
1755 $this->
onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1756 $this->authErrorTimestamp = time();
1760 $this->
onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode );
1761 $this->authErrorTimestamp = time();
1767 if ( substr( $this->authCreds[
'storage_url'], -3 ) ===
'/v1' ) {
1768 $this->isRGW =
true;
1781 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1782 $parts = [ $creds[
'storage_url'] ];
1783 if ( strlen( $container ) ) {
1784 $parts[] = rawurlencode( $container );
1786 if ( strlen( $object ) ) {
1787 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1790 return implode(
'/', $parts );
1798 return [
'x-auth-token' => $creds[
'auth_token'] ];
1808 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1822 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'' ) {
1824 $status->fatal(
'backend-fail-internal', $this->name );
1826 if ( $code == 401 ) {
1829 $msg =
"HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1834 'req_params' => FormatJson::encode( $params ),
1838 $msgParams[
'err'] = $err;
1840 $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.
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.
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.
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