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