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