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