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