(bug 39383, bug 40059) Allowing badges to use strings and returning this
[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 based file backend.
28 *
29 * This requires the SwiftCloudFiles MediaWiki extension, which includes
30 * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
31 * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
32 *
33 * Status messages should avoid mentioning the Swift account name.
34 * Likewise, error suppression should be used to avoid path disclosure.
35 *
36 * @ingroup FileBackend
37 * @since 1.19
38 */
39 class SwiftFileBackend extends FileBackendStore {
40 /** @var CF_Authentication */
41 protected $auth; // Swift authentication handler
42 protected $authTTL; // integer seconds
43 protected $swiftAnonUser; // string; username to handle unauthenticated requests
44 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
45 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
46 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
47
48 /** @var CF_Connection */
49 protected $conn; // Swift connection handle
50 protected $sessionStarted = 0; // integer UNIX timestamp
51
52 /** @var CloudFilesException */
53 protected $connException;
54 protected $connErrorTime = 0; // UNIX timestamp
55
56 /** @var BagOStuff */
57 protected $srvCache;
58
59 /** @var ProcessCacheLRU */
60 protected $connContainerCache; // container object cache
61
62 /**
63 * @see FileBackendStore::__construct()
64 * Additional $config params include:
65 * - swiftAuthUrl : Swift authentication server URL
66 * - swiftUser : Swift user used by MediaWiki (account:username)
67 * - swiftKey : Swift authentication key for the above user
68 * - swiftAuthTTL : Swift authentication TTL (seconds)
69 * - swiftAnonUser : Swift user used for end-user requests (account:username).
70 * If set, then views of public containers are assumed to go
71 * through this user. If not set, then public containers are
72 * accessible to unauthenticated requests via ".r:*" in the ACL.
73 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
74 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
75 * If files may likely change, this should probably not exceed
76 * a few days. For example, deletions may take this long to apply.
77 * If object purging is enabled, however, this is not an issue.
78 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
79 * - shardViaHashLevels : Map of container names to sharding config with:
80 * - base : base of hash characters, 16 or 36
81 * - levels : the number of hash levels (and digits)
82 * - repeat : hash subdirectories are prefixed with all the
83 * parent hash directory names (e.g. "a/ab/abc")
84 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
85 * If those are not available, then the main cache will be used.
86 * This is probably insecure in shared hosting environments.
87 */
88 public function __construct( array $config ) {
89 parent::__construct( $config );
90 if ( !MWInit::classExists( 'CF_Constants' ) ) {
91 throw new MWException( 'SwiftCloudFiles extension not installed.' );
92 }
93 // Required settings
94 $this->auth = new CF_Authentication(
95 $config['swiftUser'],
96 $config['swiftKey'],
97 null, // account; unused
98 $config['swiftAuthUrl']
99 );
100 // Optional settings
101 $this->authTTL = isset( $config['swiftAuthTTL'] )
102 ? $config['swiftAuthTTL']
103 : 5 * 60; // some sane number
104 $this->swiftAnonUser = isset( $config['swiftAnonUser'] )
105 ? $config['swiftAnonUser']
106 : '';
107 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
108 ? $config['shardViaHashLevels']
109 : '';
110 $this->swiftUseCDN = isset( $config['swiftUseCDN'] )
111 ? $config['swiftUseCDN']
112 : false;
113 $this->swiftCDNExpiry = isset( $config['swiftCDNExpiry'] )
114 ? $config['swiftCDNExpiry']
115 : 12*3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
116 $this->swiftCDNPurgable = isset( $config['swiftCDNPurgable'] )
117 ? $config['swiftCDNPurgable']
118 : true;
119 // Cache container information to mask latency
120 $this->memCache = wfGetMainCache();
121 // Process cache for container info
122 $this->connContainerCache = new ProcessCacheLRU( 300 );
123 // Cache auth token information to avoid RTTs
124 if ( !empty( $config['cacheAuthInfo'] ) ) {
125 if ( php_sapi_name() === 'cli' ) {
126 $this->srvCache = wfGetMainCache(); // preferrably memcached
127 } else {
128 try { // look for APC, XCache, WinCache, ect...
129 $this->srvCache = ObjectCache::newAccelerator( array() );
130 } catch ( Exception $e ) {}
131 }
132 }
133 $this->srvCache = $this->srvCache ? $this->srvCache : new EmptyBagOStuff();
134 }
135
136 /**
137 * @see FileBackendStore::resolveContainerPath()
138 * @return null
139 */
140 protected function resolveContainerPath( $container, $relStoragePath ) {
141 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
142 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
143 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
144 return null; // too long for Swift
145 }
146 return $relStoragePath;
147 }
148
149 /**
150 * @see FileBackendStore::isPathUsableInternal()
151 * @return bool
152 */
153 public function isPathUsableInternal( $storagePath ) {
154 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
155 if ( $rel === null ) {
156 return false; // invalid
157 }
158
159 try {
160 $this->getContainer( $container );
161 return true; // container exists
162 } catch ( NoSuchContainerException $e ) {
163 } catch ( CloudFilesException $e ) { // some other exception?
164 $this->handleException( $e, null, __METHOD__, array( 'path' => $storagePath ) );
165 }
166
167 return false;
168 }
169
170 /**
171 * @param $disposition string Content-Disposition header value
172 * @return string Truncated Content-Disposition header value to meet Swift limits
173 */
174 protected function truncDisp( $disposition ) {
175 $res = '';
176 foreach ( explode( ';', $disposition ) as $part ) {
177 $part = trim( $part );
178 $new = ( $res === '' ) ? $part : "{$res};{$part}";
179 if ( strlen( $new ) <= 255 ) {
180 $res = $new;
181 } else {
182 break; // too long; sigh
183 }
184 }
185 return $res;
186 }
187
188 /**
189 * @see FileBackendStore::doCreateInternal()
190 * @return Status
191 */
192 protected function doCreateInternal( array $params ) {
193 $status = Status::newGood();
194
195 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
196 if ( $dstRel === null ) {
197 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
198 return $status;
199 }
200
201 // (a) Check the destination container and object
202 try {
203 $dContObj = $this->getContainer( $dstCont );
204 } catch ( NoSuchContainerException $e ) {
205 $status->fatal( 'backend-fail-create', $params['dst'] );
206 return $status;
207 } catch ( CloudFilesException $e ) { // some other exception?
208 $this->handleException( $e, $status, __METHOD__, $params );
209 return $status;
210 }
211
212 // (b) Get a SHA-1 hash of the object
213 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
214
215 // (c) Actually create the object
216 try {
217 // Create a fresh CF_Object with no fields preloaded.
218 // We don't want to preserve headers, metadata, and such.
219 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
220 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
221 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
222 // The MD5 here will be checked within Swift against its own MD5.
223 $obj->set_etag( md5( $params['content'] ) );
224 // Use the same content type as StreamFile for security
225 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
226 if ( !strlen( $obj->content_type ) ) { // special case
227 $obj->content_type = 'unknown/unknown';
228 }
229 // Set the Content-Disposition header if requested
230 if ( isset( $params['disposition'] ) ) {
231 $obj->headers['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
232 }
233 if ( !empty( $params['async'] ) ) { // deferred
234 $op = $obj->write_async( $params['content'] );
235 $status->value = new SwiftFileOpHandle( $this, $params, 'Create', $op );
236 $status->value->affectedObjects[] = $obj;
237 } else { // actually write the object in Swift
238 $obj->write( $params['content'] );
239 $this->purgeCDNCache( array( $obj ) );
240 }
241 } catch ( CDNNotEnabledException $e ) {
242 // CDN not enabled; nothing to see here
243 } catch ( BadContentTypeException $e ) {
244 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
245 } catch ( CloudFilesException $e ) { // some other exception?
246 $this->handleException( $e, $status, __METHOD__, $params );
247 }
248
249 return $status;
250 }
251
252 /**
253 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
254 */
255 protected function _getResponseCreate( CF_Async_Op $cfOp, Status $status, array $params ) {
256 try {
257 $cfOp->getLastResponse();
258 } catch ( BadContentTypeException $e ) {
259 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
260 }
261 }
262
263 /**
264 * @see FileBackendStore::doStoreInternal()
265 * @return Status
266 */
267 protected function doStoreInternal( array $params ) {
268 $status = Status::newGood();
269
270 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
271 if ( $dstRel === null ) {
272 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
273 return $status;
274 }
275
276 // (a) Check the destination container and object
277 try {
278 $dContObj = $this->getContainer( $dstCont );
279 } catch ( NoSuchContainerException $e ) {
280 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
281 return $status;
282 } catch ( CloudFilesException $e ) { // some other exception?
283 $this->handleException( $e, $status, __METHOD__, $params );
284 return $status;
285 }
286
287 // (b) Get a SHA-1 hash of the object
288 $sha1Hash = sha1_file( $params['src'] );
289 if ( $sha1Hash === false ) { // source doesn't exist?
290 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
291 return $status;
292 }
293 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
294
295 // (c) Actually store the object
296 try {
297 // Create a fresh CF_Object with no fields preloaded.
298 // We don't want to preserve headers, metadata, and such.
299 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
300 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
301 // The MD5 here will be checked within Swift against its own MD5.
302 $obj->set_etag( md5_file( $params['src'] ) );
303 // Use the same content type as StreamFile for security
304 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
305 if ( !strlen( $obj->content_type ) ) { // special case
306 $obj->content_type = 'unknown/unknown';
307 }
308 // Set the Content-Disposition header if requested
309 if ( isset( $params['disposition'] ) ) {
310 $obj->headers['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
311 }
312 if ( !empty( $params['async'] ) ) { // deferred
313 wfSuppressWarnings();
314 $fp = fopen( $params['src'], 'rb' );
315 wfRestoreWarnings();
316 if ( !$fp ) {
317 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
318 } else {
319 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
320 $status->value = new SwiftFileOpHandle( $this, $params, 'Store', $op );
321 $status->value->resourcesToClose[] = $fp;
322 $status->value->affectedObjects[] = $obj;
323 }
324 } else { // actually write the object in Swift
325 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
326 $this->purgeCDNCache( array( $obj ) );
327 }
328 } catch ( CDNNotEnabledException $e ) {
329 // CDN not enabled; nothing to see here
330 } catch ( BadContentTypeException $e ) {
331 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
332 } catch ( IOException $e ) {
333 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
334 } catch ( CloudFilesException $e ) { // some other exception?
335 $this->handleException( $e, $status, __METHOD__, $params );
336 }
337
338 return $status;
339 }
340
341 /**
342 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
343 */
344 protected function _getResponseStore( CF_Async_Op $cfOp, Status $status, array $params ) {
345 try {
346 $cfOp->getLastResponse();
347 } catch ( BadContentTypeException $e ) {
348 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
349 } catch ( IOException $e ) {
350 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
351 }
352 }
353
354 /**
355 * @see FileBackendStore::doCopyInternal()
356 * @return Status
357 */
358 protected function doCopyInternal( array $params ) {
359 $status = Status::newGood();
360
361 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
362 if ( $srcRel === null ) {
363 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
364 return $status;
365 }
366
367 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
368 if ( $dstRel === null ) {
369 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
370 return $status;
371 }
372
373 // (a) Check the source/destination containers and destination object
374 try {
375 $sContObj = $this->getContainer( $srcCont );
376 $dContObj = $this->getContainer( $dstCont );
377 } catch ( NoSuchContainerException $e ) {
378 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
379 return $status;
380 } catch ( CloudFilesException $e ) { // some other exception?
381 $this->handleException( $e, $status, __METHOD__, $params );
382 return $status;
383 }
384
385 // (b) Actually copy the file to the destination
386 try {
387 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
388 $hdrs = array(); // source file headers to override with new values
389 if ( isset( $params['disposition'] ) ) {
390 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
391 }
392 if ( !empty( $params['async'] ) ) { // deferred
393 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
394 $status->value = new SwiftFileOpHandle( $this, $params, 'Copy', $op );
395 $status->value->affectedObjects[] = $dstObj;
396 } else { // actually write the object in Swift
397 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
398 $this->purgeCDNCache( array( $dstObj ) );
399 }
400 } catch ( CDNNotEnabledException $e ) {
401 // CDN not enabled; nothing to see here
402 } catch ( NoSuchObjectException $e ) { // source object does not exist
403 if ( empty( $params['ignoreMissingSource'] ) ) {
404 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
405 }
406 } catch ( CloudFilesException $e ) { // some other exception?
407 $this->handleException( $e, $status, __METHOD__, $params );
408 }
409
410 return $status;
411 }
412
413 /**
414 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
415 */
416 protected function _getResponseCopy( CF_Async_Op $cfOp, Status $status, array $params ) {
417 try {
418 $cfOp->getLastResponse();
419 } catch ( NoSuchObjectException $e ) { // source object does not exist
420 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
421 }
422 }
423
424 /**
425 * @see FileBackendStore::doMoveInternal()
426 * @return Status
427 */
428 protected function doMoveInternal( array $params ) {
429 $status = Status::newGood();
430
431 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
432 if ( $srcRel === null ) {
433 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
434 return $status;
435 }
436
437 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
438 if ( $dstRel === null ) {
439 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
440 return $status;
441 }
442
443 // (a) Check the source/destination containers and destination object
444 try {
445 $sContObj = $this->getContainer( $srcCont );
446 $dContObj = $this->getContainer( $dstCont );
447 } catch ( NoSuchContainerException $e ) {
448 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
449 return $status;
450 } catch ( CloudFilesException $e ) { // some other exception?
451 $this->handleException( $e, $status, __METHOD__, $params );
452 return $status;
453 }
454
455 // (b) Actually move the file to the destination
456 try {
457 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
458 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
459 $hdrs = array(); // source file headers to override with new values
460 if ( isset( $params['disposition'] ) ) {
461 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
462 }
463 if ( !empty( $params['async'] ) ) { // deferred
464 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
465 $status->value = new SwiftFileOpHandle( $this, $params, 'Move', $op );
466 $status->value->affectedObjects[] = $srcObj;
467 $status->value->affectedObjects[] = $dstObj;
468 } else { // actually write the object in Swift
469 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
470 $this->purgeCDNCache( array( $srcObj ) );
471 $this->purgeCDNCache( array( $dstObj ) );
472 }
473 } catch ( CDNNotEnabledException $e ) {
474 // CDN not enabled; nothing to see here
475 } catch ( NoSuchObjectException $e ) { // source object does not exist
476 if ( empty( $params['ignoreMissingSource'] ) ) {
477 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
478 }
479 } catch ( CloudFilesException $e ) { // some other exception?
480 $this->handleException( $e, $status, __METHOD__, $params );
481 }
482
483 return $status;
484 }
485
486 /**
487 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
488 */
489 protected function _getResponseMove( CF_Async_Op $cfOp, Status $status, array $params ) {
490 try {
491 $cfOp->getLastResponse();
492 } catch ( NoSuchObjectException $e ) { // source object does not exist
493 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
494 }
495 }
496
497 /**
498 * @see FileBackendStore::doDeleteInternal()
499 * @return Status
500 */
501 protected function doDeleteInternal( array $params ) {
502 $status = Status::newGood();
503
504 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
505 if ( $srcRel === null ) {
506 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
507 return $status;
508 }
509
510 try {
511 $sContObj = $this->getContainer( $srcCont );
512 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
513 if ( !empty( $params['async'] ) ) { // deferred
514 $op = $sContObj->delete_object_async( $srcRel );
515 $status->value = new SwiftFileOpHandle( $this, $params, 'Delete', $op );
516 $status->value->affectedObjects[] = $srcObj;
517 } else { // actually write the object in Swift
518 $sContObj->delete_object( $srcRel );
519 $this->purgeCDNCache( array( $srcObj ) );
520 }
521 } catch ( CDNNotEnabledException $e ) {
522 // CDN not enabled; nothing to see here
523 } catch ( NoSuchContainerException $e ) {
524 $status->fatal( 'backend-fail-delete', $params['src'] );
525 } catch ( NoSuchObjectException $e ) {
526 if ( empty( $params['ignoreMissingSource'] ) ) {
527 $status->fatal( 'backend-fail-delete', $params['src'] );
528 }
529 } catch ( CloudFilesException $e ) { // some other exception?
530 $this->handleException( $e, $status, __METHOD__, $params );
531 }
532
533 return $status;
534 }
535
536 /**
537 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
538 */
539 protected function _getResponseDelete( CF_Async_Op $cfOp, Status $status, array $params ) {
540 try {
541 $cfOp->getLastResponse();
542 } catch ( NoSuchContainerException $e ) {
543 $status->fatal( 'backend-fail-delete', $params['src'] );
544 } catch ( NoSuchObjectException $e ) {
545 if ( empty( $params['ignoreMissingSource'] ) ) {
546 $status->fatal( 'backend-fail-delete', $params['src'] );
547 }
548 }
549 }
550
551 /**
552 * @see FileBackendStore::doPrepareInternal()
553 * @return Status
554 */
555 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
556 $status = Status::newGood();
557
558 // (a) Check if container already exists
559 try {
560 $contObj = $this->getContainer( $fullCont );
561 // NoSuchContainerException not thrown: container must exist
562 return $status; // already exists
563 } catch ( NoSuchContainerException $e ) {
564 // NoSuchContainerException thrown: container does not exist
565 } catch ( CloudFilesException $e ) { // some other exception?
566 $this->handleException( $e, $status, __METHOD__, $params );
567 return $status;
568 }
569
570 // (b) Create container as needed
571 try {
572 $contObj = $this->createContainer( $fullCont );
573 if ( !empty( $params['noAccess'] ) ) {
574 // Make container private to end-users...
575 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
576 } else {
577 // Make container public to end-users...
578 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
579 }
580 if ( $this->swiftUseCDN ) { // Rackspace style CDN
581 $contObj->make_public( $this->swiftCDNExpiry );
582 }
583 } catch ( CDNNotEnabledException $e ) {
584 // CDN not enabled; nothing to see here
585 } catch ( CloudFilesException $e ) { // some other exception?
586 $this->handleException( $e, $status, __METHOD__, $params );
587 return $status;
588 }
589
590 return $status;
591 }
592
593 /**
594 * @see FileBackendStore::doSecureInternal()
595 * @return Status
596 */
597 protected function doSecureInternal( $fullCont, $dir, array $params ) {
598 $status = Status::newGood();
599 if ( empty( $params['noAccess'] ) ) {
600 return $status; // nothing to do
601 }
602
603 // Restrict container from end-users...
604 try {
605 // doPrepareInternal() should have been called,
606 // so the Swift container should already exist...
607 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
608 // NoSuchContainerException not thrown: container must exist
609
610 // Make container private to end-users...
611 $status->merge( $this->setContainerAccess(
612 $contObj,
613 array( $this->auth->username ), // read
614 array( $this->auth->username ) // write
615 ) );
616 if ( $this->swiftUseCDN && $contObj->is_public() ) { // Rackspace style CDN
617 $contObj->make_private();
618 }
619 } catch ( CDNNotEnabledException $e ) {
620 // CDN not enabled; nothing to see here
621 } catch ( CloudFilesException $e ) { // some other exception?
622 $this->handleException( $e, $status, __METHOD__, $params );
623 }
624
625 return $status;
626 }
627
628 /**
629 * @see FileBackendStore::doPublishInternal()
630 * @return Status
631 */
632 protected function doPublishInternal( $fullCont, $dir, array $params ) {
633 $status = Status::newGood();
634
635 // Unrestrict container from end-users...
636 try {
637 // doPrepareInternal() should have been called,
638 // so the Swift container should already exist...
639 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
640 // NoSuchContainerException not thrown: container must exist
641
642 // Make container public to end-users...
643 if ( $this->swiftAnonUser != '' ) {
644 $status->merge( $this->setContainerAccess(
645 $contObj,
646 array( $this->auth->username, $this->swiftAnonUser ), // read
647 array( $this->auth->username, $this->swiftAnonUser ) // write
648 ) );
649 } else {
650 $status->merge( $this->setContainerAccess(
651 $contObj,
652 array( $this->auth->username, '.r:*' ), // read
653 array( $this->auth->username ) // write
654 ) );
655 }
656 if ( $this->swiftUseCDN && !$contObj->is_public() ) { // Rackspace style CDN
657 $contObj->make_public();
658 }
659 } catch ( CDNNotEnabledException $e ) {
660 // CDN not enabled; nothing to see here
661 } catch ( CloudFilesException $e ) { // some other exception?
662 $this->handleException( $e, $status, __METHOD__, $params );
663 }
664
665 return $status;
666 }
667
668 /**
669 * @see FileBackendStore::doCleanInternal()
670 * @return Status
671 */
672 protected function doCleanInternal( $fullCont, $dir, array $params ) {
673 $status = Status::newGood();
674
675 // Only containers themselves can be removed, all else is virtual
676 if ( $dir != '' ) {
677 return $status; // nothing to do
678 }
679
680 // (a) Check the container
681 try {
682 $contObj = $this->getContainer( $fullCont, true );
683 } catch ( NoSuchContainerException $e ) {
684 return $status; // ok, nothing to do
685 } catch ( CloudFilesException $e ) { // some other exception?
686 $this->handleException( $e, $status, __METHOD__, $params );
687 return $status;
688 }
689
690 // (b) Delete the container if empty
691 if ( $contObj->object_count == 0 ) {
692 try {
693 $this->deleteContainer( $fullCont );
694 } catch ( NoSuchContainerException $e ) {
695 return $status; // race?
696 } catch ( NonEmptyContainerException $e ) {
697 return $status; // race? consistency delay?
698 } catch ( CloudFilesException $e ) { // some other exception?
699 $this->handleException( $e, $status, __METHOD__, $params );
700 return $status;
701 }
702 }
703
704 return $status;
705 }
706
707 /**
708 * @see FileBackendStore::doFileExists()
709 * @return array|bool|null
710 */
711 protected function doGetFileStat( array $params ) {
712 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
713 if ( $srcRel === null ) {
714 return false; // invalid storage path
715 }
716
717 $stat = false;
718 try {
719 $contObj = $this->getContainer( $srcCont );
720 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
721 $this->addMissingMetadata( $srcObj, $params['src'] );
722 $stat = array(
723 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
724 'mtime' => wfTimestamp( TS_MW, $srcObj->last_modified ),
725 'size' => (int)$srcObj->content_length,
726 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
727 );
728 } catch ( NoSuchContainerException $e ) {
729 } catch ( NoSuchObjectException $e ) {
730 } catch ( CloudFilesException $e ) { // some other exception?
731 $stat = null;
732 $this->handleException( $e, null, __METHOD__, $params );
733 }
734
735 return $stat;
736 }
737
738 /**
739 * Fill in any missing object metadata and save it to Swift
740 *
741 * @param $obj CF_Object
742 * @param $path string Storage path to object
743 * @return bool Success
744 * @throws Exception cloudfiles exceptions
745 */
746 protected function addMissingMetadata( CF_Object $obj, $path ) {
747 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
748 return true; // nothing to do
749 }
750 wfProfileIn( __METHOD__ );
751 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING );
752 $status = Status::newGood();
753 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
754 if ( $status->isOK() ) {
755 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
756 if ( $tmpFile ) {
757 $hash = $tmpFile->getSha1Base36();
758 if ( $hash !== false ) {
759 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
760 $obj->sync_metadata(); // save to Swift
761 wfProfileOut( __METHOD__ );
762 return true; // success
763 }
764 }
765 }
766 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
767 wfProfileOut( __METHOD__ );
768 return false; // failed
769 }
770
771 /**
772 * @see FileBackendStore::doGetFileContentsMulti()
773 * @return Array
774 */
775 protected function doGetFileContentsMulti( array $params ) {
776 $contents = array();
777
778 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
779 // Blindly create tmp files and stream to them, catching any exception if the file does
780 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
781 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
782 $cfOps = array(); // (path => CF_Async_Op)
783
784 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
785 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
786 if ( $srcRel === null ) {
787 $contents[$path] = false;
788 continue;
789 }
790 $data = false;
791 try {
792 $sContObj = $this->getContainer( $srcCont );
793 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
794 // Get source file extension
795 $ext = FileBackend::extensionFromPath( $path );
796 // Create a new temporary memory file...
797 $handle = fopen( 'php://temp', 'wb' );
798 if ( $handle ) {
799 $headers = $this->headersFromParams( $params );
800 if ( count( $pathBatch ) > 1 ) {
801 $cfOps[$path] = $obj->stream_async( $handle, $headers );
802 $cfOps[$path]->_file_handle = $handle; // close this later
803 } else {
804 $obj->stream( $handle, $headers );
805 rewind( $handle ); // start from the beginning
806 $data = stream_get_contents( $handle );
807 fclose( $handle );
808 }
809 } else {
810 $data = false;
811 }
812 } catch ( NoSuchContainerException $e ) {
813 $data = false;
814 } catch ( NoSuchObjectException $e ) {
815 $data = false;
816 } catch ( CloudFilesException $e ) { // some other exception?
817 $data = false;
818 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
819 }
820 $contents[$path] = $data;
821 }
822
823 $batch = new CF_Async_Op_Batch( $cfOps );
824 $cfOps = $batch->execute();
825 foreach ( $cfOps as $path => $cfOp ) {
826 try {
827 $cfOp->getLastResponse();
828 rewind( $cfOp->_file_handle ); // start from the beginning
829 $contents[$path] = stream_get_contents( $cfOp->_file_handle );
830 } catch ( NoSuchContainerException $e ) {
831 $contents[$path] = false;
832 } catch ( NoSuchObjectException $e ) {
833 $contents[$path] = false;
834 } catch ( CloudFilesException $e ) { // some other exception?
835 $contents[$path] = false;
836 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
837 }
838 fclose( $cfOp->_file_handle ); // close open handle
839 }
840 }
841
842 return $contents;
843 }
844
845 /**
846 * @see FileBackendStore::doDirectoryExists()
847 * @return bool|null
848 */
849 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
850 try {
851 $container = $this->getContainer( $fullCont );
852 $prefix = ( $dir == '' ) ? null : "{$dir}/";
853 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
854 } catch ( NoSuchContainerException $e ) {
855 return false;
856 } catch ( CloudFilesException $e ) { // some other exception?
857 $this->handleException( $e, null, __METHOD__,
858 array( 'cont' => $fullCont, 'dir' => $dir ) );
859 }
860
861 return null; // error
862 }
863
864 /**
865 * @see FileBackendStore::getDirectoryListInternal()
866 * @return SwiftFileBackendDirList
867 */
868 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
869 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
870 }
871
872 /**
873 * @see FileBackendStore::getFileListInternal()
874 * @return SwiftFileBackendFileList
875 */
876 public function getFileListInternal( $fullCont, $dir, array $params ) {
877 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
878 }
879
880 /**
881 * Do not call this function outside of SwiftFileBackendFileList
882 *
883 * @param $fullCont string Resolved container name
884 * @param $dir string Resolved storage directory with no trailing slash
885 * @param $after string|null Storage path of file to list items after
886 * @param $limit integer Max number of items to list
887 * @param $params Array Includes flag for 'topOnly'
888 * @return Array List of relative paths of dirs directly under $dir
889 */
890 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
891 $dirs = array();
892 if ( $after === INF ) {
893 return $dirs; // nothing more
894 }
895 wfProfileIn( __METHOD__ . '-' . $this->name );
896
897 try {
898 $container = $this->getContainer( $fullCont );
899 $prefix = ( $dir == '' ) ? null : "{$dir}/";
900 // Non-recursive: only list dirs right under $dir
901 if ( !empty( $params['topOnly'] ) ) {
902 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
903 foreach ( $objects as $object ) { // files and dirs
904 if ( substr( $object, -1 ) === '/' ) {
905 $dirs[] = $object; // directories end in '/'
906 }
907 }
908 // Recursive: list all dirs under $dir and its subdirs
909 } else {
910 // Get directory from last item of prior page
911 $lastDir = $this->getParentDir( $after ); // must be first page
912 $objects = $container->list_objects( $limit, $after, $prefix );
913 foreach ( $objects as $object ) { // files
914 $objectDir = $this->getParentDir( $object ); // directory of object
915 if ( $objectDir !== false ) { // file has a parent dir
916 // Swift stores paths in UTF-8, using binary sorting.
917 // See function "create_container_table" in common/db.py.
918 // If a directory is not "greater" than the last one,
919 // then it was already listed by the calling iterator.
920 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
921 $pDir = $objectDir;
922 do { // add dir and all its parent dirs
923 $dirs[] = "{$pDir}/";
924 $pDir = $this->getParentDir( $pDir );
925 } while ( $pDir !== false // sanity
926 && strcmp( $pDir, $lastDir ) > 0 // not done already
927 && strlen( $pDir ) > strlen( $dir ) // within $dir
928 );
929 }
930 $lastDir = $objectDir;
931 }
932 }
933 }
934 if ( count( $objects ) < $limit ) {
935 $after = INF; // avoid a second RTT
936 } else {
937 $after = end( $objects ); // update last item
938 }
939 } catch ( NoSuchContainerException $e ) {
940 } catch ( CloudFilesException $e ) { // some other exception?
941 $this->handleException( $e, null, __METHOD__,
942 array( 'cont' => $fullCont, 'dir' => $dir ) );
943 }
944
945 wfProfileOut( __METHOD__ . '-' . $this->name );
946 return $dirs;
947 }
948
949 protected function getParentDir( $path ) {
950 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
951 }
952
953 /**
954 * Do not call this function outside of SwiftFileBackendFileList
955 *
956 * @param $fullCont string Resolved container name
957 * @param $dir string Resolved storage directory with no trailing slash
958 * @param $after string|null Storage path of file to list items after
959 * @param $limit integer Max number of items to list
960 * @param $params Array Includes flag for 'topOnly'
961 * @return Array List of relative paths of files under $dir
962 */
963 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
964 $files = array();
965 if ( $after === INF ) {
966 return $files; // nothing more
967 }
968 wfProfileIn( __METHOD__ . '-' . $this->name );
969
970 try {
971 $container = $this->getContainer( $fullCont );
972 $prefix = ( $dir == '' ) ? null : "{$dir}/";
973 // Non-recursive: only list files right under $dir
974 if ( !empty( $params['topOnly'] ) ) { // files and dirs
975 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
976 foreach ( $objects as $object ) {
977 if ( substr( $object, -1 ) !== '/' ) {
978 $files[] = $object; // directories end in '/'
979 }
980 }
981 // Recursive: list all files under $dir and its subdirs
982 } else { // files
983 $objects = $container->list_objects( $limit, $after, $prefix );
984 $files = $objects;
985 }
986 if ( count( $objects ) < $limit ) {
987 $after = INF; // avoid a second RTT
988 } else {
989 $after = end( $objects ); // update last item
990 }
991 } catch ( NoSuchContainerException $e ) {
992 } catch ( CloudFilesException $e ) { // some other exception?
993 $this->handleException( $e, null, __METHOD__,
994 array( 'cont' => $fullCont, 'dir' => $dir ) );
995 }
996
997 wfProfileOut( __METHOD__ . '-' . $this->name );
998 return $files;
999 }
1000
1001 /**
1002 * @see FileBackendStore::doGetFileSha1base36()
1003 * @return bool
1004 */
1005 protected function doGetFileSha1base36( array $params ) {
1006 $stat = $this->getFileStat( $params );
1007 if ( $stat ) {
1008 return $stat['sha1'];
1009 } else {
1010 return false;
1011 }
1012 }
1013
1014 /**
1015 * @see FileBackendStore::doStreamFile()
1016 * @return Status
1017 */
1018 protected function doStreamFile( array $params ) {
1019 $status = Status::newGood();
1020
1021 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1022 if ( $srcRel === null ) {
1023 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1024 }
1025
1026 try {
1027 $cont = $this->getContainer( $srcCont );
1028 } catch ( NoSuchContainerException $e ) {
1029 $status->fatal( 'backend-fail-stream', $params['src'] );
1030 return $status;
1031 } catch ( CloudFilesException $e ) { // some other exception?
1032 $this->handleException( $e, $status, __METHOD__, $params );
1033 return $status;
1034 }
1035
1036 try {
1037 $output = fopen( 'php://output', 'wb' );
1038 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1039 $obj->stream( $output, $this->headersFromParams( $params ) );
1040 } catch ( NoSuchObjectException $e ) {
1041 $status->fatal( 'backend-fail-stream', $params['src'] );
1042 } catch ( CloudFilesException $e ) { // some other exception?
1043 $this->handleException( $e, $status, __METHOD__, $params );
1044 }
1045
1046 return $status;
1047 }
1048
1049 /**
1050 * @see FileBackendStore::doGetLocalCopyMulti()
1051 * @return null|TempFSFile
1052 */
1053 protected function doGetLocalCopyMulti( array $params ) {
1054 $tmpFiles = array();
1055
1056 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1057 // Blindly create tmp files and stream to them, catching any exception if the file does
1058 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1059 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1060 $cfOps = array(); // (path => CF_Async_Op)
1061
1062 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1063 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1064 if ( $srcRel === null ) {
1065 $tmpFiles[$path] = null;
1066 continue;
1067 }
1068 $tmpFile = null;
1069 try {
1070 $sContObj = $this->getContainer( $srcCont );
1071 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1072 // Get source file extension
1073 $ext = FileBackend::extensionFromPath( $path );
1074 // Create a new temporary file...
1075 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1076 if ( $tmpFile ) {
1077 $handle = fopen( $tmpFile->getPath(), 'wb' );
1078 if ( $handle ) {
1079 $headers = $this->headersFromParams( $params );
1080 if ( count( $pathBatch ) > 1 ) {
1081 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1082 $cfOps[$path]->_file_handle = $handle; // close this later
1083 } else {
1084 $obj->stream( $handle, $headers );
1085 fclose( $handle );
1086 }
1087 } else {
1088 $tmpFile = null;
1089 }
1090 }
1091 } catch ( NoSuchContainerException $e ) {
1092 $tmpFile = null;
1093 } catch ( NoSuchObjectException $e ) {
1094 $tmpFile = null;
1095 } catch ( CloudFilesException $e ) { // some other exception?
1096 $tmpFile = null;
1097 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1098 }
1099 $tmpFiles[$path] = $tmpFile;
1100 }
1101
1102 $batch = new CF_Async_Op_Batch( $cfOps );
1103 $cfOps = $batch->execute();
1104 foreach ( $cfOps as $path => $cfOp ) {
1105 try {
1106 $cfOp->getLastResponse();
1107 } catch ( NoSuchContainerException $e ) {
1108 $tmpFiles[$path] = null;
1109 } catch ( NoSuchObjectException $e ) {
1110 $tmpFiles[$path] = null;
1111 } catch ( CloudFilesException $e ) { // some other exception?
1112 $tmpFiles[$path] = null;
1113 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1114 }
1115 fclose( $cfOp->_file_handle ); // close open handle
1116 }
1117 }
1118
1119 return $tmpFiles;
1120 }
1121
1122 /**
1123 * @see FileBackendStore::directoriesAreVirtual()
1124 * @return bool
1125 */
1126 protected function directoriesAreVirtual() {
1127 return true;
1128 }
1129
1130 /**
1131 * Get headers to send to Swift when reading a file based
1132 * on a FileBackend params array, e.g. that of getLocalCopy().
1133 * $params is currently only checked for a 'latest' flag.
1134 *
1135 * @param $params Array
1136 * @return Array
1137 */
1138 protected function headersFromParams( array $params ) {
1139 $hdrs = array();
1140 if ( !empty( $params['latest'] ) ) {
1141 $hdrs[] = 'X-Newest: true';
1142 }
1143 return $hdrs;
1144 }
1145
1146 /**
1147 * @see FileBackendStore::doExecuteOpHandlesInternal()
1148 * @return Array List of corresponding Status objects
1149 */
1150 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1151 $statuses = array();
1152
1153 $cfOps = array(); // list of CF_Async_Op objects
1154 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1155 $cfOps[$index] = $fileOpHandle->cfOp;
1156 }
1157 $batch = new CF_Async_Op_Batch( $cfOps );
1158
1159 $cfOps = $batch->execute();
1160 foreach ( $cfOps as $index => $cfOp ) {
1161 $status = Status::newGood();
1162 try { // catch exceptions; update status
1163 $function = '_getResponse' . $fileOpHandles[$index]->call;
1164 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1165 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1166 } catch ( CloudFilesException $e ) { // some other exception?
1167 $this->handleException( $e, $status,
1168 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1169 }
1170 $statuses[$index] = $status;
1171 }
1172
1173 return $statuses;
1174 }
1175
1176 /**
1177 * Set read/write permissions for a Swift container.
1178 *
1179 * $readGrps is a list of the possible criteria for a request to have
1180 * access to read a container. Each item is one of the following formats:
1181 * - account:user : Grants access if the request is by the given user
1182 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1183 * matches the expression and the request is not for a listing.
1184 * Setting this to '*' effectively makes a container public.
1185 * -".rlistings:<regex>": Grants access if the request is from a referrer host that
1186 * matches the expression and the request for a listing.
1187 *
1188 * $writeGrps is a list of the possible criteria for a request to have
1189 * access to write to a container. Each item is of the following format:
1190 * - account:user : Grants access if the request is by the given user
1191 *
1192 * @see http://swift.openstack.org/misc.html#acls
1193 *
1194 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1195 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1196 *
1197 * @param $contObj CF_Container Swift container
1198 * @param $readGrps Array List of read access routes
1199 * @param $writeGrps Array List of write access routes
1200 * @return Status
1201 */
1202 protected function setContainerAccess(
1203 CF_Container $contObj, array $readGrps, array $writeGrps
1204 ) {
1205 $creds = $contObj->cfs_auth->export_credentials();
1206
1207 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1208
1209 // Note: 10 second timeout consistent with php-cloudfiles
1210 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1211 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1212 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1213 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1214
1215 return $req->execute(); // should return 204
1216 }
1217
1218 /**
1219 * Purge the CDN cache of affected objects if CDN caching is enabled.
1220 * This is for Rackspace/Akamai CDNs.
1221 *
1222 * @param $objects Array List of CF_Object items
1223 * @return void
1224 */
1225 public function purgeCDNCache( array $objects ) {
1226 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1227 foreach ( $objects as $object ) {
1228 try {
1229 $object->purge_from_cdn();
1230 } catch ( CDNNotEnabledException $e ) {
1231 // CDN not enabled; nothing to see here
1232 } catch ( CloudFilesException $e ) {
1233 $this->handleException( $e, null, __METHOD__,
1234 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1235 }
1236 }
1237 }
1238 }
1239
1240 /**
1241 * Get an authenticated connection handle to the Swift proxy
1242 *
1243 * @return CF_Connection|bool False on failure
1244 * @throws CloudFilesException
1245 */
1246 protected function getConnection() {
1247 if ( $this->connException instanceof CloudFilesException ) {
1248 if ( ( time() - $this->connErrorTime ) < 60 ) {
1249 throw $this->connException; // failed last attempt; don't bother
1250 } else { // actually retry this time
1251 $this->connException = null;
1252 $this->connErrorTime = 0;
1253 }
1254 }
1255 // Session keys expire after a while, so we renew them periodically
1256 $reAuth = ( ( time() - $this->sessionStarted ) > $this->authTTL );
1257 // Authenticate with proxy and get a session key...
1258 if ( !$this->conn || $reAuth ) {
1259 $this->sessionStarted = 0;
1260 $this->connContainerCache->clear();
1261 $cacheKey = $this->getCredsCacheKey( $this->auth->username );
1262 $creds = $this->srvCache->get( $cacheKey ); // credentials
1263 if ( is_array( $creds ) ) { // cache hit
1264 $this->auth->load_cached_credentials(
1265 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1266 $this->sessionStarted = time() - ceil( $this->authTTL/2 ); // skew for worst case
1267 } else { // cache miss
1268 try {
1269 $this->auth->authenticate();
1270 $creds = $this->auth->export_credentials();
1271 $this->srvCache->add( $cacheKey, $creds, ceil( $this->authTTL/2 ) ); // cache
1272 $this->sessionStarted = time();
1273 } catch ( CloudFilesException $e ) {
1274 $this->connException = $e; // don't keep re-trying
1275 $this->connErrorTime = time();
1276 throw $e; // throw it back
1277 }
1278 }
1279 if ( $this->conn ) { // re-authorizing?
1280 $this->conn->close(); // close active cURL handles in CF_Http object
1281 }
1282 $this->conn = new CF_Connection( $this->auth );
1283 }
1284 return $this->conn;
1285 }
1286
1287 /**
1288 * Close the connection to the Swift proxy
1289 *
1290 * @return void
1291 */
1292 protected function closeConnection() {
1293 if ( $this->conn ) {
1294 $this->conn->close(); // close active cURL handles in CF_Http object
1295 $this->sessionStarted = 0;
1296 $this->connContainerCache->clear();
1297 }
1298 }
1299
1300 /**
1301 * Get the cache key for a container
1302 *
1303 * @param $username string
1304 * @return string
1305 */
1306 private function getCredsCacheKey( $username ) {
1307 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1308 }
1309
1310 /**
1311 * Get a Swift container object, possibly from process cache.
1312 * Use $reCache if the file count or byte count is needed.
1313 *
1314 * @param $container string Container name
1315 * @param $bypassCache bool Bypass all caches and load from Swift
1316 * @return CF_Container
1317 * @throws CloudFilesException
1318 */
1319 protected function getContainer( $container, $bypassCache = false ) {
1320 $conn = $this->getConnection(); // Swift proxy connection
1321 if ( $bypassCache ) { // purge cache
1322 $this->connContainerCache->clear( $container );
1323 } elseif ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1324 $this->primeContainerCache( array( $container ) ); // check persistent cache
1325 }
1326 if ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1327 $contObj = $conn->get_container( $container );
1328 // NoSuchContainerException not thrown: container must exist
1329 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache it
1330 if ( !$bypassCache ) {
1331 $this->setContainerCache( $container, // update persistent cache
1332 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1333 );
1334 }
1335 }
1336 return $this->connContainerCache->get( $container, 'obj' );
1337 }
1338
1339 /**
1340 * Create a Swift container
1341 *
1342 * @param $container string Container name
1343 * @return CF_Container
1344 * @throws CloudFilesException
1345 */
1346 protected function createContainer( $container ) {
1347 $conn = $this->getConnection(); // Swift proxy connection
1348 $contObj = $conn->create_container( $container );
1349 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache
1350 return $contObj;
1351 }
1352
1353 /**
1354 * Delete a Swift container
1355 *
1356 * @param $container string Container name
1357 * @return void
1358 * @throws CloudFilesException
1359 */
1360 protected function deleteContainer( $container ) {
1361 $conn = $this->getConnection(); // Swift proxy connection
1362 $this->connContainerCache->clear( $container ); // purge
1363 $conn->delete_container( $container );
1364 }
1365
1366 /**
1367 * @see FileBackendStore::doPrimeContainerCache()
1368 * @return void
1369 */
1370 protected function doPrimeContainerCache( array $containerInfo ) {
1371 try {
1372 $conn = $this->getConnection(); // Swift proxy connection
1373 foreach ( $containerInfo as $container => $info ) {
1374 $contObj = new CF_Container( $conn->cfs_auth, $conn->cfs_http,
1375 $container, $info['count'], $info['bytes'] );
1376 $this->connContainerCache->set( $container, 'obj', $contObj );
1377 }
1378 } catch ( CloudFilesException $e ) { // some other exception?
1379 $this->handleException( $e, null, __METHOD__, array() );
1380 }
1381 }
1382
1383 /**
1384 * Log an unexpected exception for this backend.
1385 * This also sets the Status object to have a fatal error.
1386 *
1387 * @param $e Exception
1388 * @param $status Status|null
1389 * @param $func string
1390 * @param $params Array
1391 * @return void
1392 */
1393 protected function handleException( Exception $e, $status, $func, array $params ) {
1394 if ( $status instanceof Status ) {
1395 if ( $e instanceof AuthenticationException ) {
1396 $status->fatal( 'backend-fail-connect', $this->name );
1397 } else {
1398 $status->fatal( 'backend-fail-internal', $this->name );
1399 }
1400 }
1401 if ( $e->getMessage() ) {
1402 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1403 }
1404 if ( $e instanceof InvalidResponseException ) { // possibly a stale token
1405 $this->srvCache->delete( $this->getCredsCacheKey( $this->auth->username ) );
1406 $this->closeConnection(); // force a re-connect and re-auth next time
1407 }
1408 wfDebugLog( 'SwiftBackend',
1409 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1410 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1411 );
1412 }
1413 }
1414
1415 /**
1416 * @see FileBackendStoreOpHandle
1417 */
1418 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1419 /** @var CF_Async_Op */
1420 public $cfOp;
1421 /** @var Array */
1422 public $affectedObjects = array();
1423
1424 public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
1425 $this->backend = $backend;
1426 $this->params = $params;
1427 $this->call = $call;
1428 $this->cfOp = $cfOp;
1429 }
1430 }
1431
1432 /**
1433 * SwiftFileBackend helper class to page through listings.
1434 * Swift also has a listing limit of 10,000 objects for sanity.
1435 * Do not use this class from places outside SwiftFileBackend.
1436 *
1437 * @ingroup FileBackend
1438 */
1439 abstract class SwiftFileBackendList implements Iterator {
1440 /** @var Array */
1441 protected $bufferIter = array();
1442 protected $bufferAfter = null; // string; list items *after* this path
1443 protected $pos = 0; // integer
1444 /** @var Array */
1445 protected $params = array();
1446
1447 /** @var SwiftFileBackend */
1448 protected $backend;
1449 protected $container; // string; container name
1450 protected $dir; // string; storage directory
1451 protected $suffixStart; // integer
1452
1453 const PAGE_SIZE = 9000; // file listing buffer size
1454
1455 /**
1456 * @param $backend SwiftFileBackend
1457 * @param $fullCont string Resolved container name
1458 * @param $dir string Resolved directory relative to container
1459 * @param $params Array
1460 */
1461 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1462 $this->backend = $backend;
1463 $this->container = $fullCont;
1464 $this->dir = $dir;
1465 if ( substr( $this->dir, -1 ) === '/' ) {
1466 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1467 }
1468 if ( $this->dir == '' ) { // whole container
1469 $this->suffixStart = 0;
1470 } else { // dir within container
1471 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1472 }
1473 $this->params = $params;
1474 }
1475
1476 /**
1477 * @see Iterator::key()
1478 * @return integer
1479 */
1480 public function key() {
1481 return $this->pos;
1482 }
1483
1484 /**
1485 * @see Iterator::next()
1486 * @return void
1487 */
1488 public function next() {
1489 // Advance to the next file in the page
1490 next( $this->bufferIter );
1491 ++$this->pos;
1492 // Check if there are no files left in this page and
1493 // advance to the next page if this page was not empty.
1494 if ( !$this->valid() && count( $this->bufferIter ) ) {
1495 $this->bufferIter = $this->pageFromList(
1496 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1497 ); // updates $this->bufferAfter
1498 }
1499 }
1500
1501 /**
1502 * @see Iterator::rewind()
1503 * @return void
1504 */
1505 public function rewind() {
1506 $this->pos = 0;
1507 $this->bufferAfter = null;
1508 $this->bufferIter = $this->pageFromList(
1509 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1510 ); // updates $this->bufferAfter
1511 }
1512
1513 /**
1514 * @see Iterator::valid()
1515 * @return bool
1516 */
1517 public function valid() {
1518 if ( $this->bufferIter === null ) {
1519 return false; // some failure?
1520 } else {
1521 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1522 }
1523 }
1524
1525 /**
1526 * Get the given list portion (page)
1527 *
1528 * @param $container string Resolved container name
1529 * @param $dir string Resolved path relative to container
1530 * @param $after string|null
1531 * @param $limit integer
1532 * @param $params Array
1533 * @return Traversable|Array|null Returns null on failure
1534 */
1535 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1536 }
1537
1538 /**
1539 * Iterator for listing directories
1540 */
1541 class SwiftFileBackendDirList extends SwiftFileBackendList {
1542 /**
1543 * @see Iterator::current()
1544 * @return string|bool String (relative path) or false
1545 */
1546 public function current() {
1547 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1548 }
1549
1550 /**
1551 * @see SwiftFileBackendList::pageFromList()
1552 * @return Array|null
1553 */
1554 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1555 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1556 }
1557 }
1558
1559 /**
1560 * Iterator for listing regular files
1561 */
1562 class SwiftFileBackendFileList extends SwiftFileBackendList {
1563 /**
1564 * @see Iterator::current()
1565 * @return string|bool String (relative path) or false
1566 */
1567 public function current() {
1568 return substr( current( $this->bufferIter ), $this->suffixStart );
1569 }
1570
1571 /**
1572 * @see SwiftFileBackendList::pageFromList()
1573 * @return Array|null
1574 */
1575 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1576 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1577 }
1578 }