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