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