Removed cloudfiles dependency in SwiftFileBackend
[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-copy', $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-copy', $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 if ( $rcode >= 200 && $rcode <= 299 ) {
1082 // good
1083 } elseif ( $rcode === 404 ) {
1084 $tmpFiles[$path] = false;
1085 } else {
1086 $tmpFiles[$path] = null;
1087 $this->onError( null, __METHOD__,
1088 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1089 }
1090 fclose( $op['stream'] ); // close open handle
1091 }
1092 }
1093
1094 return $tmpFiles;
1095 }
1096
1097 public function getFileHttpUrl( array $params ) {
1098 if ( $this->swiftTempUrlKey != '' ||
1099 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1100 ) {
1101 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1102 if ( $srcRel === null ) {
1103 return null; // invalid path
1104 }
1105
1106 $auth = $this->getAuthentication();
1107 if ( !$auth ) {
1108 return null;
1109 }
1110
1111 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1112 $expires = time() + $ttl;
1113
1114 if ( $this->swiftTempUrlKey != '' ) {
1115 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1116 $signature = hash_hmac( 'sha1',
1117 "GET\n{$expires}\n" . parse_url( $url, PHP_URL_PATH ),
1118 $this->swiftTempUrlKey
1119 );
1120 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1121 } else { // give S3 API URL for rgw
1122 // Path for signature starts with the bucket
1123 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1124 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1125 // Calculate the hash
1126 $signature = base64_encode( hash_hmac(
1127 'sha1',
1128 "GET\n\n\n{$expires}\n{$spath}",
1129 $this->rgwS3SecretKey,
1130 true // raw
1131 ) );
1132 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1133 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1134 return wfAppendQuery(
1135 str_replace( '/swift/v1', '', // S3 API is the rgw default
1136 $this->storageUrl( $auth ) . $spath ),
1137 array(
1138 'Signature' => $signature,
1139 'Expires' => $expires,
1140 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1141 );
1142 }
1143 }
1144
1145 return null;
1146 }
1147
1148 protected function directoriesAreVirtual() {
1149 return true;
1150 }
1151
1152 /**
1153 * Get headers to send to Swift when reading a file based
1154 * on a FileBackend params array, e.g. that of getLocalCopy().
1155 * $params is currently only checked for a 'latest' flag.
1156 *
1157 * @param array $params
1158 * @return array
1159 */
1160 protected function headersFromParams( array $params ) {
1161 $hdrs = array();
1162 if ( !empty( $params['latest'] ) ) {
1163 $hdrs[] = 'X-Newest: true';
1164 }
1165
1166 return $hdrs;
1167 }
1168
1169 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1170 $statuses = array();
1171
1172 $auth = $this->getAuthentication();
1173 if ( !$auth ) {
1174 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1175 $statuses[$index] = Status::newFatal( 'backend-fail-connect', $this->name );
1176 }
1177 return $statuses;
1178 }
1179
1180 // Split the HTTP requests into stages that can be done concurrently
1181 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1182 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1183 $reqs = $fileOpHandle->httpOp;
1184 // Convert the 'url' parameter to an actual URL using $auth
1185 foreach ( $reqs as $stage => &$req ) {
1186 list( $container, $relPath ) = $req['url'];
1187 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1188 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : array();
1189 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1190 $httpReqsByStage[$stage][$index] = $req;
1191 }
1192 $statuses[$index] = Status::newGood();
1193 }
1194
1195 // Run all requests for the first stage, then the next, and so on
1196 for ( $stage = 0; $stage < count( $httpReqsByStage ); ++$stage ) {
1197 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1198 foreach ( $httpReqs as $index => $httpReq ) {
1199 // Run the callback for each request of this operation
1200 $callback = $fileOpHandles[$index]->callback;
1201 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1202 // On failure, abort all remaining requests for this operation
1203 // (e.g. abort the DELETE request if the COPY request fails for a move)
1204 if ( !$statuses[$index]->isOK() ) {
1205 $stages = count( $fileOpHandles[$index]->httpOp );
1206 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1207 unset( $httpReqsByStage[$s][$index] );
1208 }
1209 }
1210 }
1211 }
1212
1213 return $statuses;
1214 }
1215
1216 /**
1217 * Set read/write permissions for a Swift container.
1218 *
1219 * @see http://swift.openstack.org/misc.html#acls
1220 *
1221 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1222 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1223 *
1224 * @param string $container Resolved Swift container
1225 * @param array $readGrps List of the possible criteria for a request to have
1226 * access to read a container. Each item is one of the following formats:
1227 * - account:user : Grants access if the request is by the given user
1228 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1229 * matches the expression and the request is not for a listing.
1230 * Setting this to '*' effectively makes a container public.
1231 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1232 * matches the expression and the request is for a listing.
1233 * @param array $writeGrps A list of the possible criteria for a request to have
1234 * access to write to a container. Each item is of the following format:
1235 * - account:user : Grants access if the request is by the given user
1236 * @return Status
1237 */
1238 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1239 $status = Status::newGood();
1240
1241 $auth = $this->getAuthentication();
1242 if ( !$auth ) {
1243 $status->fatal( 'backend-fail-connect', $this->name );
1244 return $status;
1245 }
1246
1247 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1248 'method' => 'POST',
1249 'url' => $this->storageUrl( $auth, $container ),
1250 'headers' => $this->authTokenHeaders( $auth ) + array(
1251 'x-container-read' => implode( ',', $readGrps ),
1252 'x-container-write' => implode( ',', $writeGrps )
1253 )
1254 ) );
1255
1256 if ( $rcode != 204 && $rcode !== 202 ) {
1257 $status->fatal( 'backend-fail-internal', $this->name );
1258 }
1259
1260 return $status;
1261 }
1262
1263 /**
1264 * Get a Swift container stat array, possibly from process cache.
1265 * Use $reCache if the file count or byte count is needed.
1266 *
1267 * @param string $container Container name
1268 * @param bool $bypassCache Bypass all caches and load from Swift
1269 * @return array|bool|null False on 404, null on failure
1270 */
1271 protected function getContainerStat( $container, $bypassCache = false ) {
1272 if ( $bypassCache ) { // purge cache
1273 $this->containerStatCache->clear( $container );
1274 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1275 $this->primeContainerCache( array( $container ) ); // check persistent cache
1276 }
1277 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1278 $auth = $this->getAuthentication();
1279 if ( !$auth ) {
1280 return null;
1281 }
1282
1283 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1284 'method' => 'HEAD',
1285 'url' => $this->storageUrl( $auth, $container ),
1286 'headers' => $this->authTokenHeaders( $auth )
1287 ) );
1288
1289 if ( $rcode === 204 ) {
1290 $stat = array(
1291 'count' => $rhdrs['x-container-object-count'],
1292 'bytes' => $rhdrs['x-container-bytes-used']
1293 );
1294 if ( $bypassCache ) {
1295 return $stat;
1296 } else {
1297 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1298 }
1299 } elseif ( $rcode === 404 ) {
1300 return false;
1301 } else {
1302 $this->onError( null, __METHOD__,
1303 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1304 return null;
1305 }
1306 }
1307
1308 return $this->containerStatCache->get( $container, 'stat' );
1309 }
1310
1311 /**
1312 * Create a Swift container
1313 *
1314 * @param string $container Container name
1315 * @param array $params
1316 * @return Status
1317 */
1318 protected function createContainer( $container, array $params ) {
1319 $status = Status::newGood();
1320
1321 $auth = $this->getAuthentication();
1322 if ( !$auth ) {
1323 $status->fatal( 'backend-fail-connect', $this->name );
1324 return $status;
1325 }
1326
1327 // @see SwiftFileBackend::setContainerAccess()
1328 if ( empty( $params['noAccess'] ) ) {
1329 $readGrps = array( '.r:*', $this->swiftUser ); // public
1330 } else {
1331 $readGrps = array( $this->swiftUser ); // private
1332 }
1333 $writeGrps = array( $this->swiftUser ); // sanity
1334
1335 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1336 'method' => 'PUT',
1337 'url' => $this->storageUrl( $auth, $container ),
1338 'headers' => $this->authTokenHeaders( $auth ) + array(
1339 'x-container-read' => implode( ',', $readGrps ),
1340 'x-container-write' => implode( ',', $writeGrps )
1341 )
1342 ) );
1343
1344 if ( $rcode === 201 ) { // new
1345 // good
1346 } elseif ( $rcode === 202 ) { // already there
1347 // this shouldn't really happen, but is OK
1348 } else {
1349 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1350 }
1351
1352 return $status;
1353 }
1354
1355 /**
1356 * Delete a Swift container
1357 *
1358 * @param string $container Container name
1359 * @param array $params
1360 * @return Status
1361 */
1362 protected function deleteContainer( $container, array $params ) {
1363 $status = Status::newGood();
1364
1365 $auth = $this->getAuthentication();
1366 if ( !$auth ) {
1367 $status->fatal( 'backend-fail-connect', $this->name );
1368 return $status;
1369 }
1370
1371 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1372 'method' => 'DELETE',
1373 'url' => $this->storageUrl( $auth, $container ),
1374 'headers' => $this->authTokenHeaders( $auth )
1375 ) );
1376
1377 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1378 $this->containerStatCache->clear( $container ); // purge
1379 } elseif ( $rcode === 404 ) { // not there
1380 // this shouldn't really happen, but is OK
1381 } elseif ( $rcode === 409 ) { // not empty
1382 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1383 } else {
1384 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1385 }
1386
1387 return $status;
1388 }
1389
1390 /**
1391 * Get a list of objects under a container.
1392 * Either just the names or a list of stdClass objects with details can be returned.
1393 *
1394 * @param string $fullCont
1395 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1396 * @param integer $limit
1397 * @param string|null $after
1398 * @param string|null $prefix
1399 * @param string|null $delim
1400 * @return Status With the list as value
1401 */
1402 private function objectListing(
1403 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1404 ) {
1405 $status = Status::newGood();
1406
1407 $auth = $this->getAuthentication();
1408 if ( !$auth ) {
1409 $status->fatal( 'backend-fail-connect', $this->name );
1410 return $status;
1411 }
1412
1413 $query = array( 'limit' => $limit );
1414 if ( $type === 'info' ) {
1415 $query['format'] = 'json';
1416 }
1417 if ( $after !== null ) {
1418 $query['marker'] = $after;
1419 }
1420 if ( $prefix !== null ) {
1421 $query['prefix'] = $prefix;
1422 }
1423 if ( $delim !== null ) {
1424 $query['delimiter'] = $delim;
1425 }
1426
1427 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1428 'method' => 'GET',
1429 'url' => $this->storageUrl( $auth, $fullCont ),
1430 'query' => $query,
1431 'headers' => $this->authTokenHeaders( $auth )
1432 ) );
1433
1434 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1435 if ( $rcode === 200 ) { // good
1436 if ( $type === 'info' ) {
1437 $status->value = FormatJson::decode( trim( $rbody ) );
1438 } else {
1439 $status->value = explode( "\n", trim( $rbody ) );
1440 }
1441 } elseif ( $rcode === 204 ) {
1442 $status->value = array(); // empty container
1443 } elseif ( $rcode === 404 ) {
1444 $status->value = array(); // no container
1445 } else {
1446 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1447 }
1448
1449 return $status;
1450 }
1451
1452 protected function doPrimeContainerCache( array $containerInfo ) {
1453 foreach ( $containerInfo as $container => $info ) {
1454 $this->containerStatCache->set( $container, 'stat', $info );
1455 }
1456 }
1457
1458 /**
1459 * @return array|null Credential map
1460 */
1461 protected function getAuthentication() {
1462 if ( $this->authErrorTimestamp !== null ) {
1463 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1464 return null; // failed last attempt; don't bother
1465 } else { // actually retry this time
1466 $this->authErrorTimestamp = null;
1467 }
1468 }
1469 // Session keys expire after a while, so we renew them periodically
1470 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1471 // Authenticate with proxy and get a session key...
1472 if ( !$this->authCreds || $reAuth ) {
1473 $this->authSessionTimestamp = 0;
1474 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1475 $creds = $this->srvCache->get( $cacheKey ); // credentials
1476 // Try to use the credential cache
1477 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1478 $this->authCreds = $creds;
1479 // Skew the timestamp for worst case to avoid using stale credentials
1480 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1481 } else { // cache miss
1482 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1483 'method' => 'GET',
1484 'url' => "{$this->swiftAuthUrl}/v1.0",
1485 'headers' => array(
1486 'x-auth-user' => $this->swiftUser, 'x-auth-key' => $this->swiftKey )
1487 ) );
1488
1489 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1490 $this->authCreds = array(
1491 'auth_token' => $rhdrs['x-auth-token'],
1492 'storage_url' => $rhdrs['x-storage-url']
1493 );
1494 $this->authSessionTimestamp = time();
1495 } elseif ( $rcode === 401 ) {
1496 $this->onError( null, __METHOD__, array(), "Authentication failed.", $rcode );
1497 $this->authErrorTimestamp = time();
1498 return null;
1499 } else {
1500 $this->onError( null, __METHOD__, array(), "HTTP return code: $rcode", $rcode );
1501 $this->authErrorTimestamp = time();
1502 return null;
1503 }
1504 }
1505 }
1506 return $this->authCreds;
1507 }
1508
1509 /**
1510 * @param array $creds From getAuthentication()
1511 * @param string $container
1512 * @param string $object
1513 * @return array
1514 */
1515 protected function storageUrl( array $creds, $container = null, $object = null ) {
1516 $parts = array( $creds['storage_url'] );
1517 if ( strlen( $container ) ) {
1518 $parts[] = rawurlencode( $container );
1519 }
1520 if ( strlen( $object ) ) {
1521 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1522 }
1523 return implode( '/', $parts );
1524 }
1525
1526 /**
1527 * @param array $creds From getAuthentication()
1528 * @return array
1529 */
1530 protected function authTokenHeaders( array $creds ) {
1531 return array( 'x-auth-token' => $creds['auth_token'] );
1532 }
1533
1534 /**
1535 * Get the cache key for a container
1536 *
1537 * @param string $username
1538 * @return string
1539 */
1540 private function getCredsCacheKey( $username ) {
1541 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1542 }
1543
1544 /**
1545 * Log an unexpected exception for this backend.
1546 * This also sets the Status object to have a fatal error.
1547 *
1548 * @param Status $code null
1549 * @param string $func
1550 * @param array $params
1551 * @param string $err Error string
1552 * @param integer $status HTTP status
1553 * @param string $desc HTTP status description
1554 */
1555 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1556 if ( $status instanceof Status ) {
1557 $status->fatal( 'backend-fail-internal', $this->name );
1558 }
1559 if ( $code == 401 ) { // possibly a stale token
1560 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1561 }
1562 wfDebugLog( 'SwiftBackend',
1563 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1564 ( $err ? ": $err" : "" )
1565 );
1566 }
1567 }
1568
1569 /**
1570 * @see FileBackendStoreOpHandle
1571 */
1572 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1573 /** @var array List of Requests for MultiHttpClient */
1574 public $httpOp;
1575 /** @var Closure */
1576 public $callback;
1577
1578 /**
1579 * @param SwiftFileBackend $backend
1580 * @param Closure $callback Function that takes (HTTP request array, status)
1581 * @param array $httpOp MultiHttpClient op
1582 */
1583 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1584 $this->backend = $backend;
1585 $this->callback = $callback;
1586 $this->httpOp = $httpOp;
1587 }
1588 }
1589
1590 /**
1591 * SwiftFileBackend helper class to page through listings.
1592 * Swift also has a listing limit of 10,000 objects for sanity.
1593 * Do not use this class from places outside SwiftFileBackend.
1594 *
1595 * @ingroup FileBackend
1596 */
1597 abstract class SwiftFileBackendList implements Iterator {
1598 /** @var array List of path or (path,stat array) entries */
1599 protected $bufferIter = array();
1600
1601 /** @var string List items *after* this path */
1602 protected $bufferAfter = null;
1603
1604 /** @var int */
1605 protected $pos = 0;
1606
1607 /** @var array */
1608 protected $params = array();
1609
1610 /** @var SwiftFileBackend */
1611 protected $backend;
1612
1613 /** @var string Container name */
1614 protected $container;
1615
1616 /** @var string Storage directory */
1617 protected $dir;
1618
1619 /** @var int */
1620 protected $suffixStart;
1621
1622 const PAGE_SIZE = 9000; // file listing buffer size
1623
1624 /**
1625 * @param SwiftFileBackend $backend
1626 * @param string $fullCont Resolved container name
1627 * @param string $dir Resolved directory relative to container
1628 * @param array $params
1629 */
1630 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1631 $this->backend = $backend;
1632 $this->container = $fullCont;
1633 $this->dir = $dir;
1634 if ( substr( $this->dir, -1 ) === '/' ) {
1635 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1636 }
1637 if ( $this->dir == '' ) { // whole container
1638 $this->suffixStart = 0;
1639 } else { // dir within container
1640 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1641 }
1642 $this->params = $params;
1643 }
1644
1645 /**
1646 * @see Iterator::key()
1647 * @return int
1648 */
1649 public function key() {
1650 return $this->pos;
1651 }
1652
1653 /**
1654 * @see Iterator::next()
1655 */
1656 public function next() {
1657 // Advance to the next file in the page
1658 next( $this->bufferIter );
1659 ++$this->pos;
1660 // Check if there are no files left in this page and
1661 // advance to the next page if this page was not empty.
1662 if ( !$this->valid() && count( $this->bufferIter ) ) {
1663 $this->bufferIter = $this->pageFromList(
1664 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1665 ); // updates $this->bufferAfter
1666 }
1667 }
1668
1669 /**
1670 * @see Iterator::rewind()
1671 */
1672 public function rewind() {
1673 $this->pos = 0;
1674 $this->bufferAfter = null;
1675 $this->bufferIter = $this->pageFromList(
1676 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1677 ); // updates $this->bufferAfter
1678 }
1679
1680 /**
1681 * @see Iterator::valid()
1682 * @return bool
1683 */
1684 public function valid() {
1685 if ( $this->bufferIter === null ) {
1686 return false; // some failure?
1687 } else {
1688 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1689 }
1690 }
1691
1692 /**
1693 * Get the given list portion (page)
1694 *
1695 * @param string $container Resolved container name
1696 * @param string $dir Resolved path relative to container
1697 * @param string $after null
1698 * @param int $limit
1699 * @param array $params
1700 * @return Traversable|array
1701 */
1702 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1703 }
1704
1705 /**
1706 * Iterator for listing directories
1707 */
1708 class SwiftFileBackendDirList extends SwiftFileBackendList {
1709 /**
1710 * @see Iterator::current()
1711 * @return string|bool String (relative path) or false
1712 */
1713 public function current() {
1714 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1715 }
1716
1717 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1718 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1719 }
1720 }
1721
1722 /**
1723 * Iterator for listing regular files
1724 */
1725 class SwiftFileBackendFileList extends SwiftFileBackendList {
1726 /**
1727 * @see Iterator::current()
1728 * @return string|bool String (relative path) or false
1729 */
1730 public function current() {
1731 list( $path, $stat ) = current( $this->bufferIter );
1732 $relPath = substr( $path, $this->suffixStart );
1733 if ( is_array( $stat ) ) {
1734 $storageDir = rtrim( $this->params['dir'], '/' );
1735 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1736 }
1737
1738 return $relPath;
1739 }
1740
1741 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1742 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1743 }
1744 }