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