25use Psr\Log\LoggerInterface;
26use Wikimedia\AtEase\AtEase;
27use Wikimedia\RequestTimeout\TimeoutException;
39 private const DEFAULT_HTTP_OPTIONS = [
'httpVersion' =>
'v1.1' ];
123 parent::__construct( $config );
125 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
126 $this->swiftUser = $config[
'swiftUser'];
127 $this->swiftKey = $config[
'swiftKey'];
129 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
130 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
131 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
132 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
133 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
134 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
138 foreach ( [
'connTimeout',
'reqTimeout' ] as $optionName ) {
139 if ( isset( $config[$optionName] ) ) {
140 $httpOptions[$optionName] = $config[$optionName];
144 $this->http->setLogger( $this->logger );
147 if ( isset( $config[
'wanCache'] ) && $config[
'wanCache'] instanceof
WANObjectCache ) {
148 $this->memCache = $config[
'wanCache'];
151 $this->containerStatCache =
new MapCacheLRU( 300 );
153 if ( !empty( $config[
'cacheAuthInfo'] ) && isset( $config[
'srvCache'] ) ) {
154 $this->srvCache = $config[
'srvCache'];
158 $this->readUsers = $config[
'readUsers'] ?? [];
159 $this->writeUsers = $config[
'writeUsers'] ?? [];
160 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
161 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
166 $this->http->setLogger(
$logger );
171 self::ATTR_UNICODE_PATHS |
178 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
180 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
184 return $relStoragePath;
189 if ( $rel ===
null ) {
206 $contentHeaders = [];
208 foreach ( $headers as
$name => $value ) {
210 if (
$name ===
'x-delete-at' && is_numeric( $value ) ) {
212 $contentHeaders[
$name] = $value;
213 } elseif (
$name ===
'x-delete-after' && is_numeric( $value ) ) {
215 $contentHeaders[
$name] = $value;
216 } elseif ( preg_match(
'/^(x-)?content-(?!length$)/',
$name ) ) {
218 $contentHeaders[
$name] = $value;
219 } elseif (
$name ===
'content-type' && strlen( $value ) ) {
221 $contentHeaders[
$name] = $value;
225 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
228 $offset = $maxLength - strlen( $contentHeaders[
'content-disposition'] );
230 $pos = strrpos( $contentHeaders[
'content-disposition'],
';', $offset );
231 $contentHeaders[
'content-disposition'] = $pos ===
false
233 : trim( substr( $contentHeaders[
'content-disposition'], 0, $pos ) );
237 return $contentHeaders;
246 $metadataHeaders = [];
247 foreach ( $headers as
$name => $value ) {
249 if ( strpos(
$name,
'x-object-meta-' ) === 0 ) {
250 $metadataHeaders[
$name] = $value;
254 return $metadataHeaders;
263 $prefixLen = strlen(
'x-object-meta-' );
267 $metadata[substr(
$name, $prefixLen )] = $value;
277 if ( $dstRel ===
null ) {
278 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
286 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
287 ?? $this->
getContentType( $params[
'dst'], $params[
'content'],
null );
291 'url' => [ $dstCont, $dstRel ],
292 'headers' => array_merge(
295 'etag' => md5( $params[
'content'] ),
296 'content-length' => strlen( $params[
'content'] ),
297 'x-object-meta-sha1base36' =>
298 Wikimedia\base_convert( sha1( $params[
'content'] ), 16, 36, 31 )
301 'body' => $params[
'content']
304 $method = __METHOD__;
305 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
306 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
307 if ( $rcode === 201 || $rcode === 202 ) {
309 } elseif ( $rcode === 412 ) {
310 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
312 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
315 return SwiftFileOpHandle::CONTINUE_IF_OK;
319 if ( !empty( $params[
'async'] ) ) {
320 $status->value = $opHandle;
332 if ( $dstRel ===
null ) {
333 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
341 AtEase::suppressWarnings();
342 $srcHandle = fopen( $params[
'src'],
'rb' );
343 AtEase::restoreWarnings();
344 if ( $srcHandle ===
false ) {
345 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
351 $srcSize = fstat( $srcHandle )[
'size'];
352 $md5Context = hash_init(
'md5' );
353 $sha1Context = hash_init(
'sha1' );
355 while ( !feof( $srcHandle ) ) {
356 $buffer = (string)fread( $srcHandle, 131072 );
357 hash_update( $md5Context, $buffer );
358 hash_update( $sha1Context, $buffer );
359 $hashDigestSize += strlen( $buffer );
362 rewind( $srcHandle );
364 if ( $hashDigestSize !== $srcSize ) {
365 $status->fatal(
'backend-fail-hash', $params[
'src'] );
373 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
378 'url' => [ $dstCont, $dstRel ],
379 'headers' => array_merge(
382 'content-length' => $srcSize,
383 'etag' => hash_final( $md5Context ),
384 'x-object-meta-sha1base36' =>
385 Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
391 $method = __METHOD__;
392 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
393 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
394 if ( $rcode === 201 || $rcode === 202 ) {
396 } elseif ( $rcode === 412 ) {
397 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
399 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
402 return SwiftFileOpHandle::CONTINUE_IF_OK;
406 $opHandle->resourcesToClose[] = $srcHandle;
408 if ( !empty( $params[
'async'] ) ) {
409 $status->value = $opHandle;
421 if ( $srcRel ===
null ) {
422 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
428 if ( $dstRel ===
null ) {
429 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
436 'url' => [ $dstCont, $dstRel ],
437 'headers' => array_merge(
440 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
441 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
446 $method = __METHOD__;
447 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
448 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
449 if ( $rcode === 201 ) {
451 } elseif ( $rcode === 404 ) {
452 if ( empty( $params[
'ignoreMissingSource'] ) ) {
453 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
456 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
459 return SwiftFileOpHandle::CONTINUE_IF_OK;
463 if ( !empty( $params[
'async'] ) ) {
464 $status->value = $opHandle;
476 if ( $srcRel ===
null ) {
477 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
483 if ( $dstRel ===
null ) {
484 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
491 'url' => [ $dstCont, $dstRel ],
492 'headers' => array_merge(
495 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
496 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
500 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
502 'method' =>
'DELETE',
503 'url' => [ $srcCont, $srcRel ],
508 $method = __METHOD__;
509 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
510 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
511 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
513 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
515 } elseif ( $rcode === 404 ) {
516 if ( empty( $params[
'ignoreMissingSource'] ) ) {
517 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
520 return SwiftFileOpHandle::CONTINUE_NO;
523 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
526 return SwiftFileOpHandle::CONTINUE_IF_OK;
530 if ( !empty( $params[
'async'] ) ) {
531 $status->value = $opHandle;
543 if ( $srcRel ===
null ) {
544 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
550 'method' =>
'DELETE',
551 'url' => [ $srcCont, $srcRel ],
555 $method = __METHOD__;
556 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
557 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
558 if ( $rcode === 204 ) {
560 } elseif ( $rcode === 404 ) {
561 if ( empty( $params[
'ignoreMissingSource'] ) ) {
562 $status->fatal(
'backend-fail-delete', $params[
'src'] );
565 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
568 return SwiftFileOpHandle::CONTINUE_IF_OK;
572 if ( !empty( $params[
'async'] ) ) {
573 $status->value = $opHandle;
585 if ( $srcRel ===
null ) {
586 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
592 $stat = $this->
getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
593 if ( $stat && !isset( $stat[
'xattr'] ) ) {
594 $stat = $this->
doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
597 $status->fatal(
'backend-fail-describe', $params[
'src'] );
605 $oldMetadataHeaders = [];
606 foreach ( $stat[
'xattr'][
'metadata'] as
$name => $value ) {
607 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
610 $oldContentHeaders = $stat[
'xattr'][
'headers'];
614 'url' => [ $srcCont, $srcRel ],
615 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
618 $method = __METHOD__;
619 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
620 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
621 if ( $rcode === 202 ) {
623 } elseif ( $rcode === 404 ) {
624 $status->fatal(
'backend-fail-describe', $params[
'src'] );
626 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
631 if ( !empty( $params[
'async'] ) ) {
632 $status->value = $opHandle;
648 if ( is_array( $stat ) ) {
650 } elseif ( $stat === self::$RES_ERROR ) {
651 $status->fatal(
'backend-fail-internal', $this->name );
652 $this->logger->error( __METHOD__ .
': cannot get container stat' );
658 if ( $stat ===
false ) {
659 $params[
'op'] =
'prepare';
668 if ( empty( $params[
'noAccess'] ) ) {
673 if ( is_array( $stat ) ) {
674 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
675 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
682 } elseif ( $stat ===
false ) {
683 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
685 $status->fatal(
'backend-fail-internal', $this->name );
686 $this->logger->error( __METHOD__ .
': cannot get container stat' );
696 if ( is_array( $stat ) ) {
697 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
698 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
706 } elseif ( $stat ===
false ) {
707 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
709 $status->fatal(
'backend-fail-internal', $this->name );
710 $this->logger->error( __METHOD__ .
': cannot get container stat' );
726 if ( $stat ===
false ) {
728 } elseif ( !is_array( $stat ) ) {
729 $status->fatal(
'backend-fail-internal', $this->name );
730 $this->logger->error( __METHOD__ .
': cannot get container stat' );
736 if ( $stat[
'count'] == 0 ) {
737 $params[
'op'] =
'clean';
745 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
746 unset( $params[
'src'] );
749 return reset( $stats );
766 return $timestamp->getTimestamp( $format );
767 }
catch ( TimeoutException $e ) {
769 }
catch ( Exception $e ) {
782 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
788 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
789 [
'path' =>
$path ] );
791 $objHdrs[
'x-object-meta-sha1base36'] =
false;
806 if ( $status->isOK() ) {
809 $hash = $tmpFile->getSha1Base36();
810 if ( $hash !==
false ) {
811 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
813 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
815 list( $rcode ) = $this->http->run( [
817 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
819 ], self::DEFAULT_HTTP_OPTIONS );
820 if ( $rcode >= 200 && $rcode <= 299 ) {
829 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
830 [
'path' =>
$path ] );
838 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
844 $contents = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
845 foreach ( $params[
'srcs'] as
$path ) {
847 if ( $srcRel ===
null || !$auth ) {
851 $handle = fopen(
'php://temp',
'wb' );
855 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
864 'maxConnsPerHost' => $params[
'concurrency'],
865 ] + self::DEFAULT_HTTP_OPTIONS;
866 $reqs = $this->http->runMulti( $reqs, $opts );
867 foreach ( $reqs as
$path => $op ) {
868 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
869 if ( $rcode >= 200 && $rcode <= 299 ) {
870 rewind( $op[
'stream'] );
871 $content = (string)stream_get_contents( $op[
'stream'] );
874 if ( $size === (
int)$rhdrs[
'content-length'] ) {
878 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
879 $this->
onError(
null, __METHOD__,
880 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
882 } elseif ( $rcode === 404 ) {
886 $this->
onError(
null, __METHOD__,
887 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
889 fclose( $op[
'stream'] );
896 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
897 $status = $this->objectListing( $fullCont,
'names', 1,
null, $prefix );
898 if ( $status->isOK() ) {
899 return ( count( $status->value ) ) > 0;
940 if ( $after === INF ) {
947 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
949 if ( !empty( $params[
'topOnly'] ) ) {
950 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
951 if ( !$status->isOK() ) {
954 $objects = $status->value;
956 foreach ( $objects as $object ) {
957 if ( substr( $object, -1 ) ===
'/' ) {
963 $getParentDir =
static function (
$path ) {
964 return ( strpos(
$path,
'/' ) !== false ) ? dirname(
$path ) :
false;
968 $lastDir = $getParentDir( $after );
969 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
971 if ( !$status->isOK() ) {
975 $objects = $status->value;
978 foreach ( $objects as $object ) {
979 $objectDir = $getParentDir( $object );
981 if ( $objectDir !==
false && $objectDir !== $dir ) {
986 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
989 $dirs[] =
"{$pDir}/";
990 $pDir = $getParentDir( $pDir );
991 }
while ( $pDir !==
false
992 && strcmp( $pDir, $lastDir ) > 0
993 && strlen( $pDir ) > strlen( $dir )
996 $lastDir = $objectDir;
1001 if ( count( $objects ) < $limit ) {
1004 $after = end( $objects );
1023 if ( $after === INF ) {
1030 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1033 if ( !empty( $params[
'topOnly'] ) ) {
1034 if ( !empty( $params[
'adviseStat'] ) ) {
1035 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1037 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1041 if ( !empty( $params[
'adviseStat'] ) ) {
1042 $status = $this->objectListing( $fullCont,
'info', $limit, $after, $prefix );
1044 $status = $this->objectListing( $fullCont,
'names', $limit, $after, $prefix );
1049 if ( !$status->isOK() ) {
1053 $objects = $status->value;
1054 $files = $this->buildFileObjectListing( $objects );
1057 if ( count( $objects ) < $limit ) {
1060 $after = end( $objects );
1061 $after = is_object( $after ) ? $after->name : $after;
1074 private function buildFileObjectListing( array $objects ) {
1076 foreach ( $objects as $object ) {
1077 if ( is_object( $object ) ) {
1078 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1084 'size' => (int)$object->bytes,
1087 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1090 $names[] = [ $object->name, $stat ];
1091 } elseif ( substr( $object, -1 ) !==
'/' ) {
1093 $names[] = [ $object, null ];
1107 $this->cheapCache->setField(
$path,
'stat', $val );
1113 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1118 if ( is_array( $stat ) ) {
1119 return $stat[
'xattr'];
1128 $params[
'requireSHA1'] =
true;
1131 if ( is_array( $stat ) ) {
1132 return $stat[
'sha1'];
1144 if ( $srcRel ===
null ) {
1146 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1154 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1161 if ( $params[
'headers'] && !$this->
fileExists( $params ) ) {
1163 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1169 foreach ( $params[
'headers'] as
$header ) {
1173 if ( empty( $params[
'allowOB'] ) ) {
1178 $handle = fopen(
'php://output',
'wb' );
1179 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1181 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1184 'stream' => $handle,
1185 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1186 ], self::DEFAULT_HTTP_OPTIONS );
1188 if ( $rcode >= 200 && $rcode <= 299 ) {
1190 } elseif ( $rcode === 404 ) {
1191 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1198 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1207 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1213 $tmpFiles = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
1214 foreach ( $params[
'srcs'] as
$path ) {
1216 if ( $srcRel ===
null || !$auth ) {
1222 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_',
$ext );
1223 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1227 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1230 'stream' => $handle,
1232 $tmpFiles[
$path] = $tmpFile;
1237 $latest = ( $this->isRGW || !empty( $params[
'latest'] ) );
1240 'maxConnsPerHost' => $params[
'concurrency'],
1241 ] + self::DEFAULT_HTTP_OPTIONS;
1242 $reqs = $this->http->runMulti( $reqs, $opts );
1243 foreach ( $reqs as
$path => $op ) {
1244 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1245 fclose( $op[
'stream'] );
1246 if ( $rcode >= 200 && $rcode <= 299 ) {
1248 $tmpFile = $tmpFiles[
$path];
1250 $size = $tmpFile->getSize();
1251 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1253 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1254 $this->
onError(
null, __METHOD__,
1255 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1259 $stat[
'latest'] = $latest;
1260 $this->cheapCache->setField(
$path,
'stat', $stat );
1261 } elseif ( $rcode === 404 ) {
1263 $this->cheapCache->setField(
1270 $this->
onError(
null, __METHOD__,
1271 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1279 if ( $this->swiftTempUrlKey !=
'' ||
1280 ( $this->rgwS3AccessKey !=
'' && $this->rgwS3SecretKey !=
'' )
1283 if ( $srcRel ===
null ) {
1284 return self::TEMPURL_ERROR;
1289 return self::TEMPURL_ERROR;
1292 $ttl = $params[
'ttl'] ?? 86400;
1293 $expires = time() + $ttl;
1295 if ( $this->swiftTempUrlKey !=
'' ) {
1296 $url = $this->
storageUrl( $auth, $srcCont, $srcRel );
1298 $contPath = parse_url( $this->
storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1299 $signature = hash_hmac(
'sha1',
1300 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1301 $this->swiftTempUrlKey
1304 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1307 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1308 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1310 $signature = base64_encode( hash_hmac(
1312 "GET\n\n\n{$expires}\n{$spath}",
1313 $this->rgwS3SecretKey,
1319 return str_replace(
'/swift/v1',
'', $this->
storageUrl( $auth ) . $spath ) .
1322 'Signature' => $signature,
1323 'Expires' => $expires,
1324 'AWSAccessKeyId' => $this->rgwS3AccessKey
1329 return self::TEMPURL_ERROR;
1346 if ( !empty( $params[
'latest'] ) ) {
1347 $hdrs[
'x-newest'] =
'true';
1355 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1362 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1363 $statuses[$index] = $this->
newStatus(
'backend-fail-connect', $this->name );
1370 $httpReqsByStage = [];
1371 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1372 $reqs = $fileOpHandle->httpOp;
1374 foreach ( $reqs as $stage => &$req ) {
1375 list( $container, $relPath ) = $req[
'url'];
1376 $req[
'url'] = $this->
storageUrl( $auth, $container, $relPath );
1377 $req[
'headers'] = $req[
'headers'] ?? [];
1379 $httpReqsByStage[$stage][$index] = $req;
1385 $reqCount = count( $httpReqsByStage );
1386 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1387 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage], self::DEFAULT_HTTP_OPTIONS );
1388 foreach ( $httpReqs as $index => $httpReq ) {
1390 $fileOpHandle = $fileOpHandles[$index];
1392 $status = $statuses[$index];
1393 ( $fileOpHandle->callback )( $httpReq, $status );
1398 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1400 $stages = count( $fileOpHandle->httpOp );
1401 for (
$s = ( $stage + 1 );
$s < $stages; ++
$s ) {
1402 unset( $httpReqsByStage[
$s][$index] );
1438 $status->fatal(
'backend-fail-connect', $this->name );
1443 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1445 'url' => $this->
storageUrl( $auth, $container ),
1447 'x-container-read' => implode(
',',
$readUsers ),
1448 'x-container-write' => implode(
',',
$writeUsers )
1450 ], self::DEFAULT_HTTP_OPTIONS );
1452 if ( $rcode != 204 && $rcode !== 202 ) {
1453 $status->fatal(
'backend-fail-internal', $this->name );
1454 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1455 [
'rcode' => $rcode ] );
1473 if ( $bypassCache ) {
1474 $this->containerStatCache->clear( $container );
1475 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1478 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1484 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1486 'url' => $this->
storageUrl( $auth, $container ),
1488 ], self::DEFAULT_HTTP_OPTIONS );
1490 if ( $rcode === 204 ) {
1492 'count' => $rhdrs[
'x-container-object-count'],
1493 'bytes' => $rhdrs[
'x-container-bytes-used']
1495 if ( $bypassCache ) {
1498 $this->containerStatCache->setField( $container,
'stat', $stat );
1501 } elseif ( $rcode === 404 ) {
1504 $this->
onError(
null, __METHOD__,
1505 [
'cont' => $container ], $rerr, $rcode, $rdesc );
1511 return $this->containerStatCache->getField( $container,
'stat' );
1526 $status->fatal(
'backend-fail-connect', $this->name );
1532 if ( empty( $params[
'noAccess'] ) ) {
1534 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1535 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1538 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1539 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1542 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1544 'url' => $this->
storageUrl( $auth, $container ),
1546 'x-container-read' => implode(
',',
$readUsers ),
1547 'x-container-write' => implode(
',',
$writeUsers )
1549 ], self::DEFAULT_HTTP_OPTIONS );
1551 if ( $rcode === 201 ) {
1553 } elseif ( $rcode === 202 ) {
1556 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1574 $status->fatal(
'backend-fail-connect', $this->name );
1579 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1580 'method' =>
'DELETE',
1581 'url' => $this->
storageUrl( $auth, $container ),
1583 ], self::DEFAULT_HTTP_OPTIONS );
1585 if ( $rcode >= 200 && $rcode <= 299 ) {
1586 $this->containerStatCache->clear( $container );
1587 } elseif ( $rcode === 404 ) {
1589 } elseif ( $rcode === 409 ) {
1590 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1593 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1611 private function objectListing(
1612 $fullCont,
$type, $limit, $after =
null, $prefix =
null, $delim =
null
1618 $status->fatal(
'backend-fail-connect', $this->name );
1623 $query = [
'limit' => $limit ];
1624 if (
$type ===
'info' ) {
1625 $query[
'format'] =
'json';
1627 if ( $after !==
null ) {
1628 $query[
'marker'] = $after;
1630 if ( $prefix !==
null ) {
1631 $query[
'prefix'] = $prefix;
1633 if ( $delim !==
null ) {
1634 $query[
'delimiter'] = $delim;
1637 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1639 'url' => $this->
storageUrl( $auth, $fullCont ),
1642 ], self::DEFAULT_HTTP_OPTIONS );
1644 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1645 if ( $rcode === 200 ) {
1646 if (
$type ===
'info' ) {
1649 $status->value = explode(
"\n", trim( $rbody ) );
1651 } elseif ( $rcode === 204 ) {
1652 $status->value = [];
1653 } elseif ( $rcode === 404 ) {
1654 $status->value = [];
1656 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1663 foreach ( $containerInfo as $container => $info ) {
1664 $this->containerStatCache->setField( $container,
'stat', $info );
1675 foreach ( $params[
'srcs'] as
$path ) {
1677 if ( $srcRel ===
null || !$auth ) {
1683 if ( $cstat === self::$RES_ABSENT ) {
1686 } elseif ( !is_array( $cstat ) ) {
1693 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1700 'maxConnsPerHost' => $params[
'concurrency'],
1701 ] + self::DEFAULT_HTTP_OPTIONS;
1702 $reqs = $this->http->runMulti( $reqs, $opts );
1703 foreach ( $reqs as
$path => $op ) {
1704 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1705 if ( $rcode === 200 || $rcode === 204 ) {
1707 if ( !empty( $params[
'requireSHA1'] ) ) {
1712 if ( $this->isRGW ) {
1713 $stat[
'latest'] =
true;
1715 } elseif ( $rcode === 404 ) {
1719 $this->
onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1721 $stats[
$path] = $stat;
1741 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1742 'sha1' => $metadata[
'sha1base36'] ??
null,
1744 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1745 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1753 if ( $this->authErrorTimestamp !==
null ) {
1754 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1757 $this->authErrorTimestamp =
null;
1763 if ( !$this->authCreds || $reAuth ) {
1764 $this->authSessionTimestamp = 0;
1765 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1766 $creds = $this->srvCache->get( $cacheKey );
1768 if ( isset( $creds[
'auth_token'] ) && isset( $creds[
'storage_url'] ) ) {
1769 $this->authCreds = $creds;
1771 $this->authSessionTimestamp = time() - (int)ceil( $this->authTTL / 2 );
1773 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1775 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1777 'x-auth-user' => $this->swiftUser,
1778 'x-auth-key' => $this->swiftKey
1780 ], self::DEFAULT_HTTP_OPTIONS );
1782 if ( $rcode >= 200 && $rcode <= 299 ) {
1783 $this->authCreds = [
1784 'auth_token' => $rhdrs[
'x-auth-token'],
1785 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url']
1788 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1789 $this->authSessionTimestamp = time();
1790 } elseif ( $rcode === 401 ) {
1791 $this->
onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1792 $this->authErrorTimestamp = time();
1796 $this->
onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode );
1797 $this->authErrorTimestamp = time();
1803 if ( substr( $this->authCreds[
'storage_url'], -3 ) ===
'/v1' ) {
1804 $this->isRGW =
true;
1817 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1818 $parts = [ $creds[
'storage_url'] ];
1819 if ( strlen( $container ??
'' ) ) {
1820 $parts[] = rawurlencode( $container );
1822 if ( strlen( $object ??
'' ) ) {
1823 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1826 return implode(
'/', $parts );
1834 return [
'x-auth-token' => $creds[
'auth_token'] ];
1843 private function getCredsCacheKey( $username ) {
1844 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1858 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'' ) {
1860 $status->fatal(
'backend-fail-internal', $this->name );
1862 if ( $code == 401 ) {
1863 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1865 $msg =
"HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1870 'req_params' => FormatJson::encode( $params ),
1874 $msgParams[
'err'] = $err;
1876 $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)
int null $authErrorTimestamp
UNIX timestamp.
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)
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 $authSessionTimestamp
UNIX timestamp.
loadListingStatInternal( $path, array $val)
Do not call this function outside of SwiftFileBackendFileList.
doPrepareInternal( $fullCont, $dir, array $params)
FileBackendStore::doPrepare() to override StatusValue Good status without value for success,...
setLogger(LoggerInterface $logger)
doSecureInternal( $fullCont, $dir, array $params)
getFileListInternal( $fullCont, $dir, array $params)
getMetadataFromHeaders(array $headers)
doMoveInternal(array $params)
addMissingHashMetadata(array $objHdrs, $path)
Fill in any missing object metadata and save it to Swift.
getFeatures()
Get the a bitfield of extra features supported by the backend medium.
deleteContainer( $container, array $params)
Delete a Swift container.
doGetFileStat(array $params)
doGetLocalCopyMulti(array $params)
string $rgwS3SecretKey
S3 authentication key (RADOS Gateway)
doGetFileContentsMulti(array $params)
storageUrl(array $creds, $container=null, $object=null)
convertSwiftDate( $ts, $format=TS_MW)
Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
doStreamFile(array $params)
doPrimeContainerCache(array $containerInfo)
Fill the backend-specific process cache given an array of resolved container names and their correspo...
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
array $readUsers
Additional users (account:user) with read permissions on public containers.
array $secureReadUsers
Additional users (account:user) with read permissions on private containers.
doCleanInternal( $fullCont, $dir, array $params)
getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params)
Do not call this function outside of SwiftFileBackendFileList.
string $swiftKey
Secret key for user.
doDirectoryExists( $fullCont, $dir, array $params)
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
doExecuteOpHandlesInternal(array $fileOpHandles)
doDeleteInternal(array $params)
doDescribeInternal(array $params)
extractMutableContentHeaders(array $headers)
Filter/normalize a header map to only include mutable "content-"/"x-content-" headers.
getContainerStat( $container, $bypassCache=false)
Get a Swift container stat array, possibly from process cache.
Multi-datacenter aware caching interface.
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s
if(!is_readable( $file)) $ext