Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
24.80% |
243 / 980 |
|
12.28% |
7 / 57 |
CRAP | |
0.00% |
0 / 1 |
SwiftFileBackend | |
24.82% |
243 / 979 |
|
12.28% |
7 / 57 |
38285.37 | |
0.00% |
0 / 1 |
__construct | |
89.66% |
26 / 29 |
|
0.00% |
0 / 1 |
7.05 | |||
setLogger | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
getFeatures | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
2 | |||
resolveContainerPath | |
60.00% |
3 / 5 |
|
0.00% |
0 / 1 |
3.58 | |||
isPathUsableInternal | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
6 | |||
extractMutableContentHeaders | |
95.00% |
19 / 20 |
|
0.00% |
0 / 1 |
12 | |||
extractMetadataHeaders | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
getMetadataFromHeaders | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
doCreateInternal | |
0.00% |
0 / 37 |
|
0.00% |
0 / 1 |
42 | |||
doStoreInternal | |
0.00% |
0 / 57 |
|
0.00% |
0 / 1 |
90 | |||
doCopyInternal | |
0.00% |
0 / 36 |
|
0.00% |
0 / 1 |
56 | |||
doMoveInternal | |
0.00% |
0 / 45 |
|
0.00% |
0 / 1 |
132 | |||
doDeleteInternal | |
0.00% |
0 / 26 |
|
0.00% |
0 / 1 |
42 | |||
doDescribeInternal | |
0.00% |
0 / 35 |
|
0.00% |
0 / 1 |
90 | |||
doPrepareInternal | |
70.00% |
7 / 10 |
|
0.00% |
0 / 1 |
3.24 | |||
doSecureInternal | |
47.06% |
8 / 17 |
|
0.00% |
0 / 1 |
6.37 | |||
doPublishInternal | |
0.00% |
0 / 19 |
|
0.00% |
0 / 1 |
30 | |||
doCleanInternal | |
61.54% |
8 / 13 |
|
0.00% |
0 / 1 |
8.05 | |||
doGetFileStat | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 | |||
convertSwiftDate | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
12 | |||
addMissingHashMetadata | |
0.00% |
0 / 30 |
|
0.00% |
0 / 1 |
56 | |||
doGetFileContentsMulti | |
71.79% |
28 / 39 |
|
0.00% |
0 / 1 |
10.82 | |||
doDirectoryExists | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
12 | |||
getDirectoryListInternal | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
getFileListInternal | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getDirListPageInternal | |
0.00% |
0 / 36 |
|
0.00% |
0 / 1 |
306 | |||
getFileListPageInternal | |
42.86% |
9 / 21 |
|
0.00% |
0 / 1 |
24.11 | |||
buildFileObjectListing | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
56 | |||
loadListingStatInternal | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
doGetFileXAttributes | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
30 | |||
doGetFileSha1base36 | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
12 | |||
doStreamFile | |
0.00% |
0 / 36 |
|
0.00% |
0 / 1 |
156 | |||
doGetLocalCopyMulti | |
65.31% |
32 / 49 |
|
0.00% |
0 / 1 |
18.01 | |||
addShellboxInputFile | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
20 | |||
getFileHttpUrl | |
0.00% |
0 / 50 |
|
0.00% |
0 / 1 |
72 | |||
directoriesAreVirtual | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
headersFromParams | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
2.06 | |||
doExecuteOpHandlesInternal | |
0.00% |
0 / 20 |
|
0.00% |
0 / 1 |
72 | |||
setContainerAccess | |
0.00% |
0 / 14 |
|
0.00% |
0 / 1 |
12 | |||
getContainerStat | |
60.00% |
15 / 25 |
|
0.00% |
0 / 1 |
10.14 | |||
createContainer | |
0.00% |
0 / 20 |
|
0.00% |
0 / 1 |
30 | |||
deleteContainer | |
0.00% |
0 / 12 |
|
0.00% |
0 / 1 |
30 | |||
objectListing | |
65.38% |
17 / 26 |
|
0.00% |
0 / 1 |
12.36 | |||
doPrimeContainerCache | |
50.00% |
1 / 2 |
|
0.00% |
0 / 1 |
2.50 | |||
doGetFileStatMulti | |
42.11% |
16 / 38 |
|
0.00% |
0 / 1 |
34.48 | |||
getStatFromHeaders | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
12 | |||
getAuthentication | |
42.11% |
8 / 19 |
|
0.00% |
0 / 1 |
20.42 | |||
setAuthCreds | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
20 | |||
refreshAuthentication | |
0.00% |
0 / 28 |
|
0.00% |
0 / 1 |
30 | |||
storageUrl | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
12 | |||
authTokenHeaders | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
getCredsCacheKey | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
requestWithAuth | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
requestMultiWithAuth | |
39.13% |
9 / 23 |
|
0.00% |
0 / 1 |
38.29 | |||
getAuthFailureResponse | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
1 | |||
isAuthFailureResponse | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
onError | |
20.00% |
4 / 20 |
|
0.00% |
0 / 1 |
24.43 |
1 | <?php |
2 | /** |
3 | * OpenStack Swift based file backend. |
4 | * |
5 | * This program is free software; you can redistribute it and/or modify |
6 | * it under the terms of the GNU General Public License as published by |
7 | * the Free Software Foundation; either version 2 of the License, or |
8 | * (at your option) any later version. |
9 | * |
10 | * This program is distributed in the hope that it will be useful, |
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13 | * GNU General Public License for more details. |
14 | * |
15 | * You should have received a copy of the GNU General Public License along |
16 | * with this program; if not, write to the Free Software Foundation, Inc., |
17 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
18 | * http://www.gnu.org/copyleft/gpl.html |
19 | * |
20 | * @file |
21 | * @ingroup FileBackend |
22 | * @author Russ Nelson |
23 | */ |
24 | |
25 | namespace Wikimedia\FileBackend; |
26 | |
27 | use Exception; |
28 | use LockManager; |
29 | use MapCacheLRU; |
30 | use Psr\Log\LoggerInterface; |
31 | use Shellbox\Command\BoxedCommand; |
32 | use StatusValue; |
33 | use stdClass; |
34 | use Wikimedia\AtEase\AtEase; |
35 | use Wikimedia\FileBackend\FileIteration\SwiftFileBackendDirList; |
36 | use Wikimedia\FileBackend\FileIteration\SwiftFileBackendFileList; |
37 | use Wikimedia\FileBackend\FileOpHandle\SwiftFileOpHandle; |
38 | use Wikimedia\Http\MultiHttpClient; |
39 | use Wikimedia\ObjectCache\BagOStuff; |
40 | use Wikimedia\ObjectCache\EmptyBagOStuff; |
41 | use Wikimedia\ObjectCache\WANObjectCache; |
42 | use Wikimedia\RequestTimeout\TimeoutException; |
43 | use Wikimedia\Timestamp\ConvertibleTimestamp; |
44 | |
45 | /** |
46 | * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend. |
47 | * |
48 | * StatusValue messages should avoid mentioning the Swift account name. |
49 | * Likewise, error suppression should be used to avoid path disclosure. |
50 | * |
51 | * @ingroup FileBackend |
52 | * @since 1.19 |
53 | */ |
54 | class SwiftFileBackend extends FileBackendStore { |
55 | private const DEFAULT_HTTP_OPTIONS = [ 'httpVersion' => 'v1.1' ]; |
56 | private const AUTH_FAILURE_ERROR = 'Could not connect due to prior authentication failure'; |
57 | |
58 | /** @var MultiHttpClient */ |
59 | protected $http; |
60 | /** @var int TTL in seconds */ |
61 | protected $authTTL; |
62 | /** @var string Authentication base URL (without version) */ |
63 | protected $swiftAuthUrl; |
64 | /** @var string Override of storage base URL */ |
65 | protected $swiftStorageUrl; |
66 | /** @var string Swift user (account:user) to authenticate as */ |
67 | protected $swiftUser; |
68 | /** @var string Secret key for user */ |
69 | protected $swiftKey; |
70 | /** @var string Shared secret value for making temp URLs */ |
71 | protected $swiftTempUrlKey; |
72 | /** @var bool */ |
73 | protected $canShellboxGetTempUrl; |
74 | /** @var string|null */ |
75 | protected $shellboxIpRange; |
76 | /** @var string S3 access key (RADOS Gateway) */ |
77 | protected $rgwS3AccessKey; |
78 | /** @var string S3 authentication key (RADOS Gateway) */ |
79 | protected $rgwS3SecretKey; |
80 | /** @var array Additional users (account:user) with read permissions on public containers */ |
81 | protected $readUsers; |
82 | /** @var array Additional users (account:user) with write permissions on public containers */ |
83 | protected $writeUsers; |
84 | /** @var array Additional users (account:user) with read permissions on private containers */ |
85 | protected $secureReadUsers; |
86 | /** @var array Additional users (account:user) with write permissions on private containers */ |
87 | protected $secureWriteUsers; |
88 | |
89 | /** @var BagOStuff */ |
90 | protected $srvCache; |
91 | |
92 | /** @var MapCacheLRU Container stat cache */ |
93 | protected $containerStatCache; |
94 | |
95 | /** @var array|null */ |
96 | protected $authCreds; |
97 | /** @var int|null UNIX timestamp */ |
98 | protected $authErrorTimestamp = null; |
99 | |
100 | /** @var bool Whether the server is an Ceph RGW */ |
101 | protected $isRGW = false; |
102 | |
103 | /** |
104 | * @see FileBackendStore::__construct() |
105 | * @param array $config Params include: |
106 | * - swiftAuthUrl : Swift authentication server URL |
107 | * - swiftUser : Swift user used by MediaWiki (account:username) |
108 | * - swiftKey : Swift authentication key for the above user |
109 | * - swiftAuthTTL : Swift authentication TTL (seconds) |
110 | * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account. |
111 | * Do not set this until it has been set in the backend. |
112 | * - canShellboxGetTempUrl : Set this to true to generate a TempURL allowing Shellbox to |
113 | * directly fetch files from Swift. swiftTempUrlKey should be set. |
114 | * - shellboxIpRange : An IP range string to use when generating TempURLs for Shellbox. |
115 | * Specifying this will improve security by preventing exfiltrated |
116 | * TempURLs from being usable outside the server. |
117 | * - swiftStorageUrl : Swift storage URL (overrides that of the authentication response). |
118 | * This is useful to set if a TLS proxy is in use. |
119 | * - shardViaHashLevels : Map of container names to sharding config with: |
120 | * - base : base of hash characters, 16 or 36 |
121 | * - levels : the number of hash levels (and digits) |
122 | * - repeat : hash subdirectories are prefixed with all the |
123 | * parent hash directory names (e.g. "a/ab/abc") |
124 | * - cacheAuthInfo : Whether to cache authentication tokens in APC, etc. |
125 | * If those are not available, then the main cache will be used. |
126 | * This is probably insecure in shared hosting environments. |
127 | * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account. |
128 | * Do not set this until it has been set in the backend. |
129 | * This is used for generating expiring pre-authenticated URLs. |
130 | * Only use this when using rgw and to work around |
131 | * http://tracker.newdream.net/issues/3454. |
132 | * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account. |
133 | * Do not set this until it has been set in the backend. |
134 | * This is used for generating expiring pre-authenticated URLs. |
135 | * Only use this when using rgw and to work around |
136 | * http://tracker.newdream.net/issues/3454. |
137 | * - readUsers : Swift users with read access to public containers (account:username) |
138 | * - writeUsers : Swift users with write access to public containers (account:username) |
139 | * - secureReadUsers : Swift users with read access to private containers (account:username) |
140 | * - secureWriteUsers : Swift users with write access to private containers (account:username) |
141 | * - connTimeout : The HTTP connect timeout to use when connecting to Swift, in |
142 | * seconds. |
143 | * - reqTimeout : The HTTP request timeout to use when communicating with Swift, in |
144 | * seconds. |
145 | */ |
146 | public function __construct( array $config ) { |
147 | parent::__construct( $config ); |
148 | // Required settings |
149 | $this->swiftAuthUrl = $config['swiftAuthUrl']; |
150 | $this->swiftUser = $config['swiftUser']; |
151 | $this->swiftKey = $config['swiftKey']; |
152 | // Optional settings |
153 | $this->authTTL = $config['swiftAuthTTL'] ?? 15 * 60; // some sensible number |
154 | $this->swiftTempUrlKey = $config['swiftTempUrlKey'] ?? ''; |
155 | $this->canShellboxGetTempUrl = $config['canShellboxGetTempUrl'] ?? false; |
156 | $this->shellboxIpRange = $config['shellboxIpRange'] ?? null; |
157 | $this->swiftStorageUrl = $config['swiftStorageUrl'] ?? null; |
158 | $this->shardViaHashLevels = $config['shardViaHashLevels'] ?? ''; |
159 | $this->rgwS3AccessKey = $config['rgwS3AccessKey'] ?? ''; |
160 | $this->rgwS3SecretKey = $config['rgwS3SecretKey'] ?? ''; |
161 | |
162 | // HTTP helper client |
163 | $httpOptions = []; |
164 | foreach ( [ 'connTimeout', 'reqTimeout' ] as $optionName ) { |
165 | if ( isset( $config[$optionName] ) ) { |
166 | $httpOptions[$optionName] = $config[$optionName]; |
167 | } |
168 | } |
169 | $this->http = new MultiHttpClient( $httpOptions ); |
170 | $this->http->setLogger( $this->logger ); |
171 | |
172 | // Cache container information to mask latency |
173 | if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache ) { |
174 | $this->memCache = $config['wanCache']; |
175 | } |
176 | // Process cache for container info |
177 | $this->containerStatCache = new MapCacheLRU( 300 ); |
178 | // Cache auth token information to avoid RTTs |
179 | if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) { |
180 | $this->srvCache = $config['srvCache']; |
181 | } else { |
182 | $this->srvCache = new EmptyBagOStuff(); |
183 | } |
184 | $this->readUsers = $config['readUsers'] ?? []; |
185 | $this->writeUsers = $config['writeUsers'] ?? []; |
186 | $this->secureReadUsers = $config['secureReadUsers'] ?? []; |
187 | $this->secureWriteUsers = $config['secureWriteUsers'] ?? []; |
188 | // Per https://docs.openstack.org/swift/latest/overview_large_objects.html |
189 | // we need to split objects if they are larger than 5 GB. Support for |
190 | // splitting objects has not yet been implemented by this class |
191 | // so limit max file size to 5GiB. |
192 | $this->maxFileSize = 5 * 1024 * 1024 * 1024; |
193 | } |
194 | |
195 | public function setLogger( LoggerInterface $logger ) { |
196 | parent::setLogger( $logger ); |
197 | $this->http->setLogger( $logger ); |
198 | } |
199 | |
200 | public function getFeatures() { |
201 | return ( |
202 | self::ATTR_UNICODE_PATHS | |
203 | self::ATTR_HEADERS | |
204 | self::ATTR_METADATA |
205 | ); |
206 | } |
207 | |
208 | protected function resolveContainerPath( $container, $relStoragePath ) { |
209 | if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { |
210 | return null; // not UTF-8, makes it hard to use CF and the swift HTTP API |
211 | } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) { |
212 | return null; // too long for Swift |
213 | } |
214 | |
215 | return $relStoragePath; |
216 | } |
217 | |
218 | public function isPathUsableInternal( $storagePath ) { |
219 | [ $container, $rel ] = $this->resolveStoragePathReal( $storagePath ); |
220 | if ( $rel === null ) { |
221 | return false; // invalid |
222 | } |
223 | |
224 | return is_array( $this->getContainerStat( $container ) ); |
225 | } |
226 | |
227 | /** |
228 | * Filter/normalize a header map to only include mutable "content-"/"x-content-" headers |
229 | * |
230 | * Mutable headers can be changed via HTTP POST even if the file content is the same |
231 | * |
232 | * @see https://docs.openstack.org/api-ref/object-store |
233 | * @param string[] $headers Map of (header => value) for a swift object |
234 | * @return string[] Map of (header => value) for Content-* headers mutable via POST |
235 | */ |
236 | protected function extractMutableContentHeaders( array $headers ) { |
237 | $contentHeaders = []; |
238 | // Normalize casing, and strip out illegal headers |
239 | foreach ( $headers as $name => $value ) { |
240 | $name = strtolower( $name ); |
241 | if ( $name === 'x-delete-at' && is_numeric( $value ) ) { |
242 | // Expects a Unix Epoch date |
243 | $contentHeaders[$name] = $value; |
244 | } elseif ( $name === 'x-delete-after' && is_numeric( $value ) ) { |
245 | // Expects number of minutes time to live. |
246 | $contentHeaders[$name] = $value; |
247 | } elseif ( preg_match( '/^(x-)?content-(?!length$)/', $name ) ) { |
248 | // Only allow content-* and x-content-* headers (but not content-length) |
249 | $contentHeaders[$name] = $value; |
250 | } elseif ( $name === 'content-type' && $value !== '' ) { |
251 | // This header can be set to a value but not unset |
252 | $contentHeaders[$name] = $value; |
253 | } |
254 | } |
255 | // By default, Swift has annoyingly low maximum header value limits |
256 | if ( isset( $contentHeaders['content-disposition'] ) ) { |
257 | $maxLength = 255; |
258 | // @note: assume FileBackend::makeContentDisposition() already used |
259 | $offset = $maxLength - strlen( $contentHeaders['content-disposition'] ); |
260 | if ( $offset < 0 ) { |
261 | $pos = strrpos( $contentHeaders['content-disposition'], ';', $offset ); |
262 | $contentHeaders['content-disposition'] = $pos === false |
263 | ? '' |
264 | : trim( substr( $contentHeaders['content-disposition'], 0, $pos ) ); |
265 | } |
266 | } |
267 | |
268 | return $contentHeaders; |
269 | } |
270 | |
271 | /** |
272 | * @see https://docs.openstack.org/api-ref/object-store |
273 | * @param string[] $headers Map of (header => value) for a swift object |
274 | * @return string[] Map of (metadata header name => metadata value) |
275 | */ |
276 | protected function extractMetadataHeaders( array $headers ) { |
277 | $metadataHeaders = []; |
278 | foreach ( $headers as $name => $value ) { |
279 | $name = strtolower( $name ); |
280 | if ( strpos( $name, 'x-object-meta-' ) === 0 ) { |
281 | $metadataHeaders[$name] = $value; |
282 | } |
283 | } |
284 | |
285 | return $metadataHeaders; |
286 | } |
287 | |
288 | /** |
289 | * @see https://docs.openstack.org/api-ref/object-store |
290 | * @param string[] $headers Map of (header => value) for a swift object |
291 | * @return string[] Map of (metadata key name => metadata value) |
292 | */ |
293 | protected function getMetadataFromHeaders( array $headers ) { |
294 | $prefixLen = strlen( 'x-object-meta-' ); |
295 | |
296 | $metadata = []; |
297 | foreach ( $this->extractMetadataHeaders( $headers ) as $name => $value ) { |
298 | $metadata[substr( $name, $prefixLen )] = $value; |
299 | } |
300 | |
301 | return $metadata; |
302 | } |
303 | |
304 | protected function doCreateInternal( array $params ) { |
305 | $status = $this->newStatus(); |
306 | |
307 | [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] ); |
308 | if ( $dstRel === null ) { |
309 | $status->fatal( 'backend-fail-invalidpath', $params['dst'] ); |
310 | |
311 | return $status; |
312 | } |
313 | |
314 | // Headers that are not strictly a function of the file content |
315 | $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] ); |
316 | // Make sure that the "content-type" header is set to something sensible |
317 | $mutableHeaders['content-type'] |
318 | ??= $this->getContentType( $params['dst'], $params['content'], null ); |
319 | |
320 | $reqs = [ [ |
321 | 'method' => 'PUT', |
322 | 'container' => $dstCont, |
323 | 'relPath' => $dstRel, |
324 | 'headers' => array_merge( |
325 | $mutableHeaders, |
326 | [ |
327 | 'etag' => md5( $params['content'] ), |
328 | 'content-length' => strlen( $params['content'] ), |
329 | 'x-object-meta-sha1base36' => |
330 | \Wikimedia\base_convert( sha1( $params['content'] ), 16, 36, 31 ) |
331 | ] |
332 | ), |
333 | 'body' => $params['content'] |
334 | ] ]; |
335 | |
336 | $method = __METHOD__; |
337 | $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) { |
338 | [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response']; |
339 | if ( $rcode === 201 || $rcode === 202 ) { |
340 | // good |
341 | } elseif ( $rcode === 412 ) { |
342 | $status->fatal( 'backend-fail-contenttype', $params['dst'] ); |
343 | } else { |
344 | $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody ); |
345 | } |
346 | |
347 | return SwiftFileOpHandle::CONTINUE_IF_OK; |
348 | }; |
349 | |
350 | $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs ); |
351 | if ( !empty( $params['async'] ) ) { // deferred |
352 | $status->value = $opHandle; |
353 | } else { // actually write the object in Swift |
354 | $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) ); |
355 | } |
356 | |
357 | return $status; |
358 | } |
359 | |
360 | protected function doStoreInternal( array $params ) { |
361 | $status = $this->newStatus(); |
362 | |
363 | [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] ); |
364 | if ( $dstRel === null ) { |
365 | $status->fatal( 'backend-fail-invalidpath', $params['dst'] ); |
366 | |
367 | return $status; |
368 | } |
369 | |
370 | // Open a handle to the source file so that it can be streamed. The size and hash |
371 | // will be computed using the handle. In the off chance that the source file changes |
372 | // during this operation, the PUT will fail due to an ETag mismatch and be aborted. |
373 | AtEase::suppressWarnings(); |
374 | $srcHandle = fopen( $params['src'], 'rb' ); |
375 | AtEase::restoreWarnings(); |
376 | if ( $srcHandle === false ) { // source doesn't exist? |
377 | $status->fatal( 'backend-fail-notexists', $params['src'] ); |
378 | |
379 | return $status; |
380 | } |
381 | |
382 | // Compute the MD5 and SHA-1 hashes in one pass |
383 | $srcSize = fstat( $srcHandle )['size']; |
384 | $md5Context = hash_init( 'md5' ); |
385 | $sha1Context = hash_init( 'sha1' ); |
386 | $hashDigestSize = 0; |
387 | while ( !feof( $srcHandle ) ) { |
388 | $buffer = (string)fread( $srcHandle, 131_072 ); // 128 KiB |
389 | hash_update( $md5Context, $buffer ); |
390 | hash_update( $sha1Context, $buffer ); |
391 | $hashDigestSize += strlen( $buffer ); |
392 | } |
393 | // Reset the handle back to the beginning so that it can be streamed |
394 | rewind( $srcHandle ); |
395 | |
396 | if ( $hashDigestSize !== $srcSize ) { |
397 | $status->fatal( 'backend-fail-hash', $params['src'] ); |
398 | |
399 | return $status; |
400 | } |
401 | |
402 | // Headers that are not strictly a function of the file content |
403 | $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] ); |
404 | // Make sure that the "content-type" header is set to something sensible |
405 | $mutableHeaders['content-type'] |
406 | ??= $this->getContentType( $params['dst'], null, $params['src'] ); |
407 | |
408 | $reqs = [ [ |
409 | 'method' => 'PUT', |
410 | 'container' => $dstCont, |
411 | 'relPath' => $dstRel, |
412 | 'headers' => array_merge( |
413 | $mutableHeaders, |
414 | [ |
415 | 'content-length' => $srcSize, |
416 | 'etag' => hash_final( $md5Context ), |
417 | 'x-object-meta-sha1base36' => |
418 | \Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 ) |
419 | ] |
420 | ), |
421 | 'body' => $srcHandle // resource |
422 | ] ]; |
423 | |
424 | $method = __METHOD__; |
425 | $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) { |
426 | [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response']; |
427 | if ( $rcode === 201 || $rcode === 202 ) { |
428 | // good |
429 | } elseif ( $rcode === 412 ) { |
430 | $status->fatal( 'backend-fail-contenttype', $params['dst'] ); |
431 | } else { |
432 | $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody ); |
433 | } |
434 | |
435 | return SwiftFileOpHandle::CONTINUE_IF_OK; |
436 | }; |
437 | |
438 | $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs ); |
439 | $opHandle->resourcesToClose[] = $srcHandle; |
440 | |
441 | if ( !empty( $params['async'] ) ) { // deferred |
442 | $status->value = $opHandle; |
443 | } else { // actually write the object in Swift |
444 | $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) ); |
445 | } |
446 | |
447 | return $status; |
448 | } |
449 | |
450 | protected function doCopyInternal( array $params ) { |
451 | $status = $this->newStatus(); |
452 | |
453 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] ); |
454 | if ( $srcRel === null ) { |
455 | $status->fatal( 'backend-fail-invalidpath', $params['src'] ); |
456 | |
457 | return $status; |
458 | } |
459 | |
460 | [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] ); |
461 | if ( $dstRel === null ) { |
462 | $status->fatal( 'backend-fail-invalidpath', $params['dst'] ); |
463 | |
464 | return $status; |
465 | } |
466 | |
467 | $reqs = [ [ |
468 | 'method' => 'PUT', |
469 | 'container' => $dstCont, |
470 | 'relPath' => $dstRel, |
471 | 'headers' => array_merge( |
472 | $this->extractMutableContentHeaders( $params['headers'] ?? [] ), |
473 | [ |
474 | 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' . |
475 | str_replace( "%2F", "/", rawurlencode( $srcRel ) ) |
476 | ] |
477 | ) |
478 | ] ]; |
479 | |
480 | $method = __METHOD__; |
481 | $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) { |
482 | [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response']; |
483 | if ( $rcode === 201 ) { |
484 | // good |
485 | } elseif ( $rcode === 404 ) { |
486 | if ( empty( $params['ignoreMissingSource'] ) ) { |
487 | $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] ); |
488 | } |
489 | } else { |
490 | $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody ); |
491 | } |
492 | |
493 | return SwiftFileOpHandle::CONTINUE_IF_OK; |
494 | }; |
495 | |
496 | $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs ); |
497 | if ( !empty( $params['async'] ) ) { // deferred |
498 | $status->value = $opHandle; |
499 | } else { // actually write the object in Swift |
500 | $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) ); |
501 | } |
502 | |
503 | return $status; |
504 | } |
505 | |
506 | protected function doMoveInternal( array $params ) { |
507 | $status = $this->newStatus(); |
508 | |
509 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] ); |
510 | if ( $srcRel === null ) { |
511 | $status->fatal( 'backend-fail-invalidpath', $params['src'] ); |
512 | |
513 | return $status; |
514 | } |
515 | |
516 | [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] ); |
517 | if ( $dstRel === null ) { |
518 | $status->fatal( 'backend-fail-invalidpath', $params['dst'] ); |
519 | |
520 | return $status; |
521 | } |
522 | |
523 | $reqs = [ [ |
524 | 'method' => 'PUT', |
525 | 'container' => $dstCont, |
526 | 'relPath' => $dstRel, |
527 | 'headers' => array_merge( |
528 | $this->extractMutableContentHeaders( $params['headers'] ?? [] ), |
529 | [ |
530 | 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' . |
531 | str_replace( "%2F", "/", rawurlencode( $srcRel ) ) |
532 | ] |
533 | ) |
534 | ] ]; |
535 | if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) { |
536 | $reqs[] = [ |
537 | 'method' => 'DELETE', |
538 | 'container' => $srcCont, |
539 | 'relPath' => $srcRel, |
540 | 'headers' => [] |
541 | ]; |
542 | } |
543 | |
544 | $method = __METHOD__; |
545 | $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) { |
546 | [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response']; |
547 | if ( $request['method'] === 'PUT' && $rcode === 201 ) { |
548 | // good |
549 | } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) { |
550 | // good |
551 | } elseif ( $rcode === 404 ) { |
552 | if ( empty( $params['ignoreMissingSource'] ) ) { |
553 | $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] ); |
554 | } else { |
555 | // Leave Status as OK but skip the DELETE request |
556 | return SwiftFileOpHandle::CONTINUE_NO; |
557 | } |
558 | } else { |
559 | $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody ); |
560 | } |
561 | |
562 | return SwiftFileOpHandle::CONTINUE_IF_OK; |
563 | }; |
564 | |
565 | $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs ); |
566 | if ( !empty( $params['async'] ) ) { // deferred |
567 | $status->value = $opHandle; |
568 | } else { // actually move the object in Swift |
569 | $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) ); |
570 | } |
571 | |
572 | return $status; |
573 | } |
574 | |
575 | protected function doDeleteInternal( array $params ) { |
576 | $status = $this->newStatus(); |
577 | |
578 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] ); |
579 | if ( $srcRel === null ) { |
580 | $status->fatal( 'backend-fail-invalidpath', $params['src'] ); |
581 | |
582 | return $status; |
583 | } |
584 | |
585 | $reqs = [ [ |
586 | 'method' => 'DELETE', |
587 | 'container' => $srcCont, |
588 | 'relPath' => $srcRel, |
589 | 'headers' => [] |
590 | ] ]; |
591 | |
592 | $method = __METHOD__; |
593 | $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) { |
594 | [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response']; |
595 | if ( $rcode === 204 ) { |
596 | // good |
597 | } elseif ( $rcode === 404 ) { |
598 | if ( empty( $params['ignoreMissingSource'] ) ) { |
599 | $status->fatal( 'backend-fail-delete', $params['src'] ); |
600 | } |
601 | } else { |
602 | $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody ); |
603 | } |
604 | |
605 | return SwiftFileOpHandle::CONTINUE_IF_OK; |
606 | }; |
607 | |
608 | $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs ); |
609 | if ( !empty( $params['async'] ) ) { // deferred |
610 | $status->value = $opHandle; |
611 | } else { // actually delete the object in Swift |
612 | $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) ); |
613 | } |
614 | |
615 | return $status; |
616 | } |
617 | |
618 | protected function doDescribeInternal( array $params ) { |
619 | $status = $this->newStatus(); |
620 | |
621 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] ); |
622 | if ( $srcRel === null ) { |
623 | $status->fatal( 'backend-fail-invalidpath', $params['src'] ); |
624 | |
625 | return $status; |
626 | } |
627 | |
628 | // Fetch the old object headers/metadata...this should be in stat cache by now |
629 | $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] ); |
630 | if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry |
631 | $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] ); |
632 | } |
633 | if ( !$stat ) { |
634 | $status->fatal( 'backend-fail-describe', $params['src'] ); |
635 | |
636 | return $status; |
637 | } |
638 | |
639 | // Swift object POST clears any prior headers, so merge the new and old headers here. |
640 | // Also, during, POST, libcurl adds "Content-Type: application/x-www-form-urlencoded" |
641 | // if "Content-Type" is not set, which would clobber the header value for the object. |
642 | $oldMetadataHeaders = []; |
643 | foreach ( $stat['xattr']['metadata'] as $name => $value ) { |
644 | $oldMetadataHeaders["x-object-meta-$name"] = $value; |
645 | } |
646 | $newContentHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] ); |
647 | $oldContentHeaders = $stat['xattr']['headers']; |
648 | |
649 | $reqs = [ [ |
650 | 'method' => 'POST', |
651 | 'container' => $srcCont, |
652 | 'relPath' => $srcRel, |
653 | 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders |
654 | ] ]; |
655 | |
656 | $method = __METHOD__; |
657 | $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) { |
658 | [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response']; |
659 | if ( $rcode === 202 ) { |
660 | // good |
661 | } elseif ( $rcode === 404 ) { |
662 | $status->fatal( 'backend-fail-describe', $params['src'] ); |
663 | } else { |
664 | $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody ); |
665 | } |
666 | }; |
667 | |
668 | $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs ); |
669 | if ( !empty( $params['async'] ) ) { // deferred |
670 | $status->value = $opHandle; |
671 | } else { // actually change the object in Swift |
672 | $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) ); |
673 | } |
674 | |
675 | return $status; |
676 | } |
677 | |
678 | /** |
679 | * @inheritDoc |
680 | */ |
681 | protected function doPrepareInternal( $fullCont, $dir, array $params ) { |
682 | $status = $this->newStatus(); |
683 | |
684 | // (a) Check if container already exists |
685 | $stat = $this->getContainerStat( $fullCont ); |
686 | if ( is_array( $stat ) ) { |
687 | return $status; // already there |
688 | } elseif ( $stat === self::RES_ERROR ) { |
689 | $status->fatal( 'backend-fail-internal', $this->name ); |
690 | $this->logger->error( __METHOD__ . ': cannot get container stat' ); |
691 | } else { |
692 | // (b) Create container as needed with proper ACLs |
693 | $params['op'] = 'prepare'; |
694 | $status->merge( $this->createContainer( $fullCont, $params ) ); |
695 | } |
696 | |
697 | return $status; |
698 | } |
699 | |
700 | protected function doSecureInternal( $fullCont, $dir, array $params ) { |
701 | $status = $this->newStatus(); |
702 | if ( empty( $params['noAccess'] ) ) { |
703 | return $status; // nothing to do |
704 | } |
705 | |
706 | $stat = $this->getContainerStat( $fullCont ); |
707 | if ( is_array( $stat ) ) { |
708 | $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] ); |
709 | $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] ); |
710 | // Make container private to end-users... |
711 | $status->merge( $this->setContainerAccess( |
712 | $fullCont, |
713 | $readUsers, |
714 | $writeUsers |
715 | ) ); |
716 | } elseif ( $stat === self::RES_ABSENT ) { |
717 | $status->fatal( 'backend-fail-usable', $params['dir'] ); |
718 | } else { |
719 | $status->fatal( 'backend-fail-internal', $this->name ); |
720 | $this->logger->error( __METHOD__ . ': cannot get container stat' ); |
721 | } |
722 | |
723 | return $status; |
724 | } |
725 | |
726 | protected function doPublishInternal( $fullCont, $dir, array $params ) { |
727 | $status = $this->newStatus(); |
728 | if ( empty( $params['access'] ) ) { |
729 | return $status; // nothing to do |
730 | } |
731 | |
732 | $stat = $this->getContainerStat( $fullCont ); |
733 | if ( is_array( $stat ) ) { |
734 | $readUsers = array_merge( $this->readUsers, [ $this->swiftUser, '.r:*' ] ); |
735 | if ( !empty( $params['listing'] ) ) { |
736 | array_push( $readUsers, '.rlistings' ); |
737 | } |
738 | $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] ); |
739 | |
740 | // Make container public to end-users... |
741 | $status->merge( $this->setContainerAccess( |
742 | $fullCont, |
743 | $readUsers, |
744 | $writeUsers |
745 | ) ); |
746 | } elseif ( $stat === self::RES_ABSENT ) { |
747 | $status->fatal( 'backend-fail-usable', $params['dir'] ); |
748 | } else { |
749 | $status->fatal( 'backend-fail-internal', $this->name ); |
750 | $this->logger->error( __METHOD__ . ': cannot get container stat' ); |
751 | } |
752 | |
753 | return $status; |
754 | } |
755 | |
756 | protected function doCleanInternal( $fullCont, $dir, array $params ) { |
757 | $status = $this->newStatus(); |
758 | |
759 | // Only containers themselves can be removed, all else is virtual |
760 | if ( $dir != '' ) { |
761 | return $status; // nothing to do |
762 | } |
763 | |
764 | // (a) Check the container |
765 | $stat = $this->getContainerStat( $fullCont, true ); |
766 | if ( $stat === self::RES_ABSENT ) { |
767 | return $status; // ok, nothing to do |
768 | } elseif ( $stat === self::RES_ERROR ) { |
769 | $status->fatal( 'backend-fail-internal', $this->name ); |
770 | $this->logger->error( __METHOD__ . ': cannot get container stat' ); |
771 | } elseif ( is_array( $stat ) && $stat['count'] == 0 ) { |
772 | // (b) Delete the container if empty |
773 | $params['op'] = 'clean'; |
774 | $status->merge( $this->deleteContainer( $fullCont, $params ) ); |
775 | } |
776 | |
777 | return $status; |
778 | } |
779 | |
780 | protected function doGetFileStat( array $params ) { |
781 | $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] + $params; |
782 | unset( $params['src'] ); |
783 | $stats = $this->doGetFileStatMulti( $params ); |
784 | |
785 | return reset( $stats ); |
786 | } |
787 | |
788 | /** |
789 | * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z". |
790 | * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings, |
791 | * missing the timezone suffix (though Ceph RGW does not appear to have this bug). |
792 | * |
793 | * @param string $ts |
794 | * @param int $format Output format (TS_* constant) |
795 | * @return string |
796 | * @throws FileBackendError |
797 | */ |
798 | protected function convertSwiftDate( $ts, $format = TS_MW ) { |
799 | try { |
800 | $timestamp = new ConvertibleTimestamp( $ts ); |
801 | |
802 | return $timestamp->getTimestamp( $format ); |
803 | } catch ( TimeoutException $e ) { |
804 | throw $e; |
805 | } catch ( Exception $e ) { |
806 | throw new FileBackendError( $e->getMessage() ); |
807 | } |
808 | } |
809 | |
810 | /** |
811 | * Fill in any missing object metadata and save it to Swift |
812 | * |
813 | * @param array $objHdrs Object response headers |
814 | * @param string $path Storage path to object |
815 | * @return array New headers |
816 | */ |
817 | protected function addMissingHashMetadata( array $objHdrs, $path ) { |
818 | if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) { |
819 | return $objHdrs; // nothing to do |
820 | } |
821 | |
822 | /** @noinspection PhpUnusedLocalVariableInspection */ |
823 | $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" ); |
824 | $this->logger->error( __METHOD__ . ": {path} was not stored with SHA-1 metadata.", |
825 | [ 'path' => $path ] ); |
826 | |
827 | $objHdrs['x-object-meta-sha1base36'] = false; |
828 | |
829 | // Find prior custom HTTP headers |
830 | $postHeaders = $this->extractMutableContentHeaders( $objHdrs ); |
831 | // Find prior metadata headers |
832 | $postHeaders += $this->extractMetadataHeaders( $objHdrs ); |
833 | |
834 | $status = $this->newStatus(); |
835 | /** @noinspection PhpUnusedLocalVariableInspection */ |
836 | $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager::LOCK_UW, $status ); |
837 | if ( $status->isOK() ) { |
838 | $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] ); |
839 | if ( $tmpFile ) { |
840 | $hash = $tmpFile->getSha1Base36(); |
841 | if ( $hash !== false ) { |
842 | $objHdrs['x-object-meta-sha1base36'] = $hash; |
843 | // Merge new SHA1 header into the old ones |
844 | $postHeaders['x-object-meta-sha1base36'] = $hash; |
845 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path ); |
846 | [ $rcode ] = $this->requestWithAuth( [ |
847 | 'method' => 'POST', |
848 | 'container' => $srcCont, |
849 | 'relPath' => $srcRel, |
850 | 'headers' => $postHeaders |
851 | ] ); |
852 | if ( $rcode >= 200 && $rcode <= 299 ) { |
853 | $this->deleteFileCache( $path ); |
854 | |
855 | return $objHdrs; // success |
856 | } |
857 | } |
858 | } |
859 | } |
860 | |
861 | $this->logger->error( __METHOD__ . ': unable to set SHA-1 metadata for {path}', |
862 | [ 'path' => $path ] ); |
863 | |
864 | return $objHdrs; // failed |
865 | } |
866 | |
867 | protected function doGetFileContentsMulti( array $params ) { |
868 | $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging |
869 | // Blindly create tmp files and stream to them, catching any exception |
870 | // if the file does not exist. Do not waste time doing file stats here. |
871 | $reqs = []; // (path => op) |
872 | |
873 | // Initial dummy values to preserve path order |
874 | $contents = array_fill_keys( $params['srcs'], self::RES_ERROR ); |
875 | foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch |
876 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path ); |
877 | if ( $srcRel === null ) { |
878 | continue; // invalid storage path |
879 | } |
880 | // Create a new temporary memory file... |
881 | $handle = fopen( 'php://temp', 'wb' ); |
882 | if ( $handle ) { |
883 | $reqs[$path] = [ |
884 | 'method' => 'GET', |
885 | 'container' => $srcCont, |
886 | 'relPath' => $srcRel, |
887 | 'headers' => $this->headersFromParams( $params ), |
888 | 'stream' => $handle, |
889 | ]; |
890 | } |
891 | } |
892 | |
893 | $reqs = $this->requestMultiWithAuth( |
894 | $reqs, |
895 | [ 'maxConnsPerHost' => $params['concurrency'] ] |
896 | ); |
897 | foreach ( $reqs as $path => $op ) { |
898 | [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response']; |
899 | if ( $rcode >= 200 && $rcode <= 299 ) { |
900 | rewind( $op['stream'] ); // start from the beginning |
901 | $content = (string)stream_get_contents( $op['stream'] ); |
902 | $size = strlen( $content ); |
903 | // Make sure that stream finished |
904 | if ( $size === (int)$rhdrs['content-length'] ) { |
905 | $contents[$path] = $content; |
906 | } else { |
907 | $contents[$path] = self::RES_ERROR; |
908 | $rerr = "Got {$size}/{$rhdrs['content-length']} bytes"; |
909 | $this->onError( null, __METHOD__, |
910 | [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc ); |
911 | } |
912 | } elseif ( $rcode === 404 ) { |
913 | $contents[$path] = self::RES_ABSENT; |
914 | } else { |
915 | $contents[$path] = self::RES_ERROR; |
916 | $this->onError( null, __METHOD__, |
917 | [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc, $rbody ); |
918 | } |
919 | fclose( $op['stream'] ); // close open handle |
920 | } |
921 | |
922 | return $contents; |
923 | } |
924 | |
925 | protected function doDirectoryExists( $fullCont, $dir, array $params ) { |
926 | $prefix = ( $dir == '' ) ? null : "{$dir}/"; |
927 | $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix ); |
928 | if ( $status->isOK() ) { |
929 | return ( count( $status->value ) ) > 0; |
930 | } |
931 | |
932 | return self::RES_ERROR; |
933 | } |
934 | |
935 | /** |
936 | * @see FileBackendStore::getDirectoryListInternal() |
937 | * @param string $fullCont |
938 | * @param string $dir |
939 | * @param array $params |
940 | * @return SwiftFileBackendDirList |
941 | */ |
942 | public function getDirectoryListInternal( $fullCont, $dir, array $params ) { |
943 | return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params ); |
944 | } |
945 | |
946 | /** |
947 | * @see FileBackendStore::getFileListInternal() |
948 | * @param string $fullCont |
949 | * @param string $dir |
950 | * @param array $params |
951 | * @return SwiftFileBackendFileList |
952 | */ |
953 | public function getFileListInternal( $fullCont, $dir, array $params ) { |
954 | return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params ); |
955 | } |
956 | |
957 | /** |
958 | * Do not call this function outside of SwiftFileBackendFileList |
959 | * |
960 | * @param string $fullCont Resolved container name |
961 | * @param string $dir Resolved storage directory with no trailing slash |
962 | * @param string|null &$after Resolved container relative path used for continuation paging |
963 | * @param int $limit Max number of items to list |
964 | * @param array $params Parameters for {@link getDirectoryList()} |
965 | * @return string[] List of resolved container relative directories directly under $dir |
966 | * @throws FileBackendError |
967 | */ |
968 | public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) { |
969 | $dirs = []; |
970 | if ( $after === INF ) { |
971 | return $dirs; // nothing more |
972 | } |
973 | |
974 | /** @noinspection PhpUnusedLocalVariableInspection */ |
975 | $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" ); |
976 | |
977 | $prefix = ( $dir == '' ) ? null : "{$dir}/"; |
978 | // Non-recursive: only list dirs right under $dir |
979 | if ( !empty( $params['topOnly'] ) ) { |
980 | $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' ); |
981 | if ( !$status->isOK() ) { |
982 | throw new FileBackendError( "Iterator page I/O error." ); |
983 | } |
984 | $objects = $status->value; |
985 | // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach |
986 | foreach ( $objects as $object ) { // files and directories |
987 | if ( substr( $object, -1 ) === '/' ) { |
988 | $dirs[] = $object; // directories end in '/' |
989 | } |
990 | } |
991 | } else { |
992 | // Recursive: list all dirs under $dir and its subdirs |
993 | $getParentDir = static function ( $path ) { |
994 | return ( $path !== null && strpos( $path, '/' ) !== false ) ? dirname( $path ) : false; |
995 | }; |
996 | |
997 | // Get directory from last item of prior page |
998 | $lastDir = $getParentDir( $after ); // must be first page |
999 | $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix ); |
1000 | |
1001 | if ( !$status->isOK() ) { |
1002 | throw new FileBackendError( "Iterator page I/O error." ); |
1003 | } |
1004 | |
1005 | $objects = $status->value; |
1006 | |
1007 | // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach |
1008 | foreach ( $objects as $object ) { // files |
1009 | $objectDir = $getParentDir( $object ); // directory of object |
1010 | |
1011 | if ( $objectDir !== false && $objectDir !== $dir ) { |
1012 | // Swift stores paths in UTF-8, using binary sorting. |
1013 | // See function "create_container_table" in common/db.py. |
1014 | // If a directory is not "greater" than the last one, |
1015 | // then it was already listed by the calling iterator. |
1016 | if ( strcmp( $objectDir, $lastDir ) > 0 ) { |
1017 | $pDir = $objectDir; |
1018 | do { // add dir and all its parent dirs |
1019 | $dirs[] = "{$pDir}/"; |
1020 | $pDir = $getParentDir( $pDir ); |
1021 | } while ( $pDir !== false |
1022 | && strcmp( $pDir, $lastDir ) > 0 // not done already |
1023 | && strlen( $pDir ) > strlen( $dir ) // within $dir |
1024 | ); |
1025 | } |
1026 | $lastDir = $objectDir; |
1027 | } |
1028 | } |
1029 | } |
1030 | // Page on the unfiltered directory listing (what is returned may be filtered) |
1031 | if ( count( $objects ) < $limit ) { |
1032 | $after = INF; // avoid a second RTT |
1033 | } else { |
1034 | $after = end( $objects ); // update last item |
1035 | } |
1036 | |
1037 | return $dirs; |
1038 | } |
1039 | |
1040 | /** |
1041 | * Do not call this function outside of SwiftFileBackendFileList |
1042 | * |
1043 | * @param string $fullCont Resolved container name |
1044 | * @param string $dir Resolved storage directory with no trailing slash |
1045 | * @param string|null &$after Resolved container relative path of file to list items after |
1046 | * @param int $limit Max number of items to list |
1047 | * @param array $params Parameters for {@link getFileList()} |
1048 | * @return array[] List of (name, stat map or null) tuples under $dir |
1049 | * @throws FileBackendError |
1050 | */ |
1051 | public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) { |
1052 | $files = []; // list of (path, stat map or null) entries |
1053 | if ( $after === INF ) { |
1054 | return $files; // nothing more |
1055 | } |
1056 | |
1057 | /** @noinspection PhpUnusedLocalVariableInspection */ |
1058 | $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" ); |
1059 | |
1060 | $prefix = ( $dir == '' ) ? null : "{$dir}/"; |
1061 | // $objects will contain a list of unfiltered names or stdClass items |
1062 | // Non-recursive: only list files right under $dir |
1063 | if ( !empty( $params['topOnly'] ) ) { |
1064 | if ( !empty( $params['adviseStat'] ) ) { |
1065 | $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' ); |
1066 | } else { |
1067 | $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' ); |
1068 | } |
1069 | } else { |
1070 | // Recursive: list all files under $dir and its subdirs |
1071 | if ( !empty( $params['adviseStat'] ) ) { |
1072 | $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix ); |
1073 | } else { |
1074 | $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix ); |
1075 | } |
1076 | } |
1077 | |
1078 | // Reformat this list into a list of (name, stat map or null) entries |
1079 | if ( !$status->isOK() ) { |
1080 | throw new FileBackendError( "Iterator page I/O error." ); |
1081 | } |
1082 | |
1083 | $objects = $status->value; |
1084 | $files = $this->buildFileObjectListing( $objects ); |
1085 | |
1086 | // Page on the unfiltered object listing (what is returned may be filtered) |
1087 | if ( count( $objects ) < $limit ) { |
1088 | $after = INF; // avoid a second RTT |
1089 | } else { |
1090 | $after = end( $objects ); // update last item |
1091 | $after = is_object( $after ) ? $after->name : $after; |
1092 | } |
1093 | |
1094 | return $files; |
1095 | } |
1096 | |
1097 | /** |
1098 | * Build a list of file objects, filtering out any directories |
1099 | * and extracting any stat info if provided in $objects |
1100 | * |
1101 | * @param stdClass[]|string[] $objects List of stdClass items or object names |
1102 | * @return array[] List of (name, stat map or null) entries |
1103 | */ |
1104 | private function buildFileObjectListing( array $objects ) { |
1105 | $names = []; |
1106 | foreach ( $objects as $object ) { |
1107 | if ( is_object( $object ) ) { |
1108 | if ( isset( $object->subdir ) || !isset( $object->name ) ) { |
1109 | continue; // virtual directory entry; ignore |
1110 | } |
1111 | $stat = [ |
1112 | // Convert various random Swift dates to TS_MW |
1113 | 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ), |
1114 | 'size' => (int)$object->bytes, |
1115 | 'sha1' => null, |
1116 | // Note: manifest ETags are not an MD5 of the file |
1117 | 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null, |
1118 | 'latest' => false // eventually consistent |
1119 | ]; |
1120 | $names[] = [ $object->name, $stat ]; |
1121 | } elseif ( substr( $object, -1 ) !== '/' ) { |
1122 | // Omit directories, which end in '/' in listings |
1123 | $names[] = [ $object, null ]; |
1124 | } |
1125 | } |
1126 | |
1127 | return $names; |
1128 | } |
1129 | |
1130 | /** |
1131 | * Do not call this function outside of SwiftFileBackendFileList |
1132 | * |
1133 | * @param string $path Storage path |
1134 | * @param array $val Stat value |
1135 | */ |
1136 | public function loadListingStatInternal( $path, array $val ) { |
1137 | $this->cheapCache->setField( $path, 'stat', $val ); |
1138 | } |
1139 | |
1140 | protected function doGetFileXAttributes( array $params ) { |
1141 | $stat = $this->getFileStat( $params ); |
1142 | // Stat entries filled by file listings don't include metadata/headers |
1143 | if ( is_array( $stat ) && !isset( $stat['xattr'] ) ) { |
1144 | $this->clearCache( [ $params['src'] ] ); |
1145 | $stat = $this->getFileStat( $params ); |
1146 | } |
1147 | |
1148 | if ( is_array( $stat ) ) { |
1149 | return $stat['xattr']; |
1150 | } |
1151 | |
1152 | return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT; |
1153 | } |
1154 | |
1155 | protected function doGetFileSha1base36( array $params ) { |
1156 | // Avoid using stat entries from file listings, which never include the SHA-1 hash. |
1157 | // Also, recompute the hash if it's not part of the metadata headers for some reason. |
1158 | $params['requireSHA1'] = true; |
1159 | |
1160 | $stat = $this->getFileStat( $params ); |
1161 | if ( is_array( $stat ) ) { |
1162 | return $stat['sha1']; |
1163 | } |
1164 | |
1165 | return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT; |
1166 | } |
1167 | |
1168 | protected function doStreamFile( array $params ) { |
1169 | $status = $this->newStatus(); |
1170 | |
1171 | $flags = !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0; |
1172 | |
1173 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] ); |
1174 | if ( $srcRel === null ) { |
1175 | HTTPFileStreamer::send404Message( $params['src'], $flags ); |
1176 | $status->fatal( 'backend-fail-invalidpath', $params['src'] ); |
1177 | |
1178 | return $status; |
1179 | } |
1180 | |
1181 | if ( !is_array( $this->getContainerStat( $srcCont ) ) ) { |
1182 | HTTPFileStreamer::send404Message( $params['src'], $flags ); |
1183 | $status->fatal( 'backend-fail-stream', $params['src'] ); |
1184 | |
1185 | return $status; |
1186 | } |
1187 | |
1188 | // If "headers" is set, we only want to send them if the file is there. |
1189 | // Do not bother checking if the file exists if headers are not set though. |
1190 | if ( $params['headers'] && !$this->fileExists( $params ) ) { |
1191 | HTTPFileStreamer::send404Message( $params['src'], $flags ); |
1192 | $status->fatal( 'backend-fail-stream', $params['src'] ); |
1193 | |
1194 | return $status; |
1195 | } |
1196 | |
1197 | // Send the requested additional headers |
1198 | if ( empty( $params['headless'] ) ) { |
1199 | foreach ( $params['headers'] as $header ) { |
1200 | $this->header( $header ); |
1201 | } |
1202 | } |
1203 | |
1204 | if ( empty( $params['allowOB'] ) ) { |
1205 | // Cancel output buffering and gzipping if set |
1206 | $this->resetOutputBuffer(); |
1207 | } |
1208 | |
1209 | $handle = fopen( 'php://output', 'wb' ); |
1210 | [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [ |
1211 | 'method' => 'GET', |
1212 | 'container' => $srcCont, |
1213 | 'relPath' => $srcRel, |
1214 | 'headers' => $this->headersFromParams( $params ) + $params['options'], |
1215 | 'stream' => $handle, |
1216 | 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ] |
1217 | ] ); |
1218 | |
1219 | if ( $rcode >= 200 && $rcode <= 299 ) { |
1220 | // good |
1221 | } elseif ( $rcode === 404 ) { |
1222 | $status->fatal( 'backend-fail-stream', $params['src'] ); |
1223 | // Per T43113, nasty things can happen if bad cache entries get |
1224 | // stuck in cache. It's also possible that this error can come up |
1225 | // with simple race conditions. Clear out the stat cache to be safe. |
1226 | $this->clearCache( [ $params['src'] ] ); |
1227 | $this->deleteFileCache( $params['src'] ); |
1228 | } else { |
1229 | $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody ); |
1230 | } |
1231 | |
1232 | return $status; |
1233 | } |
1234 | |
1235 | protected function doGetLocalCopyMulti( array $params ) { |
1236 | $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging |
1237 | // Blindly create tmp files and stream to them, catching any exception |
1238 | // if the file does not exist. Do not waste time doing file stats here. |
1239 | $reqs = []; // (path => op) |
1240 | |
1241 | // Initial dummy values to preserve path order |
1242 | $tmpFiles = array_fill_keys( $params['srcs'], self::RES_ERROR ); |
1243 | foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch |
1244 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path ); |
1245 | if ( $srcRel === null ) { |
1246 | continue; // invalid storage path |
1247 | } |
1248 | // Get source file extension |
1249 | $ext = FileBackend::extensionFromPath( $path ); |
1250 | // Create a new temporary file... |
1251 | $tmpFile = $this->tmpFileFactory->newTempFSFile( 'localcopy_', $ext ); |
1252 | $handle = $tmpFile ? fopen( $tmpFile->getPath(), 'wb' ) : false; |
1253 | if ( $handle ) { |
1254 | $reqs[$path] = [ |
1255 | 'method' => 'GET', |
1256 | 'container' => $srcCont, |
1257 | 'relPath' => $srcRel, |
1258 | 'headers' => $this->headersFromParams( $params ), |
1259 | 'stream' => $handle, |
1260 | ]; |
1261 | $tmpFiles[$path] = $tmpFile; |
1262 | } |
1263 | } |
1264 | |
1265 | // Ceph RADOS Gateway is in use (strong consistency) or X-Newest will be used |
1266 | $latest = ( $this->isRGW || !empty( $params['latest'] ) ); |
1267 | |
1268 | $reqs = $this->requestMultiWithAuth( |
1269 | $reqs, |
1270 | [ 'maxConnsPerHost' => $params['concurrency'] ] |
1271 | ); |
1272 | foreach ( $reqs as $path => $op ) { |
1273 | [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response']; |
1274 | fclose( $op['stream'] ); // close open handle |
1275 | if ( $rcode >= 200 && $rcode <= 299 ) { |
1276 | /** @var TempFSFile $tmpFile */ |
1277 | $tmpFile = $tmpFiles[$path]; |
1278 | // Make sure that the stream finished and fully wrote to disk |
1279 | $size = $tmpFile->getSize(); |
1280 | if ( $size !== (int)$rhdrs['content-length'] ) { |
1281 | $tmpFiles[$path] = self::RES_ERROR; |
1282 | $rerr = "Got {$size}/{$rhdrs['content-length']} bytes"; |
1283 | $this->onError( null, __METHOD__, |
1284 | [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc ); |
1285 | } |
1286 | // Set the file stat process cache in passing |
1287 | $stat = $this->getStatFromHeaders( $rhdrs ); |
1288 | $stat['latest'] = $latest; |
1289 | $this->cheapCache->setField( $path, 'stat', $stat ); |
1290 | } elseif ( $rcode === 404 ) { |
1291 | $tmpFiles[$path] = self::RES_ABSENT; |
1292 | $this->cheapCache->setField( |
1293 | $path, |
1294 | 'stat', |
1295 | $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL |
1296 | ); |
1297 | } else { |
1298 | $tmpFiles[$path] = self::RES_ERROR; |
1299 | $this->onError( null, __METHOD__, |
1300 | [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc, $rbody ); |
1301 | } |
1302 | } |
1303 | |
1304 | return $tmpFiles; |
1305 | } |
1306 | |
1307 | public function addShellboxInputFile( BoxedCommand $command, string $boxedName, |
1308 | array $params |
1309 | ) { |
1310 | if ( $this->canShellboxGetTempUrl ) { |
1311 | $urlParams = [ 'src' => $params['src'] ]; |
1312 | if ( $this->shellboxIpRange !== null ) { |
1313 | $urlParams['ipRange'] = $this->shellboxIpRange; |
1314 | } |
1315 | $url = $this->getFileHttpUrl( $urlParams ); |
1316 | if ( $url ) { |
1317 | $command->inputFileFromUrl( $boxedName, $url ); |
1318 | return $this->newStatus(); |
1319 | } |
1320 | } |
1321 | return parent::addShellboxInputFile( $command, $boxedName, $params ); |
1322 | } |
1323 | |
1324 | public function getFileHttpUrl( array $params ) { |
1325 | if ( $this->swiftTempUrlKey == '' && |
1326 | ( $this->rgwS3AccessKey == '' || $this->rgwS3SecretKey != '' ) |
1327 | ) { |
1328 | $this->logger->debug( "Can't get Swift file URL: no key available" ); |
1329 | return self::TEMPURL_ERROR; |
1330 | } |
1331 | |
1332 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] ); |
1333 | if ( $srcRel === null ) { |
1334 | $this->logger->debug( "Can't get Swift file URL: can't resolve path" ); |
1335 | return self::TEMPURL_ERROR; // invalid path |
1336 | } |
1337 | |
1338 | $auth = $this->getAuthentication(); |
1339 | if ( !$auth ) { |
1340 | $this->logger->debug( "Can't get Swift file URL: authentication failed" ); |
1341 | return self::TEMPURL_ERROR; |
1342 | } |
1343 | |
1344 | $method = $params['method'] ?? 'GET'; |
1345 | $ttl = $params['ttl'] ?? 86400; |
1346 | $expires = time() + $ttl; |
1347 | |
1348 | if ( $this->swiftTempUrlKey != '' ) { |
1349 | $url = $this->storageUrl( $auth, $srcCont, $srcRel ); |
1350 | // Swift wants the signature based on the unencoded object name |
1351 | $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH ); |
1352 | $messageParts = [ |
1353 | $method, |
1354 | $expires, |
1355 | "{$contPath}/{$srcRel}" |
1356 | ]; |
1357 | $query = [ |
1358 | 'temp_url_expires' => $expires, |
1359 | ]; |
1360 | if ( isset( $params['ipRange'] ) ) { |
1361 | array_unshift( $messageParts, "ip={$params['ipRange']}" ); |
1362 | $query['temp_url_ip_range'] = $params['ipRange']; |
1363 | } |
1364 | |
1365 | $signature = hash_hmac( 'sha1', |
1366 | implode( "\n", $messageParts ), |
1367 | $this->swiftTempUrlKey |
1368 | ); |
1369 | $query = [ 'temp_url_sig' => $signature ] + $query; |
1370 | |
1371 | return $url . '?' . http_build_query( $query ); |
1372 | } else { // give S3 API URL for rgw |
1373 | // Path for signature starts with the bucket |
1374 | $spath = '/' . rawurlencode( $srcCont ) . '/' . |
1375 | str_replace( '%2F', '/', rawurlencode( $srcRel ) ); |
1376 | // Calculate the hash |
1377 | $signature = base64_encode( hash_hmac( |
1378 | 'sha1', |
1379 | "{$method}\n\n\n{$expires}\n{$spath}", |
1380 | $this->rgwS3SecretKey, |
1381 | true // raw |
1382 | ) ); |
1383 | // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html. |
1384 | // Note: adding a newline for empty CanonicalizedAmzHeaders does not work. |
1385 | // Note: S3 API is the rgw default; remove the /swift/ URL bit. |
1386 | return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) . |
1387 | '?' . |
1388 | http_build_query( [ |
1389 | 'Signature' => $signature, |
1390 | 'Expires' => $expires, |
1391 | 'AWSAccessKeyId' => $this->rgwS3AccessKey |
1392 | ] ); |
1393 | } |
1394 | } |
1395 | |
1396 | protected function directoriesAreVirtual() { |
1397 | return true; |
1398 | } |
1399 | |
1400 | /** |
1401 | * Get headers to send to Swift when reading a file based |
1402 | * on a FileBackend params array, e.g. that of getLocalCopy(). |
1403 | * $params is currently only checked for a 'latest' flag. |
1404 | * |
1405 | * @param array $params |
1406 | * @return array |
1407 | */ |
1408 | protected function headersFromParams( array $params ) { |
1409 | $hdrs = []; |
1410 | if ( !empty( $params['latest'] ) ) { |
1411 | $hdrs['x-newest'] = 'true'; |
1412 | } |
1413 | |
1414 | return $hdrs; |
1415 | } |
1416 | |
1417 | protected function doExecuteOpHandlesInternal( array $fileOpHandles ) { |
1418 | /** @var SwiftFileOpHandle[] $fileOpHandles */ |
1419 | '@phan-var SwiftFileOpHandle[] $fileOpHandles'; |
1420 | |
1421 | /** @var StatusValue[] $statuses */ |
1422 | $statuses = []; |
1423 | |
1424 | // Split the HTTP requests into stages that can be done concurrently |
1425 | $httpReqsByStage = []; // map of (stage => index => HTTP request) |
1426 | foreach ( $fileOpHandles as $index => $fileOpHandle ) { |
1427 | $reqs = $fileOpHandle->httpOp; |
1428 | foreach ( $reqs as $stage => $req ) { |
1429 | $httpReqsByStage[$stage][$index] = $req; |
1430 | } |
1431 | $statuses[$index] = $this->newStatus(); |
1432 | } |
1433 | |
1434 | // Run all requests for the first stage, then the next, and so on |
1435 | $reqCount = count( $httpReqsByStage ); |
1436 | for ( $stage = 0; $stage < $reqCount; ++$stage ) { |
1437 | $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] ); |
1438 | foreach ( $httpReqs as $index => $httpReq ) { |
1439 | /** @var SwiftFileOpHandle $fileOpHandle */ |
1440 | $fileOpHandle = $fileOpHandles[$index]; |
1441 | // Run the callback for each request of this operation |
1442 | $status = $statuses[$index]; |
1443 | ( $fileOpHandle->callback )( $httpReq, $status ); |
1444 | // On failure, abort all remaining requests for this operation. This is used |
1445 | // in "move" operations to abort the DELETE request if the PUT request fails. |
1446 | if ( |
1447 | !$status->isOK() || |
1448 | $fileOpHandle->state === $fileOpHandle::CONTINUE_NO |
1449 | ) { |
1450 | $stages = count( $fileOpHandle->httpOp ); |
1451 | for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) { |
1452 | unset( $httpReqsByStage[$s][$index] ); |
1453 | } |
1454 | } |
1455 | } |
1456 | } |
1457 | |
1458 | return $statuses; |
1459 | } |
1460 | |
1461 | /** |
1462 | * Set read/write permissions for a Swift container. |
1463 | * |
1464 | * @see http://docs.openstack.org/developer/swift/misc.html#acls |
1465 | * |
1466 | * In general, we don't allow listings to end-users. It's not useful, isn't well-defined |
1467 | * (lists are truncated to 10000 item with no way to page), and is just a performance risk. |
1468 | * |
1469 | * @param string $container Resolved Swift container |
1470 | * @param array $readUsers List of the possible criteria for a request to have |
1471 | * access to read a container. Each item is one of the following formats: |
1472 | * - account:user : Grants access if the request is by the given user |
1473 | * - ".r:<regex>" : Grants access if the request is from a referrer host that |
1474 | * matches the expression and the request is not for a listing. |
1475 | * Setting this to '*' effectively makes a container public. |
1476 | * -".rlistings:<regex>" : Grants access if the request is from a referrer host that |
1477 | * matches the expression and the request is for a listing. |
1478 | * @param array $writeUsers A list of the possible criteria for a request to have |
1479 | * access to write to a container. Each item is of the following format: |
1480 | * - account:user : Grants access if the request is by the given user |
1481 | * @return StatusValue Good status without value for success, fatal otherwise. |
1482 | */ |
1483 | protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) { |
1484 | $status = $this->newStatus(); |
1485 | |
1486 | [ $rcode, , , , ] = $this->requestWithAuth( [ |
1487 | 'method' => 'POST', |
1488 | 'container' => $container, |
1489 | 'headers' => [ |
1490 | 'x-container-read' => implode( ',', $readUsers ), |
1491 | 'x-container-write' => implode( ',', $writeUsers ) |
1492 | ] |
1493 | ] ); |
1494 | |
1495 | if ( $rcode != 204 && $rcode !== 202 ) { |
1496 | $status->fatal( 'backend-fail-internal', $this->name ); |
1497 | $this->logger->error( __METHOD__ . ': unexpected rcode value ({rcode})', |
1498 | [ 'rcode' => $rcode ] ); |
1499 | } |
1500 | |
1501 | return $status; |
1502 | } |
1503 | |
1504 | /** |
1505 | * Get a Swift container stat map, possibly from process cache. |
1506 | * Use $reCache if the file count or byte count is needed. |
1507 | * |
1508 | * @param string $container Container name |
1509 | * @param bool $bypassCache Bypass all caches and load from Swift |
1510 | * @return array|false|null False on 404, null on failure |
1511 | */ |
1512 | protected function getContainerStat( $container, $bypassCache = false ) { |
1513 | /** @noinspection PhpUnusedLocalVariableInspection */ |
1514 | $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" ); |
1515 | |
1516 | if ( $bypassCache ) { // purge cache |
1517 | $this->containerStatCache->clear( $container ); |
1518 | } elseif ( !$this->containerStatCache->hasField( $container, 'stat' ) ) { |
1519 | $this->primeContainerCache( [ $container ] ); // check persistent cache |
1520 | } |
1521 | if ( !$this->containerStatCache->hasField( $container, 'stat' ) ) { |
1522 | [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [ |
1523 | 'method' => 'HEAD', |
1524 | 'container' => $container |
1525 | ] ); |
1526 | |
1527 | if ( $rcode === 204 ) { |
1528 | $stat = [ |
1529 | 'count' => $rhdrs['x-container-object-count'], |
1530 | 'bytes' => $rhdrs['x-container-bytes-used'] |
1531 | ]; |
1532 | if ( $bypassCache ) { |
1533 | return $stat; |
1534 | } else { |
1535 | $this->containerStatCache->setField( $container, 'stat', $stat ); // cache it |
1536 | $this->setContainerCache( $container, $stat ); // update persistent cache |
1537 | } |
1538 | } elseif ( $rcode === 404 ) { |
1539 | return self::RES_ABSENT; |
1540 | } else { |
1541 | $this->onError( null, __METHOD__, |
1542 | [ 'cont' => $container ], $rerr, $rcode, $rdesc, $rbody ); |
1543 | |
1544 | return self::RES_ERROR; |
1545 | } |
1546 | } |
1547 | |
1548 | return $this->containerStatCache->getField( $container, 'stat' ); |
1549 | } |
1550 | |
1551 | /** |
1552 | * Create a Swift container |
1553 | * |
1554 | * @param string $container Container name |
1555 | * @param array $params |
1556 | * @return StatusValue Good status without value for success, fatal otherwise. |
1557 | */ |
1558 | protected function createContainer( $container, array $params ) { |
1559 | $status = $this->newStatus(); |
1560 | |
1561 | // @see SwiftFileBackend::setContainerAccess() |
1562 | if ( empty( $params['noAccess'] ) ) { |
1563 | // public |
1564 | $readUsers = array_merge( $this->readUsers, [ '.r:*', $this->swiftUser ] ); |
1565 | if ( empty( $params['noListing'] ) ) { |
1566 | array_push( $readUsers, '.rlistings' ); |
1567 | } |
1568 | $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] ); |
1569 | } else { |
1570 | // private |
1571 | $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] ); |
1572 | $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] ); |
1573 | } |
1574 | |
1575 | [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [ |
1576 | 'method' => 'PUT', |
1577 | 'container' => $container, |
1578 | 'headers' => [ |
1579 | 'x-container-read' => implode( ',', $readUsers ), |
1580 | 'x-container-write' => implode( ',', $writeUsers ) |
1581 | ] |
1582 | ] ); |
1583 | |
1584 | if ( $rcode === 201 ) { // new |
1585 | // good |
1586 | } elseif ( $rcode === 202 ) { // already there |
1587 | // this shouldn't really happen, but is OK |
1588 | } else { |
1589 | $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody ); |
1590 | } |
1591 | |
1592 | return $status; |
1593 | } |
1594 | |
1595 | /** |
1596 | * Delete a Swift container |
1597 | * |
1598 | * @param string $container Container name |
1599 | * @param array $params |
1600 | * @return StatusValue |
1601 | */ |
1602 | protected function deleteContainer( $container, array $params ) { |
1603 | $status = $this->newStatus(); |
1604 | |
1605 | [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [ |
1606 | 'method' => 'DELETE', |
1607 | 'container' => $container |
1608 | ] ); |
1609 | |
1610 | if ( $rcode >= 200 && $rcode <= 299 ) { // deleted |
1611 | $this->containerStatCache->clear( $container ); // purge |
1612 | } elseif ( $rcode === 404 ) { // not there |
1613 | // this shouldn't really happen, but is OK |
1614 | } elseif ( $rcode === 409 ) { // not empty |
1615 | $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race? |
1616 | } else { |
1617 | $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody ); |
1618 | } |
1619 | |
1620 | return $status; |
1621 | } |
1622 | |
1623 | /** |
1624 | * Get a list of objects under a container. |
1625 | * Either just the names or a list of stdClass objects with details can be returned. |
1626 | * |
1627 | * @param string $fullCont |
1628 | * @param string $type ('info' for a list of object detail maps, 'names' for names only) |
1629 | * @param int $limit |
1630 | * @param string|null $after |
1631 | * @param string|null $prefix |
1632 | * @param string|null $delim |
1633 | * @return StatusValue With the list as value |
1634 | */ |
1635 | private function objectListing( |
1636 | $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null |
1637 | ) { |
1638 | $status = $this->newStatus(); |
1639 | |
1640 | $query = [ 'limit' => $limit ]; |
1641 | if ( $type === 'info' ) { |
1642 | $query['format'] = 'json'; |
1643 | } |
1644 | if ( $after !== null ) { |
1645 | $query['marker'] = $after; |
1646 | } |
1647 | if ( $prefix !== null ) { |
1648 | $query['prefix'] = $prefix; |
1649 | } |
1650 | if ( $delim !== null ) { |
1651 | $query['delimiter'] = $delim; |
1652 | } |
1653 | |
1654 | [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [ |
1655 | 'method' => 'GET', |
1656 | 'container' => $fullCont, |
1657 | 'query' => $query, |
1658 | ] ); |
1659 | |
1660 | $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ]; |
1661 | if ( $rcode === 200 ) { // good |
1662 | if ( $type === 'info' ) { |
1663 | $status->value = json_decode( trim( $rbody ) ); |
1664 | } else { |
1665 | $status->value = explode( "\n", trim( $rbody ) ); |
1666 | } |
1667 | } elseif ( $rcode === 204 ) { |
1668 | $status->value = []; // empty container |
1669 | } elseif ( $rcode === 404 ) { |
1670 | $status->value = []; // no container |
1671 | } else { |
1672 | $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody ); |
1673 | } |
1674 | |
1675 | return $status; |
1676 | } |
1677 | |
1678 | protected function doPrimeContainerCache( array $containerInfo ) { |
1679 | foreach ( $containerInfo as $container => $info ) { |
1680 | $this->containerStatCache->setField( $container, 'stat', $info ); |
1681 | } |
1682 | } |
1683 | |
1684 | protected function doGetFileStatMulti( array $params ) { |
1685 | $stats = []; |
1686 | |
1687 | $reqs = []; // (path => op) |
1688 | // (a) Check the containers of the paths... |
1689 | foreach ( $params['srcs'] as $path ) { |
1690 | [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path ); |
1691 | if ( $srcRel === null ) { |
1692 | // invalid storage path |
1693 | $stats[$path] = self::RES_ERROR; |
1694 | continue; |
1695 | } |
1696 | |
1697 | $cstat = $this->getContainerStat( $srcCont ); |
1698 | if ( $cstat === self::RES_ABSENT ) { |
1699 | $stats[$path] = self::RES_ABSENT; |
1700 | continue; // ok, nothing to do |
1701 | } elseif ( $cstat === self::RES_ERROR ) { |
1702 | $stats[$path] = self::RES_ERROR; |
1703 | continue; |
1704 | } |
1705 | |
1706 | $reqs[$path] = [ |
1707 | 'method' => 'HEAD', |
1708 | 'container' => $srcCont, |
1709 | 'relPath' => $srcRel, |
1710 | 'headers' => $this->headersFromParams( $params ) |
1711 | ]; |
1712 | } |
1713 | |
1714 | // (b) Check the files themselves... |
1715 | $reqs = $this->requestMultiWithAuth( |
1716 | $reqs, |
1717 | [ 'maxConnsPerHost' => $params['concurrency'] ] |
1718 | ); |
1719 | foreach ( $reqs as $path => $op ) { |
1720 | [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response']; |
1721 | if ( $rcode === 200 || $rcode === 204 ) { |
1722 | // Update the object if it is missing some headers |
1723 | if ( !empty( $params['requireSHA1'] ) ) { |
1724 | $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path ); |
1725 | } |
1726 | // Load the stat map from the headers |
1727 | $stat = $this->getStatFromHeaders( $rhdrs ); |
1728 | if ( $this->isRGW ) { |
1729 | $stat['latest'] = true; // strong consistency |
1730 | } |
1731 | } elseif ( $rcode === 404 ) { |
1732 | $stat = self::RES_ABSENT; |
1733 | } else { |
1734 | $stat = self::RES_ERROR; |
1735 | $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody ); |
1736 | } |
1737 | $stats[$path] = $stat; |
1738 | } |
1739 | |
1740 | return $stats; |
1741 | } |
1742 | |
1743 | /** |
1744 | * @param array $rhdrs |
1745 | * @return array |
1746 | */ |
1747 | protected function getStatFromHeaders( array $rhdrs ) { |
1748 | // Fetch all of the custom metadata headers |
1749 | $metadata = $this->getMetadataFromHeaders( $rhdrs ); |
1750 | // Fetch all of the custom raw HTTP headers |
1751 | $headers = $this->extractMutableContentHeaders( $rhdrs ); |
1752 | |
1753 | return [ |
1754 | // Convert various random Swift dates to TS_MW |
1755 | 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ), |
1756 | // Empty objects actually return no content-length header in Ceph |
1757 | 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0, |
1758 | 'sha1' => $metadata['sha1base36'] ?? null, |
1759 | // Note: manifest ETags are not an MD5 of the file |
1760 | 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null, |
1761 | 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ] |
1762 | ]; |
1763 | } |
1764 | |
1765 | /** |
1766 | * Get the cached auth token. |
1767 | * |
1768 | * @return array|null Credential map |
1769 | */ |
1770 | protected function getAuthentication() { |
1771 | if ( $this->authErrorTimestamp !== null ) { |
1772 | $interval = time() - $this->authErrorTimestamp; |
1773 | if ( $interval < 60 ) { |
1774 | $this->logger->debug( |
1775 | 'rejecting request since auth failure occurred {interval} seconds ago', |
1776 | [ 'interval' => $interval ] |
1777 | ); |
1778 | return null; |
1779 | } else { // actually retry this time |
1780 | $this->authErrorTimestamp = null; |
1781 | } |
1782 | } |
1783 | // Authenticate with proxy and get a session key... |
1784 | if ( !$this->authCreds ) { |
1785 | $cacheKey = $this->getCredsCacheKey( $this->swiftUser ); |
1786 | $creds = $this->srvCache->get( $cacheKey ); // credentials |
1787 | // Try to use the credential cache |
1788 | if ( isset( $creds['auth_token'] ) |
1789 | && isset( $creds['storage_url'] ) |
1790 | && isset( $creds['expiry_time'] ) |
1791 | && $creds['expiry_time'] > time() |
1792 | ) { |
1793 | $this->setAuthCreds( $creds ); |
1794 | } else { // cache miss |
1795 | $this->refreshAuthentication(); |
1796 | } |
1797 | } |
1798 | |
1799 | return $this->authCreds; |
1800 | } |
1801 | |
1802 | /** |
1803 | * Update the auth credentials |
1804 | * |
1805 | * @param array|null $creds |
1806 | */ |
1807 | private function setAuthCreds( ?array $creds ) { |
1808 | $this->logger->debug( 'Using auth token with expiry_time={expiry_time}', |
1809 | [ |
1810 | 'expiry_time' => isset( $creds['expiry_time'] ) |
1811 | ? gmdate( 'c', $creds['expiry_time'] ) : 'null' |
1812 | ] |
1813 | ); |
1814 | $this->authCreds = $creds; |
1815 | // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>") |
1816 | if ( $creds && str_ends_with( $creds['storage_url'], '/v1' ) ) { |
1817 | $this->isRGW = true; // take advantage of strong consistency in Ceph |
1818 | } |
1819 | } |
1820 | |
1821 | /** |
1822 | * Fetch the auth token from the server, without caching. |
1823 | * |
1824 | * @return array|null Credential map |
1825 | */ |
1826 | private function refreshAuthentication() { |
1827 | [ $rcode, , $rhdrs, $rbody, ] = $this->http->run( [ |
1828 | 'method' => 'GET', |
1829 | 'url' => "{$this->swiftAuthUrl}/v1.0", |
1830 | 'headers' => [ |
1831 | 'x-auth-user' => $this->swiftUser, |
1832 | 'x-auth-key' => $this->swiftKey |
1833 | ] |
1834 | ], self::DEFAULT_HTTP_OPTIONS ); |
1835 | |
1836 | if ( $rcode >= 200 && $rcode <= 299 ) { // OK |
1837 | if ( isset( $rhdrs['x-auth-token-expires'] ) ) { |
1838 | $ttl = intval( $rhdrs['x-auth-token-expires'] ); |
1839 | } else { |
1840 | $ttl = $this->authTTL; |
1841 | } |
1842 | $expiryTime = time() + $ttl; |
1843 | $creds = [ |
1844 | 'auth_token' => $rhdrs['x-auth-token'], |
1845 | 'storage_url' => $this->swiftStorageUrl ?? $rhdrs['x-storage-url'], |
1846 | 'expiry_time' => $expiryTime, |
1847 | ]; |
1848 | $this->srvCache->set( $this->getCredsCacheKey( $this->swiftUser ), $creds, $expiryTime ); |
1849 | } elseif ( $rcode === 401 ) { |
1850 | $this->onError( null, __METHOD__, [], "Authentication failed.", $rcode ); |
1851 | $this->authErrorTimestamp = time(); |
1852 | $creds = null; |
1853 | } else { |
1854 | $this->onError( null, __METHOD__, [], "HTTP return code: $rcode", $rcode, $rbody ); |
1855 | $this->authErrorTimestamp = time(); |
1856 | $creds = null; |
1857 | } |
1858 | $this->setAuthCreds( $creds ); |
1859 | return $creds; |
1860 | } |
1861 | |
1862 | /** |
1863 | * @param array $creds From getAuthentication() |
1864 | * @param string|null $container |
1865 | * @param string|null $object |
1866 | * @return string |
1867 | */ |
1868 | protected function storageUrl( array $creds, $container = null, $object = null ) { |
1869 | $parts = [ $creds['storage_url'] ]; |
1870 | if ( ( $container ?? '' ) !== '' ) { |
1871 | $parts[] = rawurlencode( $container ); |
1872 | } |
1873 | if ( ( $object ?? '' ) !== '' ) { |
1874 | $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) ); |
1875 | } |
1876 | |
1877 | return implode( '/', $parts ); |
1878 | } |
1879 | |
1880 | /** |
1881 | * @param array $creds From getAuthentication() |
1882 | * @return array |
1883 | */ |
1884 | protected function authTokenHeaders( array $creds ) { |
1885 | return [ 'x-auth-token' => $creds['auth_token'] ]; |
1886 | } |
1887 | |
1888 | /** |
1889 | * Get the cache key for a container |
1890 | * |
1891 | * @param string $username |
1892 | * @return string |
1893 | */ |
1894 | private function getCredsCacheKey( $username ) { |
1895 | return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl ); |
1896 | } |
1897 | |
1898 | /** |
1899 | * Perform an authenticated HTTP request |
1900 | * |
1901 | * @param array $req The request data, including: |
1902 | * - container: The name of the container (required) |
1903 | * - relPath: The relative path under the container. If this is omitted, |
1904 | * the request will refer to the container itself. |
1905 | * - headers: An array of request headers to send, in addition to the |
1906 | * auth headers. |
1907 | * - Other keys to be passed through to MultiHttpClient::run() |
1908 | * @param array $options Options to pass through to MultiHttpClient, in |
1909 | * addition to the default options DEFAULT_HTTP_OPTIONS |
1910 | * @return array The response array from MultiHttpClient::run() |
1911 | */ |
1912 | private function requestWithAuth( array $req, array $options = [] ) { |
1913 | return $this->requestMultiWithAuth( [ $req ], $options )[0]['response']; |
1914 | } |
1915 | |
1916 | /** |
1917 | * Perform a batch of authenticated HTTP requests |
1918 | * |
1919 | * @param array $reqs An array of request data arrays. See self::requestWithAuth() |
1920 | * @param array $options Options to pass through to MultiHttpClient, in |
1921 | * addition to the default options DEFAULT_HTTP_OPTIONS |
1922 | * @return array The request array with responses populated, as returned by |
1923 | * MultiHttpClient::runMulti() |
1924 | */ |
1925 | private function requestMultiWithAuth( array $reqs, $options = [] ) { |
1926 | $remainingTries = 2; |
1927 | $auth = $this->getAuthentication(); |
1928 | while ( true ) { |
1929 | if ( !$auth ) { |
1930 | foreach ( $reqs as &$req ) { |
1931 | if ( !isset( $req['response'] ) ) { |
1932 | $req['response'] = $this->getAuthFailureResponse(); |
1933 | } |
1934 | } |
1935 | break; |
1936 | } |
1937 | foreach ( $reqs as &$req ) { |
1938 | '@phan-var array $req'; // Not array[] |
1939 | if ( isset( $req['response'] ) ) { |
1940 | // Request was attempted before |
1941 | // Retry only if it gave a 401 response code |
1942 | if ( $req['response']['code'] !== 401 ) { |
1943 | continue; |
1944 | } |
1945 | } |
1946 | $req['headers'] = $this->authTokenHeaders( $auth ) + ( $req['headers'] ?? [] ); |
1947 | $req['url'] = $this->storageUrl( $auth, $req['container'], $req['relPath'] ?? null ); |
1948 | } |
1949 | unset( $req ); |
1950 | $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS ); |
1951 | if ( --$remainingTries > 0 ) { |
1952 | // Retry if any request failed with 401 "not authorized" |
1953 | foreach ( $reqs as $req ) { |
1954 | if ( $req['response']['code'] === 401 ) { |
1955 | $auth = $this->refreshAuthentication(); |
1956 | continue 2; |
1957 | } |
1958 | } |
1959 | } |
1960 | break; |
1961 | } |
1962 | return $reqs; |
1963 | } |
1964 | |
1965 | /** |
1966 | * Get a synthetic response to return from requestWithAuth() or requestMultiWithAuth() |
1967 | * if the request could not be issued due to failure of a prior authentication request. |
1968 | * This failure should not be logged as an HTTP error since the original failure would |
1969 | * have been logged. |
1970 | * |
1971 | * @return array |
1972 | */ |
1973 | private function getAuthFailureResponse() { |
1974 | return [ |
1975 | 'code' => 0, |
1976 | 0 => 0, |
1977 | 'reason' => '', |
1978 | 1 => '', |
1979 | 'headers' => [], |
1980 | 2 => [], |
1981 | 'body' => '', |
1982 | 3 => '', |
1983 | 'error' => self::AUTH_FAILURE_ERROR, |
1984 | 4 => self::AUTH_FAILURE_ERROR |
1985 | ]; |
1986 | } |
1987 | |
1988 | /** |
1989 | * Determine whether an HTTP response was generated by getAuthFailureResponse() |
1990 | * |
1991 | * @param int $code |
1992 | * @param string $error |
1993 | * @return bool |
1994 | */ |
1995 | private function isAuthFailureResponse( $code, $error ) { |
1996 | return $code === 0 && $error === self::AUTH_FAILURE_ERROR; |
1997 | } |
1998 | |
1999 | /** |
2000 | * Log an unexpected exception for this backend. |
2001 | * This also sets the StatusValue object to have a fatal error. |
2002 | * |
2003 | * @param StatusValue|null $status To add fatal errors to |
2004 | * @param string $func |
2005 | * @param array $params |
2006 | * @param string $err Error string |
2007 | * @param int $code HTTP status |
2008 | * @param string $desc HTTP StatusValue description |
2009 | * @param string $body HTTP body |
2010 | */ |
2011 | public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '', $body = '' ) { |
2012 | if ( $this->isAuthFailureResponse( $code, $err ) ) { |
2013 | if ( $status instanceof StatusValue ) { |
2014 | $status->fatal( 'backend-fail-connect', $this->name ); |
2015 | } |
2016 | // Already logged |
2017 | return; |
2018 | } |
2019 | if ( $status instanceof StatusValue ) { |
2020 | $status->fatal( 'backend-fail-internal', $this->name ); |
2021 | } |
2022 | $msg = "HTTP {code} ({desc}) in '{func}'"; |
2023 | $msgParams = [ |
2024 | 'code' => $code, |
2025 | 'desc' => $desc, |
2026 | 'func' => $func, |
2027 | 'req_params' => $params, |
2028 | ]; |
2029 | if ( $err ) { |
2030 | $msg .= ': {err}'; |
2031 | $msgParams['err'] = $err; |
2032 | } |
2033 | if ( $code == 502 ) { |
2034 | $msg .= ' ({truncatedBody})'; |
2035 | $msgParams['truncatedBody'] = substr( strip_tags( $body ), 0, 100 ); |
2036 | } |
2037 | $this->logger->error( $msg, $msgParams ); |
2038 | } |
2039 | } |
2040 | |
2041 | /** @deprecated class alias since 1.43 */ |
2042 | class_alias( SwiftFileBackend::class, 'SwiftFileBackend' ); |