Merge "Don't check namespace in SpecialWantedtemplates"
[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 // Find prior custom HTTP headers
719 $postHeaders = $this->getCustomHeaders( $objHdrs );
720 // Find prior metadata headers
721 $postHeaders += $this->getMetadataHeaders( $objHdrs );
722
723 $status = Status::newGood();
724 /** @noinspection PhpUnusedLocalVariableInspection */
725 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
726 if ( $status->isOK() ) {
727 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
728 if ( $tmpFile ) {
729 $hash = $tmpFile->getSha1Base36();
730 if ( $hash !== false ) {
731 $objHdrs['x-object-meta-sha1base36'] = $hash;
732 // Merge new SHA1 header into the old ones
733 $postHeaders['x-object-meta-sha1base36'] = $hash;
734 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
735 list( $rcode ) = $this->http->run( array(
736 'method' => 'POST',
737 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
738 'headers' => $this->authTokenHeaders( $auth ) + $postHeaders
739 ) );
740 if ( $rcode >= 200 && $rcode <= 299 ) {
741 $this->deleteFileCache( $path );
742
743 return $objHdrs; // success
744 }
745 }
746 }
747 }
748
749 wfDebugLog( 'SwiftBackend', __METHOD__ . ": unable to set SHA-1 metadata for $path" );
750
751 return $objHdrs; // failed
752 }
753
754 protected function doGetFileContentsMulti( array $params ) {
755 $contents = array();
756
757 $auth = $this->getAuthentication();
758
759 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
760 // Blindly create tmp files and stream to them, catching any exception if the file does
761 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
762 $reqs = array(); // (path => op)
763
764 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
765 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
766 if ( $srcRel === null || !$auth ) {
767 $contents[$path] = false;
768 continue;
769 }
770 // Create a new temporary memory file...
771 $handle = fopen( 'php://temp', 'wb' );
772 if ( $handle ) {
773 $reqs[$path] = array(
774 'method' => 'GET',
775 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
776 'headers' => $this->authTokenHeaders( $auth )
777 + $this->headersFromParams( $params ),
778 'stream' => $handle,
779 );
780 }
781 $contents[$path] = false;
782 }
783
784 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
785 $reqs = $this->http->runMulti( $reqs, $opts );
786 foreach ( $reqs as $path => $op ) {
787 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
788 if ( $rcode >= 200 && $rcode <= 299 ) {
789 rewind( $op['stream'] ); // start from the beginning
790 $contents[$path] = stream_get_contents( $op['stream'] );
791 } elseif ( $rcode === 404 ) {
792 $contents[$path] = false;
793 } else {
794 $this->onError( null, __METHOD__,
795 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
796 }
797 fclose( $op['stream'] ); // close open handle
798 }
799
800 return $contents;
801 }
802
803 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
804 $prefix = ( $dir == '' ) ? null : "{$dir}/";
805 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
806 if ( $status->isOk() ) {
807 return ( count( $status->value ) ) > 0;
808 }
809
810 return null; // error
811 }
812
813 /**
814 * @see FileBackendStore::getDirectoryListInternal()
815 * @param string $fullCont
816 * @param string $dir
817 * @param array $params
818 * @return SwiftFileBackendDirList
819 */
820 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
821 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
822 }
823
824 /**
825 * @see FileBackendStore::getFileListInternal()
826 * @param string $fullCont
827 * @param string $dir
828 * @param array $params
829 * @return SwiftFileBackendFileList
830 */
831 public function getFileListInternal( $fullCont, $dir, array $params ) {
832 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
833 }
834
835 /**
836 * Do not call this function outside of SwiftFileBackendFileList
837 *
838 * @param string $fullCont Resolved container name
839 * @param string $dir Resolved storage directory with no trailing slash
840 * @param string|null $after Resolved container relative path to list items after
841 * @param int $limit Max number of items to list
842 * @param array $params Parameters for getDirectoryList()
843 * @return array List of container relative resolved paths of directories directly under $dir
844 * @throws FileBackendError
845 */
846 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
847 $dirs = array();
848 if ( $after === INF ) {
849 return $dirs; // nothing more
850 }
851
852 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
853
854 $prefix = ( $dir == '' ) ? null : "{$dir}/";
855 // Non-recursive: only list dirs right under $dir
856 if ( !empty( $params['topOnly'] ) ) {
857 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
858 if ( !$status->isOk() ) {
859 return $dirs; // error
860 }
861 $objects = $status->value;
862 foreach ( $objects as $object ) { // files and directories
863 if ( substr( $object, -1 ) === '/' ) {
864 $dirs[] = $object; // directories end in '/'
865 }
866 }
867 } else {
868 // Recursive: list all dirs under $dir and its subdirs
869 $getParentDir = function ( $path ) {
870 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
871 };
872
873 // Get directory from last item of prior page
874 $lastDir = $getParentDir( $after ); // must be first page
875 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
876
877 if ( !$status->isOk() ) {
878 return $dirs; // error
879 }
880
881 $objects = $status->value;
882
883 foreach ( $objects as $object ) { // files
884 $objectDir = $getParentDir( $object ); // directory of object
885
886 if ( $objectDir !== false && $objectDir !== $dir ) {
887 // Swift stores paths in UTF-8, using binary sorting.
888 // See function "create_container_table" in common/db.py.
889 // If a directory is not "greater" than the last one,
890 // then it was already listed by the calling iterator.
891 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
892 $pDir = $objectDir;
893 do { // add dir and all its parent dirs
894 $dirs[] = "{$pDir}/";
895 $pDir = $getParentDir( $pDir );
896 } while ( $pDir !== false // sanity
897 && strcmp( $pDir, $lastDir ) > 0 // not done already
898 && strlen( $pDir ) > strlen( $dir ) // within $dir
899 );
900 }
901 $lastDir = $objectDir;
902 }
903 }
904 }
905 // Page on the unfiltered directory listing (what is returned may be filtered)
906 if ( count( $objects ) < $limit ) {
907 $after = INF; // avoid a second RTT
908 } else {
909 $after = end( $objects ); // update last item
910 }
911
912 return $dirs;
913 }
914
915 /**
916 * Do not call this function outside of SwiftFileBackendFileList
917 *
918 * @param string $fullCont Resolved container name
919 * @param string $dir Resolved storage directory with no trailing slash
920 * @param string|null $after Resolved container relative path of file to list items after
921 * @param int $limit Max number of items to list
922 * @param array $params Parameters for getDirectoryList()
923 * @return array List of resolved container relative paths of files under $dir
924 * @throws FileBackendError
925 */
926 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
927 $files = array(); // list of (path, stat array or null) entries
928 if ( $after === INF ) {
929 return $files; // nothing more
930 }
931
932 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
933
934 $prefix = ( $dir == '' ) ? null : "{$dir}/";
935 // $objects will contain a list of unfiltered names or CF_Object items
936 // Non-recursive: only list files right under $dir
937 if ( !empty( $params['topOnly'] ) ) {
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 } else {
944 // Recursive: list all files under $dir and its subdirs
945 if ( !empty( $params['adviseStat'] ) ) {
946 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
947 } else {
948 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
949 }
950 }
951
952 // Reformat this list into a list of (name, stat array or null) entries
953 if ( !$status->isOk() ) {
954 return $files; // error
955 }
956
957 $objects = $status->value;
958 $files = $this->buildFileObjectListing( $params, $dir, $objects );
959
960 // Page on the unfiltered object listing (what is returned may be filtered)
961 if ( count( $objects ) < $limit ) {
962 $after = INF; // avoid a second RTT
963 } else {
964 $after = end( $objects ); // update last item
965 $after = is_object( $after ) ? $after->name : $after;
966 }
967
968 return $files;
969 }
970
971 /**
972 * Build a list of file objects, filtering out any directories
973 * and extracting any stat info if provided in $objects (for CF_Objects)
974 *
975 * @param array $params Parameters for getDirectoryList()
976 * @param string $dir Resolved container directory path
977 * @param array $objects List of CF_Object items or object names
978 * @return array List of (names,stat array or null) entries
979 */
980 private function buildFileObjectListing( array $params, $dir, array $objects ) {
981 $names = array();
982 foreach ( $objects as $object ) {
983 if ( is_object( $object ) ) {
984 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
985 continue; // virtual directory entry; ignore
986 }
987 $stat = array(
988 // Convert various random Swift dates to TS_MW
989 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
990 'size' => (int)$object->bytes,
991 'sha1' => null,
992 // Note: manifiest ETags are not an MD5 of the file
993 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
994 'latest' => false // eventually consistent
995 );
996 $names[] = array( $object->name, $stat );
997 } elseif ( substr( $object, -1 ) !== '/' ) {
998 // Omit directories, which end in '/' in listings
999 $names[] = array( $object, null );
1000 }
1001 }
1002
1003 return $names;
1004 }
1005
1006 /**
1007 * Do not call this function outside of SwiftFileBackendFileList
1008 *
1009 * @param string $path Storage path
1010 * @param array $val Stat value
1011 */
1012 public function loadListingStatInternal( $path, array $val ) {
1013 $this->cheapCache->set( $path, 'stat', $val );
1014 }
1015
1016 protected function doGetFileXAttributes( array $params ) {
1017 $stat = $this->getFileStat( $params );
1018 if ( $stat ) {
1019 if ( !isset( $stat['xattr'] ) ) {
1020 // Stat entries filled by file listings don't include metadata/headers
1021 $this->clearCache( array( $params['src'] ) );
1022 $stat = $this->getFileStat( $params );
1023 }
1024
1025 return $stat['xattr'];
1026 } else {
1027 return false;
1028 }
1029 }
1030
1031 protected function doGetFileSha1base36( array $params ) {
1032 $stat = $this->getFileStat( $params );
1033 if ( $stat ) {
1034 if ( !isset( $stat['sha1'] ) ) {
1035 // Stat entries filled by file listings don't include SHA1
1036 $this->clearCache( array( $params['src'] ) );
1037 $stat = $this->getFileStat( $params );
1038 }
1039
1040 return $stat['sha1'];
1041 } else {
1042 return false;
1043 }
1044 }
1045
1046 protected function doStreamFile( array $params ) {
1047 $status = Status::newGood();
1048
1049 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1050 if ( $srcRel === null ) {
1051 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1052 }
1053
1054 $auth = $this->getAuthentication();
1055 if ( !$auth || !is_array( $this->getContainerStat( $srcCont ) ) ) {
1056 $status->fatal( 'backend-fail-stream', $params['src'] );
1057
1058 return $status;
1059 }
1060
1061 $handle = fopen( 'php://output', 'wb' );
1062
1063 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1064 'method' => 'GET',
1065 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1066 'headers' => $this->authTokenHeaders( $auth )
1067 + $this->headersFromParams( $params ),
1068 'stream' => $handle,
1069 ) );
1070
1071 if ( $rcode >= 200 && $rcode <= 299 ) {
1072 // good
1073 } elseif ( $rcode === 404 ) {
1074 $status->fatal( 'backend-fail-stream', $params['src'] );
1075 } else {
1076 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1077 }
1078
1079 return $status;
1080 }
1081
1082 protected function doGetLocalCopyMulti( array $params ) {
1083 $tmpFiles = array();
1084
1085 $auth = $this->getAuthentication();
1086
1087 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1088 // Blindly create tmp files and stream to them, catching any exception if the file does
1089 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1090 $reqs = array(); // (path => op)
1091
1092 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1093 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1094 if ( $srcRel === null || !$auth ) {
1095 $tmpFiles[$path] = null;
1096 continue;
1097 }
1098 // Get source file extension
1099 $ext = FileBackend::extensionFromPath( $path );
1100 // Create a new temporary file...
1101 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1102 if ( $tmpFile ) {
1103 $handle = fopen( $tmpFile->getPath(), 'wb' );
1104 if ( $handle ) {
1105 $reqs[$path] = array(
1106 'method' => 'GET',
1107 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1108 'headers' => $this->authTokenHeaders( $auth )
1109 + $this->headersFromParams( $params ),
1110 'stream' => $handle,
1111 );
1112 } else {
1113 $tmpFile = null;
1114 }
1115 }
1116 $tmpFiles[$path] = $tmpFile;
1117 }
1118
1119 $isLatest = ( $this->isRGW || !empty( $params['latest'] ) );
1120 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1121 $reqs = $this->http->runMulti( $reqs, $opts );
1122 foreach ( $reqs as $path => $op ) {
1123 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1124 fclose( $op['stream'] ); // close open handle
1125 if ( $rcode >= 200 && $rcode <= 299 ) {
1126 $size = $tmpFiles[$path] ? $tmpFiles[$path]->getSize() : 0;
1127 // Double check that the disk is not full/broken
1128 if ( $size != $rhdrs['content-length'] ) {
1129 $tmpFiles[$path] = null;
1130 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1131 $this->onError( null, __METHOD__,
1132 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1133 }
1134 // Set the file stat process cache in passing
1135 $stat = $this->getStatFromHeaders( $rhdrs );
1136 $stat['latest'] = $isLatest;
1137 $this->cheapCache->set( $path, 'stat', $stat );
1138 } elseif ( $rcode === 404 ) {
1139 $tmpFiles[$path] = false;
1140 } else {
1141 $tmpFiles[$path] = null;
1142 $this->onError( null, __METHOD__,
1143 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1144 }
1145 }
1146
1147 return $tmpFiles;
1148 }
1149
1150 public function getFileHttpUrl( array $params ) {
1151 if ( $this->swiftTempUrlKey != '' ||
1152 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1153 ) {
1154 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1155 if ( $srcRel === null ) {
1156 return null; // invalid path
1157 }
1158
1159 $auth = $this->getAuthentication();
1160 if ( !$auth ) {
1161 return null;
1162 }
1163
1164 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1165 $expires = time() + $ttl;
1166
1167 if ( $this->swiftTempUrlKey != '' ) {
1168 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1169 // Swift wants the signature based on the unencoded object name
1170 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1171 $signature = hash_hmac( 'sha1',
1172 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1173 $this->swiftTempUrlKey
1174 );
1175
1176 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1177 } else { // give S3 API URL for rgw
1178 // Path for signature starts with the bucket
1179 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1180 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1181 // Calculate the hash
1182 $signature = base64_encode( hash_hmac(
1183 'sha1',
1184 "GET\n\n\n{$expires}\n{$spath}",
1185 $this->rgwS3SecretKey,
1186 true // raw
1187 ) );
1188 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1189 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1190 return wfAppendQuery(
1191 str_replace( '/swift/v1', '', // S3 API is the rgw default
1192 $this->storageUrl( $auth ) . $spath ),
1193 array(
1194 'Signature' => $signature,
1195 'Expires' => $expires,
1196 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1197 );
1198 }
1199 }
1200
1201 return null;
1202 }
1203
1204 protected function directoriesAreVirtual() {
1205 return true;
1206 }
1207
1208 /**
1209 * Get headers to send to Swift when reading a file based
1210 * on a FileBackend params array, e.g. that of getLocalCopy().
1211 * $params is currently only checked for a 'latest' flag.
1212 *
1213 * @param array $params
1214 * @return array
1215 */
1216 protected function headersFromParams( array $params ) {
1217 $hdrs = array();
1218 if ( !empty( $params['latest'] ) ) {
1219 $hdrs['x-newest'] = 'true';
1220 }
1221
1222 return $hdrs;
1223 }
1224
1225 /**
1226 * @param FileBackendStoreOpHandle[] $fileOpHandles
1227 *
1228 * @return Status[]
1229 */
1230 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1231 $statuses = array();
1232
1233 $auth = $this->getAuthentication();
1234 if ( !$auth ) {
1235 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1236 $statuses[$index] = Status::newFatal( 'backend-fail-connect', $this->name );
1237 }
1238
1239 return $statuses;
1240 }
1241
1242 // Split the HTTP requests into stages that can be done concurrently
1243 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1244 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1245 $reqs = $fileOpHandle->httpOp;
1246 // Convert the 'url' parameter to an actual URL using $auth
1247 foreach ( $reqs as $stage => &$req ) {
1248 list( $container, $relPath ) = $req['url'];
1249 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1250 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : array();
1251 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1252 $httpReqsByStage[$stage][$index] = $req;
1253 }
1254 $statuses[$index] = Status::newGood();
1255 }
1256
1257 // Run all requests for the first stage, then the next, and so on
1258 $reqCount = count( $httpReqsByStage );
1259 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1260 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1261 foreach ( $httpReqs as $index => $httpReq ) {
1262 // Run the callback for each request of this operation
1263 $callback = $fileOpHandles[$index]->callback;
1264 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1265 // On failure, abort all remaining requests for this operation
1266 // (e.g. abort the DELETE request if the COPY request fails for a move)
1267 if ( !$statuses[$index]->isOK() ) {
1268 $stages = count( $fileOpHandles[$index]->httpOp );
1269 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1270 unset( $httpReqsByStage[$s][$index] );
1271 }
1272 }
1273 }
1274 }
1275
1276 return $statuses;
1277 }
1278
1279 /**
1280 * Set read/write permissions for a Swift container.
1281 *
1282 * @see http://swift.openstack.org/misc.html#acls
1283 *
1284 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1285 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1286 *
1287 * @param string $container Resolved Swift container
1288 * @param array $readGrps List of the possible criteria for a request to have
1289 * access to read a container. Each item is one of the following formats:
1290 * - account:user : Grants access if the request is by the given user
1291 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1292 * matches the expression and the request is not for a listing.
1293 * Setting this to '*' effectively makes a container public.
1294 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1295 * matches the expression and the request is for a listing.
1296 * @param array $writeGrps A list of the possible criteria for a request to have
1297 * access to write to a container. Each item is of the following format:
1298 * - account:user : Grants access if the request is by the given user
1299 * @return Status
1300 */
1301 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1302 $status = Status::newGood();
1303 $auth = $this->getAuthentication();
1304
1305 if ( !$auth ) {
1306 $status->fatal( 'backend-fail-connect', $this->name );
1307
1308 return $status;
1309 }
1310
1311 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1312 'method' => 'POST',
1313 'url' => $this->storageUrl( $auth, $container ),
1314 'headers' => $this->authTokenHeaders( $auth ) + array(
1315 'x-container-read' => implode( ',', $readGrps ),
1316 'x-container-write' => implode( ',', $writeGrps )
1317 )
1318 ) );
1319
1320 if ( $rcode != 204 && $rcode !== 202 ) {
1321 $status->fatal( 'backend-fail-internal', $this->name );
1322 wfDebugLog( 'SwiftBackend', __METHOD__ . ': unexpected rcode value (' . $rcode . ')' );
1323 }
1324
1325 return $status;
1326 }
1327
1328 /**
1329 * Get a Swift container stat array, possibly from process cache.
1330 * Use $reCache if the file count or byte count is needed.
1331 *
1332 * @param string $container Container name
1333 * @param bool $bypassCache Bypass all caches and load from Swift
1334 * @return array|bool|null False on 404, null on failure
1335 */
1336 protected function getContainerStat( $container, $bypassCache = false ) {
1337 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1338
1339 if ( $bypassCache ) { // purge cache
1340 $this->containerStatCache->clear( $container );
1341 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1342 $this->primeContainerCache( array( $container ) ); // check persistent cache
1343 }
1344 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1345 $auth = $this->getAuthentication();
1346 if ( !$auth ) {
1347 return null;
1348 }
1349
1350 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1351 'method' => 'HEAD',
1352 'url' => $this->storageUrl( $auth, $container ),
1353 'headers' => $this->authTokenHeaders( $auth )
1354 ) );
1355
1356 if ( $rcode === 204 ) {
1357 $stat = array(
1358 'count' => $rhdrs['x-container-object-count'],
1359 'bytes' => $rhdrs['x-container-bytes-used']
1360 );
1361 if ( $bypassCache ) {
1362 return $stat;
1363 } else {
1364 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1365 $this->setContainerCache( $container, $stat ); // update persistent cache
1366 }
1367 } elseif ( $rcode === 404 ) {
1368 return false;
1369 } else {
1370 $this->onError( null, __METHOD__,
1371 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1372
1373 return null;
1374 }
1375 }
1376
1377 return $this->containerStatCache->get( $container, 'stat' );
1378 }
1379
1380 /**
1381 * Create a Swift container
1382 *
1383 * @param string $container Container name
1384 * @param array $params
1385 * @return Status
1386 */
1387 protected function createContainer( $container, array $params ) {
1388 $status = Status::newGood();
1389
1390 $auth = $this->getAuthentication();
1391 if ( !$auth ) {
1392 $status->fatal( 'backend-fail-connect', $this->name );
1393
1394 return $status;
1395 }
1396
1397 // @see SwiftFileBackend::setContainerAccess()
1398 if ( empty( $params['noAccess'] ) ) {
1399 $readGrps = array( '.r:*', $this->swiftUser ); // public
1400 } else {
1401 $readGrps = array( $this->swiftUser ); // private
1402 }
1403 $writeGrps = array( $this->swiftUser ); // sanity
1404
1405 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1406 'method' => 'PUT',
1407 'url' => $this->storageUrl( $auth, $container ),
1408 'headers' => $this->authTokenHeaders( $auth ) + array(
1409 'x-container-read' => implode( ',', $readGrps ),
1410 'x-container-write' => implode( ',', $writeGrps )
1411 )
1412 ) );
1413
1414 if ( $rcode === 201 ) { // new
1415 // good
1416 } elseif ( $rcode === 202 ) { // already there
1417 // this shouldn't really happen, but is OK
1418 } else {
1419 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1420 }
1421
1422 return $status;
1423 }
1424
1425 /**
1426 * Delete a Swift container
1427 *
1428 * @param string $container Container name
1429 * @param array $params
1430 * @return Status
1431 */
1432 protected function deleteContainer( $container, array $params ) {
1433 $status = Status::newGood();
1434
1435 $auth = $this->getAuthentication();
1436 if ( !$auth ) {
1437 $status->fatal( 'backend-fail-connect', $this->name );
1438
1439 return $status;
1440 }
1441
1442 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1443 'method' => 'DELETE',
1444 'url' => $this->storageUrl( $auth, $container ),
1445 'headers' => $this->authTokenHeaders( $auth )
1446 ) );
1447
1448 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1449 $this->containerStatCache->clear( $container ); // purge
1450 } elseif ( $rcode === 404 ) { // not there
1451 // this shouldn't really happen, but is OK
1452 } elseif ( $rcode === 409 ) { // not empty
1453 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1454 } else {
1455 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1456 }
1457
1458 return $status;
1459 }
1460
1461 /**
1462 * Get a list of objects under a container.
1463 * Either just the names or a list of stdClass objects with details can be returned.
1464 *
1465 * @param string $fullCont
1466 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1467 * @param int $limit
1468 * @param string|null $after
1469 * @param string|null $prefix
1470 * @param string|null $delim
1471 * @return Status With the list as value
1472 */
1473 private function objectListing(
1474 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1475 ) {
1476 $status = Status::newGood();
1477
1478 $auth = $this->getAuthentication();
1479 if ( !$auth ) {
1480 $status->fatal( 'backend-fail-connect', $this->name );
1481
1482 return $status;
1483 }
1484
1485 $query = array( 'limit' => $limit );
1486 if ( $type === 'info' ) {
1487 $query['format'] = 'json';
1488 }
1489 if ( $after !== null ) {
1490 $query['marker'] = $after;
1491 }
1492 if ( $prefix !== null ) {
1493 $query['prefix'] = $prefix;
1494 }
1495 if ( $delim !== null ) {
1496 $query['delimiter'] = $delim;
1497 }
1498
1499 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1500 'method' => 'GET',
1501 'url' => $this->storageUrl( $auth, $fullCont ),
1502 'query' => $query,
1503 'headers' => $this->authTokenHeaders( $auth )
1504 ) );
1505
1506 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1507 if ( $rcode === 200 ) { // good
1508 if ( $type === 'info' ) {
1509 $status->value = FormatJson::decode( trim( $rbody ) );
1510 } else {
1511 $status->value = explode( "\n", trim( $rbody ) );
1512 }
1513 } elseif ( $rcode === 204 ) {
1514 $status->value = array(); // empty container
1515 } elseif ( $rcode === 404 ) {
1516 $status->value = array(); // no container
1517 } else {
1518 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1519 }
1520
1521 return $status;
1522 }
1523
1524 protected function doPrimeContainerCache( array $containerInfo ) {
1525 foreach ( $containerInfo as $container => $info ) {
1526 $this->containerStatCache->set( $container, 'stat', $info );
1527 }
1528 }
1529
1530 protected function doGetFileStatMulti( array $params ) {
1531 $stats = array();
1532
1533 $auth = $this->getAuthentication();
1534
1535 $reqs = array();
1536 foreach ( $params['srcs'] as $path ) {
1537 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1538 if ( $srcRel === null ) {
1539 $stats[$path] = false;
1540 continue; // invalid storage path
1541 } elseif ( !$auth ) {
1542 $stats[$path] = null;
1543 continue;
1544 }
1545
1546 // (a) Check the container
1547 $cstat = $this->getContainerStat( $srcCont );
1548 if ( $cstat === false ) {
1549 $stats[$path] = false;
1550 continue; // ok, nothing to do
1551 } elseif ( !is_array( $cstat ) ) {
1552 $stats[$path] = null;
1553 continue;
1554 }
1555
1556 $reqs[$path] = array(
1557 'method' => 'HEAD',
1558 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1559 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1560 );
1561 }
1562
1563 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1564 $reqs = $this->http->runMulti( $reqs, $opts );
1565
1566 foreach ( $params['srcs'] as $path ) {
1567 if ( array_key_exists( $path, $stats ) ) {
1568 continue; // some sort of failure above
1569 }
1570 // (b) Check the file
1571 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1572 if ( $rcode === 200 || $rcode === 204 ) {
1573 // Update the object if it is missing some headers
1574 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1575 // Load the stat array from the headers
1576 $stat = $this->getStatFromHeaders( $rhdrs );
1577 if ( $this->isRGW ) {
1578 $stat['latest'] = true; // strong consistency
1579 }
1580 } elseif ( $rcode === 404 ) {
1581 $stat = false;
1582 } else {
1583 $stat = null;
1584 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1585 }
1586 $stats[$path] = $stat;
1587 }
1588
1589 return $stats;
1590 }
1591
1592 /**
1593 * @param array $rhdrs
1594 * @return array
1595 */
1596 protected function getStatFromHeaders( array $rhdrs ) {
1597 // Fetch all of the custom metadata headers
1598 $metadata = $this->getMetadata( $rhdrs );
1599 // Fetch all of the custom raw HTTP headers
1600 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1601
1602 return array(
1603 // Convert various random Swift dates to TS_MW
1604 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1605 // Empty objects actually return no content-length header in Ceph
1606 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1607 'sha1' => isset( $metadata['sha1base36'] ) ? $metadata['sha1base36'] : null,
1608 // Note: manifiest ETags are not an MD5 of the file
1609 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1610 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1611 );
1612 }
1613
1614 /**
1615 * @return array|null Credential map
1616 */
1617 protected function getAuthentication() {
1618 if ( $this->authErrorTimestamp !== null ) {
1619 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1620 return null; // failed last attempt; don't bother
1621 } else { // actually retry this time
1622 $this->authErrorTimestamp = null;
1623 }
1624 }
1625 // Session keys expire after a while, so we renew them periodically
1626 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1627 // Authenticate with proxy and get a session key...
1628 if ( !$this->authCreds || $reAuth ) {
1629 $this->authSessionTimestamp = 0;
1630 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1631 $creds = $this->srvCache->get( $cacheKey ); // credentials
1632 // Try to use the credential cache
1633 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1634 $this->authCreds = $creds;
1635 // Skew the timestamp for worst case to avoid using stale credentials
1636 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1637 } else { // cache miss
1638 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1639 'method' => 'GET',
1640 'url' => "{$this->swiftAuthUrl}/v1.0",
1641 'headers' => array(
1642 'x-auth-user' => $this->swiftUser,
1643 'x-auth-key' => $this->swiftKey
1644 )
1645 ) );
1646
1647 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1648 $this->authCreds = array(
1649 'auth_token' => $rhdrs['x-auth-token'],
1650 'storage_url' => $rhdrs['x-storage-url']
1651 );
1652 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1653 $this->authSessionTimestamp = time();
1654 } elseif ( $rcode === 401 ) {
1655 $this->onError( null, __METHOD__, array(), "Authentication failed.", $rcode );
1656 $this->authErrorTimestamp = time();
1657
1658 return null;
1659 } else {
1660 $this->onError( null, __METHOD__, array(), "HTTP return code: $rcode", $rcode );
1661 $this->authErrorTimestamp = time();
1662
1663 return null;
1664 }
1665 }
1666 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1667 if ( substr( $this->authCreds['storage_url'], -3 ) === '/v1' ) {
1668 $this->isRGW = true; // take advantage of strong consistency in Ceph
1669 }
1670 }
1671
1672 return $this->authCreds;
1673 }
1674
1675 /**
1676 * @param array $creds From getAuthentication()
1677 * @param string $container
1678 * @param string $object
1679 * @return array
1680 */
1681 protected function storageUrl( array $creds, $container = null, $object = null ) {
1682 $parts = array( $creds['storage_url'] );
1683 if ( strlen( $container ) ) {
1684 $parts[] = rawurlencode( $container );
1685 }
1686 if ( strlen( $object ) ) {
1687 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1688 }
1689
1690 return implode( '/', $parts );
1691 }
1692
1693 /**
1694 * @param array $creds From getAuthentication()
1695 * @return array
1696 */
1697 protected function authTokenHeaders( array $creds ) {
1698 return array( 'x-auth-token' => $creds['auth_token'] );
1699 }
1700
1701 /**
1702 * Get the cache key for a container
1703 *
1704 * @param string $username
1705 * @return string
1706 */
1707 private function getCredsCacheKey( $username ) {
1708 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1709 }
1710
1711 /**
1712 * Log an unexpected exception for this backend.
1713 * This also sets the Status object to have a fatal error.
1714 *
1715 * @param Status|null $status
1716 * @param string $func
1717 * @param array $params
1718 * @param string $err Error string
1719 * @param int $code HTTP status
1720 * @param string $desc HTTP status description
1721 */
1722 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1723 if ( $status instanceof Status ) {
1724 $status->fatal( 'backend-fail-internal', $this->name );
1725 }
1726 if ( $code == 401 ) { // possibly a stale token
1727 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1728 }
1729 wfDebugLog( 'SwiftBackend',
1730 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1731 ( $err ? ": $err" : "" )
1732 );
1733 }
1734 }
1735
1736 /**
1737 * @see FileBackendStoreOpHandle
1738 */
1739 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1740 /** @var array List of Requests for MultiHttpClient */
1741 public $httpOp;
1742 /** @var Closure */
1743 public $callback;
1744
1745 /**
1746 * @param SwiftFileBackend $backend
1747 * @param Closure $callback Function that takes (HTTP request array, status)
1748 * @param array $httpOp MultiHttpClient op
1749 */
1750 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1751 $this->backend = $backend;
1752 $this->callback = $callback;
1753 $this->httpOp = $httpOp;
1754 }
1755 }
1756
1757 /**
1758 * SwiftFileBackend helper class to page through listings.
1759 * Swift also has a listing limit of 10,000 objects for sanity.
1760 * Do not use this class from places outside SwiftFileBackend.
1761 *
1762 * @ingroup FileBackend
1763 */
1764 abstract class SwiftFileBackendList implements Iterator {
1765 /** @var array List of path or (path,stat array) entries */
1766 protected $bufferIter = array();
1767
1768 /** @var string List items *after* this path */
1769 protected $bufferAfter = null;
1770
1771 /** @var int */
1772 protected $pos = 0;
1773
1774 /** @var array */
1775 protected $params = array();
1776
1777 /** @var SwiftFileBackend */
1778 protected $backend;
1779
1780 /** @var string Container name */
1781 protected $container;
1782
1783 /** @var string Storage directory */
1784 protected $dir;
1785
1786 /** @var int */
1787 protected $suffixStart;
1788
1789 const PAGE_SIZE = 9000; // file listing buffer size
1790
1791 /**
1792 * @param SwiftFileBackend $backend
1793 * @param string $fullCont Resolved container name
1794 * @param string $dir Resolved directory relative to container
1795 * @param array $params
1796 */
1797 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1798 $this->backend = $backend;
1799 $this->container = $fullCont;
1800 $this->dir = $dir;
1801 if ( substr( $this->dir, -1 ) === '/' ) {
1802 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1803 }
1804 if ( $this->dir == '' ) { // whole container
1805 $this->suffixStart = 0;
1806 } else { // dir within container
1807 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1808 }
1809 $this->params = $params;
1810 }
1811
1812 /**
1813 * @see Iterator::key()
1814 * @return int
1815 */
1816 public function key() {
1817 return $this->pos;
1818 }
1819
1820 /**
1821 * @see Iterator::next()
1822 */
1823 public function next() {
1824 // Advance to the next file in the page
1825 next( $this->bufferIter );
1826 ++$this->pos;
1827 // Check if there are no files left in this page and
1828 // advance to the next page if this page was not empty.
1829 if ( !$this->valid() && count( $this->bufferIter ) ) {
1830 $this->bufferIter = $this->pageFromList(
1831 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1832 ); // updates $this->bufferAfter
1833 }
1834 }
1835
1836 /**
1837 * @see Iterator::rewind()
1838 */
1839 public function rewind() {
1840 $this->pos = 0;
1841 $this->bufferAfter = null;
1842 $this->bufferIter = $this->pageFromList(
1843 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1844 ); // updates $this->bufferAfter
1845 }
1846
1847 /**
1848 * @see Iterator::valid()
1849 * @return bool
1850 */
1851 public function valid() {
1852 if ( $this->bufferIter === null ) {
1853 return false; // some failure?
1854 } else {
1855 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1856 }
1857 }
1858
1859 /**
1860 * Get the given list portion (page)
1861 *
1862 * @param string $container Resolved container name
1863 * @param string $dir Resolved path relative to container
1864 * @param string $after
1865 * @param int $limit
1866 * @param array $params
1867 * @return Traversable|array
1868 */
1869 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1870 }
1871
1872 /**
1873 * Iterator for listing directories
1874 */
1875 class SwiftFileBackendDirList extends SwiftFileBackendList {
1876 /**
1877 * @see Iterator::current()
1878 * @return string|bool String (relative path) or false
1879 */
1880 public function current() {
1881 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1882 }
1883
1884 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1885 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1886 }
1887 }
1888
1889 /**
1890 * Iterator for listing regular files
1891 */
1892 class SwiftFileBackendFileList extends SwiftFileBackendList {
1893 /**
1894 * @see Iterator::current()
1895 * @return string|bool String (relative path) or false
1896 */
1897 public function current() {
1898 list( $path, $stat ) = current( $this->bufferIter );
1899 $relPath = substr( $path, $this->suffixStart );
1900 if ( is_array( $stat ) ) {
1901 $storageDir = rtrim( $this->params['dir'], '/' );
1902 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1903 }
1904
1905 return $relPath;
1906 }
1907
1908 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1909 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1910 }
1911 }