25use Psr\Log\LoggerInterface;
26use Wikimedia\AtEase\AtEase;
120 parent::__construct( $config );
122 $this->swiftAuthUrl = $config[
'swiftAuthUrl'];
123 $this->swiftUser = $config[
'swiftUser'];
124 $this->swiftKey = $config[
'swiftKey'];
126 $this->authTTL = $config[
'swiftAuthTTL'] ?? 15 * 60;
127 $this->swiftTempUrlKey = $config[
'swiftTempUrlKey'] ??
'';
128 $this->swiftStorageUrl = $config[
'swiftStorageUrl'] ??
null;
129 $this->shardViaHashLevels = $config[
'shardViaHashLevels'] ??
'';
130 $this->rgwS3AccessKey = $config[
'rgwS3AccessKey'] ??
'';
131 $this->rgwS3SecretKey = $config[
'rgwS3SecretKey'] ??
'';
135 foreach ( [
'connTimeout',
'reqTimeout' ] as $optionName ) {
136 if ( isset( $config[$optionName] ) ) {
137 $httpOptions[$optionName] = $config[$optionName];
141 $this->http->setLogger( $this->logger );
144 if ( isset( $config[
'wanCache'] ) && $config[
'wanCache'] instanceof
WANObjectCache ) {
145 $this->memCache = $config[
'wanCache'];
148 $this->containerStatCache =
new MapCacheLRU( 300 );
150 if ( !empty( $config[
'cacheAuthInfo'] ) && isset( $config[
'srvCache'] ) ) {
151 $this->srvCache = $config[
'srvCache'];
155 $this->readUsers = $config[
'readUsers'] ?? [];
156 $this->writeUsers = $config[
'writeUsers'] ?? [];
157 $this->secureReadUsers = $config[
'secureReadUsers'] ?? [];
158 $this->secureWriteUsers = $config[
'secureWriteUsers'] ?? [];
163 $this->http->setLogger(
$logger );
168 self::ATTR_UNICODE_PATHS |
175 if ( !mb_check_encoding( $relStoragePath,
'UTF-8' ) ) {
177 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
181 return $relStoragePath;
186 if ( $rel ===
null ) {
203 $contentHeaders = [];
205 foreach ( $headers as
$name => $value ) {
207 if (
$name ===
'x-delete-at' && is_numeric( $value ) ) {
209 $contentHeaders[
$name] = $value;
210 } elseif (
$name ===
'x-delete-after' && is_numeric( $value ) ) {
212 $contentHeaders[
$name] = $value;
213 } elseif ( preg_match(
'/^(x-)?content-(?!length$)/',
$name ) ) {
215 $contentHeaders[
$name] = $value;
216 } elseif (
$name ===
'content-type' && strlen( $value ) ) {
218 $contentHeaders[
$name] = $value;
222 if ( isset( $contentHeaders[
'content-disposition'] ) ) {
225 $offset = $maxLength - strlen( $contentHeaders[
'content-disposition'] );
227 $pos = strrpos( $contentHeaders[
'content-disposition'],
';', $offset );
228 $contentHeaders[
'content-disposition'] = $pos ===
false
230 : trim( substr( $contentHeaders[
'content-disposition'], 0, $pos ) );
234 return $contentHeaders;
243 $metadataHeaders = [];
244 foreach ( $headers as
$name => $value ) {
246 if ( strpos(
$name,
'x-object-meta-' ) === 0 ) {
247 $metadataHeaders[
$name] = $value;
251 return $metadataHeaders;
260 $prefixLen = strlen(
'x-object-meta-' );
264 $metadata[substr(
$name, $prefixLen )] = $value;
274 if ( $dstRel ===
null ) {
275 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
283 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
284 ?? $this->
getContentType( $params[
'dst'], $params[
'content'],
null );
288 'url' => [ $dstCont, $dstRel ],
289 'headers' => array_merge(
292 'etag' => md5( $params[
'content'] ),
293 'content-length' => strlen( $params[
'content'] ),
294 'x-object-meta-sha1base36' =>
295 Wikimedia\base_convert( sha1( $params[
'content'] ), 16, 36, 31 )
298 'body' => $params[
'content']
301 $method = __METHOD__;
302 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
303 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
304 if ( $rcode === 201 || $rcode === 202 ) {
306 } elseif ( $rcode === 412 ) {
307 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
309 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
312 return SwiftFileOpHandle::CONTINUE_IF_OK;
316 if ( !empty( $params[
'async'] ) ) {
317 $status->value = $opHandle;
329 if ( $dstRel ===
null ) {
330 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
338 AtEase::suppressWarnings();
339 $srcHandle = fopen( $params[
'src'],
'rb' );
340 AtEase::restoreWarnings();
341 if ( $srcHandle ===
false ) {
342 $status->fatal(
'backend-fail-notexists', $params[
'src'] );
348 $srcSize = fstat( $srcHandle )[
'size'];
349 $md5Context = hash_init(
'md5' );
350 $sha1Context = hash_init(
'sha1' );
352 while ( !feof( $srcHandle ) ) {
353 $buffer = (string)fread( $srcHandle, 131072 );
354 hash_update( $md5Context, $buffer );
355 hash_update( $sha1Context, $buffer );
356 $hashDigestSize += strlen( $buffer );
359 rewind( $srcHandle );
361 if ( $hashDigestSize !== $srcSize ) {
362 $status->fatal(
'backend-fail-hash', $params[
'src'] );
370 $mutableHeaders[
'content-type'] = $mutableHeaders[
'content-type']
375 'url' => [ $dstCont, $dstRel ],
376 'headers' => array_merge(
379 'content-length' => $srcSize,
380 'etag' => hash_final( $md5Context ),
381 'x-object-meta-sha1base36' =>
382 Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
388 $method = __METHOD__;
389 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
390 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
391 if ( $rcode === 201 || $rcode === 202 ) {
393 } elseif ( $rcode === 412 ) {
394 $status->fatal(
'backend-fail-contenttype', $params[
'dst'] );
396 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
399 return SwiftFileOpHandle::CONTINUE_IF_OK;
403 $opHandle->resourcesToClose[] = $srcHandle;
405 if ( !empty( $params[
'async'] ) ) {
406 $status->value = $opHandle;
418 if ( $srcRel ===
null ) {
419 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
425 if ( $dstRel ===
null ) {
426 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
433 'url' => [ $dstCont, $dstRel ],
434 'headers' => array_merge(
437 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
438 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
443 $method = __METHOD__;
444 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
445 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
446 if ( $rcode === 201 ) {
448 } elseif ( $rcode === 404 ) {
449 if ( empty( $params[
'ignoreMissingSource'] ) ) {
450 $status->fatal(
'backend-fail-copy', $params[
'src'], $params[
'dst'] );
453 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
456 return SwiftFileOpHandle::CONTINUE_IF_OK;
460 if ( !empty( $params[
'async'] ) ) {
461 $status->value = $opHandle;
473 if ( $srcRel ===
null ) {
474 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
480 if ( $dstRel ===
null ) {
481 $status->fatal(
'backend-fail-invalidpath', $params[
'dst'] );
488 'url' => [ $dstCont, $dstRel ],
489 'headers' => array_merge(
492 'x-copy-from' =>
'/' . rawurlencode( $srcCont ) .
'/' .
493 str_replace(
"%2F",
"/", rawurlencode( $srcRel ) )
497 if (
"{$srcCont}/{$srcRel}" !==
"{$dstCont}/{$dstRel}" ) {
499 'method' =>
'DELETE',
500 'url' => [ $srcCont, $srcRel ],
505 $method = __METHOD__;
506 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
507 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
508 if ( $request[
'method'] ===
'PUT' && $rcode === 201 ) {
510 } elseif ( $request[
'method'] ===
'DELETE' && $rcode === 204 ) {
512 } elseif ( $rcode === 404 ) {
513 if ( empty( $params[
'ignoreMissingSource'] ) ) {
514 $status->fatal(
'backend-fail-move', $params[
'src'], $params[
'dst'] );
517 return SwiftFileOpHandle::CONTINUE_NO;
520 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
523 return SwiftFileOpHandle::CONTINUE_IF_OK;
527 if ( !empty( $params[
'async'] ) ) {
528 $status->value = $opHandle;
540 if ( $srcRel ===
null ) {
541 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
547 'method' =>
'DELETE',
548 'url' => [ $srcCont, $srcRel ],
552 $method = __METHOD__;
553 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
554 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
555 if ( $rcode === 204 ) {
557 } elseif ( $rcode === 404 ) {
558 if ( empty( $params[
'ignoreMissingSource'] ) ) {
559 $status->fatal(
'backend-fail-delete', $params[
'src'] );
562 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
565 return SwiftFileOpHandle::CONTINUE_IF_OK;
569 if ( !empty( $params[
'async'] ) ) {
570 $status->value = $opHandle;
582 if ( $srcRel ===
null ) {
583 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
589 $stat = $this->
getFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
590 if ( $stat && !isset( $stat[
'xattr'] ) ) {
591 $stat = $this->
doGetFileStat( [
'src' => $params[
'src'],
'latest' => 1 ] );
594 $status->fatal(
'backend-fail-describe', $params[
'src'] );
602 $oldMetadataHeaders = [];
603 foreach ( $stat[
'xattr'][
'metadata'] as
$name => $value ) {
604 $oldMetadataHeaders[
"x-object-meta-$name"] = $value;
607 $oldContentHeaders = $stat[
'xattr'][
'headers'];
611 'url' => [ $srcCont, $srcRel ],
612 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
615 $method = __METHOD__;
616 $handler =
function ( array $request,
StatusValue $status ) use ( $method, $params ) {
617 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request[
'response'];
618 if ( $rcode === 202 ) {
620 } elseif ( $rcode === 404 ) {
621 $status->fatal(
'backend-fail-describe', $params[
'src'] );
623 $this->
onError( $status, $method, $params, $rerr, $rcode, $rdesc );
628 if ( !empty( $params[
'async'] ) ) {
629 $status->value = $opHandle;
642 if ( is_array( $stat ) ) {
644 } elseif ( $stat === self::$RES_ERROR ) {
645 $status->fatal(
'backend-fail-internal', $this->name );
646 $this->logger->error( __METHOD__ .
': cannot get container stat' );
652 if ( $stat ===
false ) {
653 $params[
'op'] =
'prepare';
662 if ( empty( $params[
'noAccess'] ) ) {
667 if ( is_array( $stat ) ) {
668 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
669 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
676 } elseif ( $stat ===
false ) {
677 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
679 $status->fatal(
'backend-fail-internal', $this->name );
680 $this->logger->error( __METHOD__ .
': cannot get container stat' );
690 if ( is_array( $stat ) ) {
691 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser,
'.r:*' ] );
692 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
700 } elseif ( $stat ===
false ) {
701 $status->fatal(
'backend-fail-usable', $params[
'dir'] );
703 $status->fatal(
'backend-fail-internal', $this->name );
704 $this->logger->error( __METHOD__ .
': cannot get container stat' );
720 if ( $stat ===
false ) {
722 } elseif ( !is_array( $stat ) ) {
723 $status->fatal(
'backend-fail-internal', $this->name );
724 $this->logger->error( __METHOD__ .
': cannot get container stat' );
730 if ( $stat[
'count'] == 0 ) {
731 $params[
'op'] =
'clean';
739 $params = [
'srcs' => [ $params[
'src'] ],
'concurrency' => 1 ] + $params;
740 unset( $params[
'src'] );
743 return reset( $stats );
760 return $timestamp->getTimestamp( $format );
761 }
catch ( Exception $e ) {
774 if ( isset( $objHdrs[
'x-object-meta-sha1base36'] ) ) {
780 $this->logger->error( __METHOD__ .
": {path} was not stored with SHA-1 metadata.",
781 [
'path' =>
$path ] );
783 $objHdrs[
'x-object-meta-sha1base36'] =
false;
798 if ( $status->isOK() ) {
801 $hash = $tmpFile->getSha1Base36();
802 if ( $hash !==
false ) {
803 $objHdrs[
'x-object-meta-sha1base36'] = $hash;
805 $postHeaders[
'x-object-meta-sha1base36'] = $hash;
807 list( $rcode ) = $this->http->run( [
809 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
812 if ( $rcode >= 200 && $rcode <= 299 ) {
821 $this->logger->error( __METHOD__ .
': unable to set SHA-1 metadata for {path}',
822 [
'path' =>
$path ] );
830 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
836 $contents = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
837 foreach ( $params[
'srcs'] as
$path ) {
839 if ( $srcRel ===
null || !$auth ) {
843 $handle = fopen(
'php://temp',
'wb' );
847 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
855 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
856 $reqs = $this->http->runMulti( $reqs, $opts );
857 foreach ( $reqs as
$path => $op ) {
858 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
859 if ( $rcode >= 200 && $rcode <= 299 ) {
860 rewind( $op[
'stream'] );
861 $content = (string)stream_get_contents( $op[
'stream'] );
864 if ( $size === (
int)$rhdrs[
'content-length'] ) {
868 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
869 $this->
onError(
null, __METHOD__,
870 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
872 } elseif ( $rcode === 404 ) {
876 $this->
onError(
null, __METHOD__,
877 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
879 fclose( $op[
'stream'] );
886 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
887 $status = $this->
objectListing( $fullCont,
'names', 1,
null, $prefix );
888 if ( $status->isOK() ) {
889 return ( count( $status->value ) ) > 0;
930 if ( $after === INF ) {
937 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
939 if ( !empty( $params[
'topOnly'] ) ) {
940 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
941 if ( !$status->isOK() ) {
944 $objects = $status->value;
946 foreach ( $objects as $object ) {
947 if ( substr( $object, -1 ) ===
'/' ) {
953 $getParentDir =
static function (
$path ) {
954 return ( strpos(
$path,
'/' ) !== false ) ? dirname(
$path ) :
false;
958 $lastDir = $getParentDir( $after );
959 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix );
961 if ( !$status->isOK() ) {
965 $objects = $status->value;
968 foreach ( $objects as $object ) {
969 $objectDir = $getParentDir( $object );
971 if ( $objectDir !==
false && $objectDir !== $dir ) {
976 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
979 $dirs[] =
"{$pDir}/";
980 $pDir = $getParentDir( $pDir );
981 }
while ( $pDir !==
false
982 && strcmp( $pDir, $lastDir ) > 0
983 && strlen( $pDir ) > strlen( $dir )
986 $lastDir = $objectDir;
991 if ( count( $objects ) < $limit ) {
994 $after = end( $objects );
1013 if ( $after === INF ) {
1020 $prefix = ( $dir ==
'' ) ?
null :
"{$dir}/";
1023 if ( !empty( $params[
'topOnly'] ) ) {
1024 if ( !empty( $params[
'adviseStat'] ) ) {
1025 $status = $this->
objectListing( $fullCont,
'info', $limit, $after, $prefix,
'/' );
1027 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix,
'/' );
1031 if ( !empty( $params[
'adviseStat'] ) ) {
1032 $status = $this->
objectListing( $fullCont,
'info', $limit, $after, $prefix );
1034 $status = $this->
objectListing( $fullCont,
'names', $limit, $after, $prefix );
1039 if ( !$status->isOK() ) {
1043 $objects = $status->value;
1047 if ( count( $objects ) < $limit ) {
1050 $after = end( $objects );
1051 $after = is_object( $after ) ? $after->name : $after;
1066 foreach ( $objects as $object ) {
1067 if ( is_object( $object ) ) {
1068 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1074 'size' => (int)$object->bytes,
1077 'md5' => ctype_xdigit( $object->hash ) ? $object->hash :
null,
1080 $names[] = [ $object->name, $stat ];
1081 } elseif ( substr( $object, -1 ) !==
'/' ) {
1083 $names[] = [ $object, null ];
1097 $this->cheapCache->setField(
$path,
'stat', $val );
1103 if ( is_array( $stat ) && !isset( $stat[
'xattr'] ) ) {
1108 if ( is_array( $stat ) ) {
1109 return $stat[
'xattr'];
1118 $params[
'requireSHA1'] =
true;
1121 if ( is_array( $stat ) ) {
1122 return $stat[
'sha1'];
1134 if ( $srcRel ===
null ) {
1136 $status->fatal(
'backend-fail-invalidpath', $params[
'src'] );
1144 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1151 if ( $params[
'headers'] && !$this->
fileExists( $params ) ) {
1153 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1159 foreach ( $params[
'headers'] as
$header ) {
1163 if ( empty( $params[
'allowOB'] ) ) {
1168 $handle = fopen(
'php://output',
'wb' );
1169 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1171 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1174 'stream' => $handle,
1175 'flags' => [
'relayResponseHeaders' => empty( $params[
'headless'] ) ]
1178 if ( $rcode >= 200 && $rcode <= 299 ) {
1180 } elseif ( $rcode === 404 ) {
1181 $status->fatal(
'backend-fail-stream', $params[
'src'] );
1188 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1197 $ep = array_diff_key( $params, [
'srcs' => 1 ] );
1203 $tmpFiles = array_fill_keys( $params[
'srcs'], self::$RES_ERROR );
1204 foreach ( $params[
'srcs'] as
$path ) {
1206 if ( $srcRel ===
null || !$auth ) {
1212 $tmpFile = $this->tmpFileFactory->newTempFSFile(
'localcopy_',
$ext );
1213 $handle = $tmpFile ? fopen( $tmpFile->getPath(),
'wb' ) :
false;
1217 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1220 'stream' => $handle,
1222 $tmpFiles[
$path] = $tmpFile;
1227 $latest = ( $this->isRGW || !empty( $params[
'latest'] ) );
1229 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
1230 $reqs = $this->http->runMulti( $reqs, $opts );
1231 foreach ( $reqs as
$path => $op ) {
1232 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1233 fclose( $op[
'stream'] );
1234 if ( $rcode >= 200 && $rcode <= 299 ) {
1236 $tmpFile = $tmpFiles[
$path];
1238 $size = $tmpFile->getSize();
1239 if ( $size !== (
int)$rhdrs[
'content-length'] ) {
1241 $rerr =
"Got {$size}/{$rhdrs['content-length']} bytes";
1242 $this->
onError(
null, __METHOD__,
1243 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1247 $stat[
'latest'] = $latest;
1248 $this->cheapCache->setField(
$path,
'stat', $stat );
1249 } elseif ( $rcode === 404 ) {
1251 $this->cheapCache->setField(
1258 $this->
onError(
null, __METHOD__,
1259 [
'src' =>
$path ] + $ep, $rerr, $rcode, $rdesc );
1267 if ( $this->swiftTempUrlKey !=
'' ||
1268 ( $this->rgwS3AccessKey !=
'' && $this->rgwS3SecretKey !=
'' )
1271 if ( $srcRel ===
null ) {
1272 return self::TEMPURL_ERROR;
1277 return self::TEMPURL_ERROR;
1280 $ttl = $params[
'ttl'] ?? 86400;
1281 $expires = time() + $ttl;
1283 if ( $this->swiftTempUrlKey !=
'' ) {
1284 $url = $this->
storageUrl( $auth, $srcCont, $srcRel );
1286 $contPath = parse_url( $this->
storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1287 $signature = hash_hmac(
'sha1',
1288 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1289 $this->swiftTempUrlKey
1292 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1295 $spath =
'/' . rawurlencode( $srcCont ) .
'/' .
1296 str_replace(
'%2F',
'/', rawurlencode( $srcRel ) );
1298 $signature = base64_encode( hash_hmac(
1300 "GET\n\n\n{$expires}\n{$spath}",
1301 $this->rgwS3SecretKey,
1307 return str_replace(
'/swift/v1',
'', $this->
storageUrl( $auth ) . $spath ) .
1310 'Signature' => $signature,
1311 'Expires' => $expires,
1312 'AWSAccessKeyId' => $this->rgwS3AccessKey
1317 return self::TEMPURL_ERROR;
1334 if ( !empty( $params[
'latest'] ) ) {
1335 $hdrs[
'x-newest'] =
'true';
1343 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1350 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1351 $statuses[$index] = $this->
newStatus(
'backend-fail-connect', $this->name );
1358 $httpReqsByStage = [];
1359 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1360 $reqs = $fileOpHandle->httpOp;
1362 foreach ( $reqs as $stage => &$req ) {
1363 list( $container, $relPath ) = $req[
'url'];
1364 $req[
'url'] = $this->
storageUrl( $auth, $container, $relPath );
1365 $req[
'headers'] = $req[
'headers'] ?? [];
1367 $httpReqsByStage[$stage][$index] = $req;
1373 $reqCount = count( $httpReqsByStage );
1374 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1375 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1376 foreach ( $httpReqs as $index => $httpReq ) {
1378 $fileOpHandle = $fileOpHandles[$index];
1380 $status = $statuses[$index];
1381 ( $fileOpHandle->callback )( $httpReq, $status );
1386 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1388 $stages = count( $fileOpHandle->httpOp );
1389 for (
$s = ( $stage + 1 );
$s < $stages; ++
$s ) {
1390 unset( $httpReqsByStage[
$s][$index] );
1426 $status->fatal(
'backend-fail-connect', $this->name );
1431 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1433 'url' => $this->
storageUrl( $auth, $container ),
1435 'x-container-read' => implode(
',',
$readUsers ),
1436 'x-container-write' => implode(
',',
$writeUsers )
1440 if ( $rcode != 204 && $rcode !== 202 ) {
1441 $status->fatal(
'backend-fail-internal', $this->name );
1442 $this->logger->error( __METHOD__ .
': unexpected rcode value ({rcode})',
1443 [
'rcode' => $rcode ] );
1461 if ( $bypassCache ) {
1462 $this->containerStatCache->clear( $container );
1463 } elseif ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1466 if ( !$this->containerStatCache->hasField( $container,
'stat' ) ) {
1472 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1474 'url' => $this->
storageUrl( $auth, $container ),
1478 if ( $rcode === 204 ) {
1480 'count' => $rhdrs[
'x-container-object-count'],
1481 'bytes' => $rhdrs[
'x-container-bytes-used']
1483 if ( $bypassCache ) {
1486 $this->containerStatCache->setField( $container,
'stat', $stat );
1489 } elseif ( $rcode === 404 ) {
1492 $this->
onError(
null, __METHOD__,
1493 [
'cont' => $container ], $rerr, $rcode, $rdesc );
1499 return $this->containerStatCache->getField( $container,
'stat' );
1514 $status->fatal(
'backend-fail-connect', $this->name );
1520 if ( empty( $params[
'noAccess'] ) ) {
1522 $readUsers = array_merge( $this->readUsers, [
'.r:*', $this->swiftUser ] );
1523 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1526 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1527 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1530 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1532 'url' => $this->
storageUrl( $auth, $container ),
1534 'x-container-read' => implode(
',',
$readUsers ),
1535 'x-container-write' => implode(
',',
$writeUsers )
1539 if ( $rcode === 201 ) {
1541 } elseif ( $rcode === 202 ) {
1544 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1562 $status->fatal(
'backend-fail-connect', $this->name );
1567 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1568 'method' =>
'DELETE',
1569 'url' => $this->
storageUrl( $auth, $container ),
1573 if ( $rcode >= 200 && $rcode <= 299 ) {
1574 $this->containerStatCache->clear( $container );
1575 } elseif ( $rcode === 404 ) {
1577 } elseif ( $rcode === 409 ) {
1578 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1581 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1600 $fullCont,
$type, $limit, $after =
null, $prefix =
null, $delim =
null
1606 $status->fatal(
'backend-fail-connect', $this->name );
1611 $query = [
'limit' => $limit ];
1612 if (
$type ===
'info' ) {
1613 $query[
'format'] =
'json';
1615 if ( $after !==
null ) {
1616 $query[
'marker'] = $after;
1618 if ( $prefix !==
null ) {
1619 $query[
'prefix'] = $prefix;
1621 if ( $delim !==
null ) {
1622 $query[
'delimiter'] = $delim;
1625 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1627 'url' => $this->
storageUrl( $auth, $fullCont ),
1632 $params = [
'cont' => $fullCont,
'prefix' => $prefix,
'delim' => $delim ];
1633 if ( $rcode === 200 ) {
1634 if (
$type ===
'info' ) {
1635 $status->value = FormatJson::decode( trim( $rbody ) );
1637 $status->value = explode(
"\n", trim( $rbody ) );
1639 } elseif ( $rcode === 204 ) {
1640 $status->value = [];
1641 } elseif ( $rcode === 404 ) {
1642 $status->value = [];
1644 $this->
onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1651 foreach ( $containerInfo as $container => $info ) {
1652 $this->containerStatCache->setField( $container,
'stat', $info );
1663 foreach ( $params[
'srcs'] as
$path ) {
1665 if ( $srcRel ===
null || !$auth ) {
1671 if ( $cstat === self::$RES_ABSENT ) {
1674 } elseif ( !is_array( $cstat ) ) {
1681 'url' => $this->
storageUrl( $auth, $srcCont, $srcRel ),
1687 $opts = [
'maxConnsPerHost' => $params[
'concurrency'] ];
1688 $reqs = $this->http->runMulti( $reqs, $opts );
1689 foreach ( $reqs as
$path => $op ) {
1690 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op[
'response'];
1691 if ( $rcode === 200 || $rcode === 204 ) {
1693 if ( !empty( $params[
'requireSHA1'] ) ) {
1698 if ( $this->isRGW ) {
1699 $stat[
'latest'] =
true;
1701 } elseif ( $rcode === 404 ) {
1705 $this->
onError(
null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1707 $stats[
$path] = $stat;
1727 'size' => isset( $rhdrs[
'content-length'] ) ? (int)$rhdrs[
'content-length'] : 0,
1728 'sha1' => $metadata[
'sha1base36'] ??
null,
1730 'md5' => ctype_xdigit( $rhdrs[
'etag'] ) ? $rhdrs[
'etag'] :
null,
1731 'xattr' => [
'metadata' => $metadata,
'headers' => $headers ]
1739 if ( $this->authErrorTimestamp !==
null ) {
1740 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1743 $this->authErrorTimestamp =
null;
1749 if ( !$this->authCreds || $reAuth ) {
1750 $this->authSessionTimestamp = 0;
1752 $creds = $this->srvCache->get( $cacheKey );
1754 if ( isset( $creds[
'auth_token'] ) && isset( $creds[
'storage_url'] ) ) {
1755 $this->authCreds = $creds;
1757 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1759 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( [
1761 'url' =>
"{$this->swiftAuthUrl}/v1.0",
1763 'x-auth-user' => $this->swiftUser,
1764 'x-auth-key' => $this->swiftKey
1768 if ( $rcode >= 200 && $rcode <= 299 ) {
1769 $this->authCreds = [
1770 'auth_token' => $rhdrs[
'x-auth-token'],
1771 'storage_url' => $this->swiftStorageUrl ?? $rhdrs[
'x-storage-url']
1774 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1775 $this->authSessionTimestamp = time();
1776 } elseif ( $rcode === 401 ) {
1777 $this->
onError(
null, __METHOD__, [],
"Authentication failed.", $rcode );
1778 $this->authErrorTimestamp = time();
1782 $this->
onError(
null, __METHOD__, [],
"HTTP return code: $rcode", $rcode );
1783 $this->authErrorTimestamp = time();
1789 if ( substr( $this->authCreds[
'storage_url'], -3 ) ===
'/v1' ) {
1790 $this->isRGW =
true;
1803 protected function storageUrl( array $creds, $container =
null, $object =
null ) {
1804 $parts = [ $creds[
'storage_url'] ];
1805 if ( strlen( $container ) ) {
1806 $parts[] = rawurlencode( $container );
1808 if ( strlen( $object ) ) {
1809 $parts[] = str_replace(
"%2F",
"/", rawurlencode( $object ) );
1812 return implode(
'/', $parts );
1820 return [
'x-auth-token' => $creds[
'auth_token'] ];
1830 return 'swiftcredentials:' . md5( $username .
':' . $this->swiftAuthUrl );
1844 public function onError( $status, $func, array $params, $err =
'', $code = 0, $desc =
'' ) {
1846 $status->fatal(
'backend-fail-internal', $this->name );
1848 if ( $code == 401 ) {
1851 $msg =
"HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1856 'req_params' => FormatJson::encode( $params ),
1860 $msgParams[
'err'] = $err;
1862 $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)
setLogger(LoggerInterface $logger)
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.
foreach( $mmfl['setupFiles'] as $fileName) if($queue) if(empty( $mmfl['quiet'])) $s
if(!is_readable( $file)) $ext