Merge "[FileBackend] Use the new CloudFiles metadata functions."
[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 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
404 } catch ( CloudFilesException $e ) { // some other exception?
405 $this->handleException( $e, $status, __METHOD__, $params );
406 }
407
408 return $status;
409 }
410
411 /**
412 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
413 */
414 protected function _getResponseCopy( CF_Async_Op $cfOp, Status $status, array $params ) {
415 try {
416 $cfOp->getLastResponse();
417 } catch ( NoSuchObjectException $e ) { // source object does not exist
418 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
419 }
420 }
421
422 /**
423 * @see FileBackendStore::doMoveInternal()
424 * @return Status
425 */
426 protected function doMoveInternal( array $params ) {
427 $status = Status::newGood();
428
429 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
430 if ( $srcRel === null ) {
431 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
432 return $status;
433 }
434
435 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
436 if ( $dstRel === null ) {
437 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
438 return $status;
439 }
440
441 // (a) Check the source/destination containers and destination object
442 try {
443 $sContObj = $this->getContainer( $srcCont );
444 $dContObj = $this->getContainer( $dstCont );
445 } catch ( NoSuchContainerException $e ) {
446 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
447 return $status;
448 } catch ( CloudFilesException $e ) { // some other exception?
449 $this->handleException( $e, $status, __METHOD__, $params );
450 return $status;
451 }
452
453 // (b) Actually move the file to the destination
454 try {
455 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
456 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
457 $hdrs = array(); // source file headers to override with new values
458 if ( isset( $params['disposition'] ) ) {
459 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
460 }
461 if ( !empty( $params['async'] ) ) { // deferred
462 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
463 $status->value = new SwiftFileOpHandle( $this, $params, 'Move', $op );
464 $status->value->affectedObjects[] = $srcObj;
465 $status->value->affectedObjects[] = $dstObj;
466 } else { // actually write the object in Swift
467 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
468 $this->purgeCDNCache( array( $srcObj ) );
469 $this->purgeCDNCache( array( $dstObj ) );
470 }
471 } catch ( CDNNotEnabledException $e ) {
472 // CDN not enabled; nothing to see here
473 } catch ( NoSuchObjectException $e ) { // source object does not exist
474 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
475 } catch ( CloudFilesException $e ) { // some other exception?
476 $this->handleException( $e, $status, __METHOD__, $params );
477 }
478
479 return $status;
480 }
481
482 /**
483 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
484 */
485 protected function _getResponseMove( CF_Async_Op $cfOp, Status $status, array $params ) {
486 try {
487 $cfOp->getLastResponse();
488 } catch ( NoSuchObjectException $e ) { // source object does not exist
489 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
490 }
491 }
492
493 /**
494 * @see FileBackendStore::doDeleteInternal()
495 * @return Status
496 */
497 protected function doDeleteInternal( array $params ) {
498 $status = Status::newGood();
499
500 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
501 if ( $srcRel === null ) {
502 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
503 return $status;
504 }
505
506 try {
507 $sContObj = $this->getContainer( $srcCont );
508 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
509 if ( !empty( $params['async'] ) ) { // deferred
510 $op = $sContObj->delete_object_async( $srcRel );
511 $status->value = new SwiftFileOpHandle( $this, $params, 'Delete', $op );
512 $status->value->affectedObjects[] = $srcObj;
513 } else { // actually write the object in Swift
514 $sContObj->delete_object( $srcRel );
515 $this->purgeCDNCache( array( $srcObj ) );
516 }
517 } catch ( CDNNotEnabledException $e ) {
518 // CDN not enabled; nothing to see here
519 } catch ( NoSuchContainerException $e ) {
520 $status->fatal( 'backend-fail-delete', $params['src'] );
521 } catch ( NoSuchObjectException $e ) {
522 if ( empty( $params['ignoreMissingSource'] ) ) {
523 $status->fatal( 'backend-fail-delete', $params['src'] );
524 }
525 } catch ( CloudFilesException $e ) { // some other exception?
526 $this->handleException( $e, $status, __METHOD__, $params );
527 }
528
529 return $status;
530 }
531
532 /**
533 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
534 */
535 protected function _getResponseDelete( CF_Async_Op $cfOp, Status $status, array $params ) {
536 try {
537 $cfOp->getLastResponse();
538 } catch ( NoSuchContainerException $e ) {
539 $status->fatal( 'backend-fail-delete', $params['src'] );
540 } catch ( NoSuchObjectException $e ) {
541 if ( empty( $params['ignoreMissingSource'] ) ) {
542 $status->fatal( 'backend-fail-delete', $params['src'] );
543 }
544 }
545 }
546
547 /**
548 * @see FileBackendStore::doPrepareInternal()
549 * @return Status
550 */
551 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
552 $status = Status::newGood();
553
554 // (a) Check if container already exists
555 try {
556 $contObj = $this->getContainer( $fullCont );
557 // NoSuchContainerException not thrown: container must exist
558 return $status; // already exists
559 } catch ( NoSuchContainerException $e ) {
560 // NoSuchContainerException thrown: container does not exist
561 } catch ( CloudFilesException $e ) { // some other exception?
562 $this->handleException( $e, $status, __METHOD__, $params );
563 return $status;
564 }
565
566 // (b) Create container as needed
567 try {
568 $contObj = $this->createContainer( $fullCont );
569 if ( !empty( $params['noAccess'] ) ) {
570 // Make container private to end-users...
571 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
572 } else {
573 // Make container public to end-users...
574 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
575 }
576 if ( $this->swiftUseCDN ) { // Rackspace style CDN
577 $contObj->make_public( $this->swiftCDNExpiry );
578 }
579 } catch ( CDNNotEnabledException $e ) {
580 // CDN not enabled; nothing to see here
581 } catch ( CloudFilesException $e ) { // some other exception?
582 $this->handleException( $e, $status, __METHOD__, $params );
583 return $status;
584 }
585
586 return $status;
587 }
588
589 /**
590 * @see FileBackendStore::doSecureInternal()
591 * @return Status
592 */
593 protected function doSecureInternal( $fullCont, $dir, array $params ) {
594 $status = Status::newGood();
595 if ( empty( $params['noAccess'] ) ) {
596 return $status; // nothing to do
597 }
598
599 // Restrict container from end-users...
600 try {
601 // doPrepareInternal() should have been called,
602 // so the Swift container should already exist...
603 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
604 // NoSuchContainerException not thrown: container must exist
605
606 // Make container private to end-users...
607 $status->merge( $this->setContainerAccess(
608 $contObj,
609 array( $this->auth->username ), // read
610 array( $this->auth->username ) // write
611 ) );
612 if ( $this->swiftUseCDN && $contObj->is_public() ) { // Rackspace style CDN
613 $contObj->make_private();
614 }
615 } catch ( CDNNotEnabledException $e ) {
616 // CDN not enabled; nothing to see here
617 } catch ( CloudFilesException $e ) { // some other exception?
618 $this->handleException( $e, $status, __METHOD__, $params );
619 }
620
621 return $status;
622 }
623
624 /**
625 * @see FileBackendStore::doPublishInternal()
626 * @return Status
627 */
628 protected function doPublishInternal( $fullCont, $dir, array $params ) {
629 $status = Status::newGood();
630
631 // Unrestrict container from end-users...
632 try {
633 // doPrepareInternal() should have been called,
634 // so the Swift container should already exist...
635 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
636 // NoSuchContainerException not thrown: container must exist
637
638 // Make container public to end-users...
639 if ( $this->swiftAnonUser != '' ) {
640 $status->merge( $this->setContainerAccess(
641 $contObj,
642 array( $this->auth->username, $this->swiftAnonUser ), // read
643 array( $this->auth->username, $this->swiftAnonUser ) // write
644 ) );
645 } else {
646 $status->merge( $this->setContainerAccess(
647 $contObj,
648 array( $this->auth->username, '.r:*' ), // read
649 array( $this->auth->username ) // write
650 ) );
651 }
652 if ( $this->swiftUseCDN && !$contObj->is_public() ) { // Rackspace style CDN
653 $contObj->make_public();
654 }
655 } catch ( CDNNotEnabledException $e ) {
656 // CDN not enabled; nothing to see here
657 } catch ( CloudFilesException $e ) { // some other exception?
658 $this->handleException( $e, $status, __METHOD__, $params );
659 }
660
661 return $status;
662 }
663
664 /**
665 * @see FileBackendStore::doCleanInternal()
666 * @return Status
667 */
668 protected function doCleanInternal( $fullCont, $dir, array $params ) {
669 $status = Status::newGood();
670
671 // Only containers themselves can be removed, all else is virtual
672 if ( $dir != '' ) {
673 return $status; // nothing to do
674 }
675
676 // (a) Check the container
677 try {
678 $contObj = $this->getContainer( $fullCont, true );
679 } catch ( NoSuchContainerException $e ) {
680 return $status; // ok, nothing to do
681 } catch ( CloudFilesException $e ) { // some other exception?
682 $this->handleException( $e, $status, __METHOD__, $params );
683 return $status;
684 }
685
686 // (b) Delete the container if empty
687 if ( $contObj->object_count == 0 ) {
688 try {
689 $this->deleteContainer( $fullCont );
690 } catch ( NoSuchContainerException $e ) {
691 return $status; // race?
692 } catch ( NonEmptyContainerException $e ) {
693 return $status; // race? consistency delay?
694 } catch ( CloudFilesException $e ) { // some other exception?
695 $this->handleException( $e, $status, __METHOD__, $params );
696 return $status;
697 }
698 }
699
700 return $status;
701 }
702
703 /**
704 * @see FileBackendStore::doFileExists()
705 * @return array|bool|null
706 */
707 protected function doGetFileStat( array $params ) {
708 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
709 if ( $srcRel === null ) {
710 return false; // invalid storage path
711 }
712
713 $stat = false;
714 try {
715 $contObj = $this->getContainer( $srcCont );
716 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
717 $this->addMissingMetadata( $srcObj, $params['src'] );
718 $stat = array(
719 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
720 'mtime' => wfTimestamp( TS_MW, $srcObj->last_modified ),
721 'size' => (int)$srcObj->content_length,
722 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
723 );
724 } catch ( NoSuchContainerException $e ) {
725 } catch ( NoSuchObjectException $e ) {
726 } catch ( CloudFilesException $e ) { // some other exception?
727 $stat = null;
728 $this->handleException( $e, null, __METHOD__, $params );
729 }
730
731 return $stat;
732 }
733
734 /**
735 * Fill in any missing object metadata and save it to Swift
736 *
737 * @param $obj CF_Object
738 * @param $path string Storage path to object
739 * @return bool Success
740 * @throws Exception cloudfiles exceptions
741 */
742 protected function addMissingMetadata( CF_Object $obj, $path ) {
743 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
744 return true; // nothing to do
745 }
746 wfProfileIn( __METHOD__ );
747 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING );
748 $status = Status::newGood();
749 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
750 if ( $status->isOK() ) {
751 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
752 if ( $tmpFile ) {
753 $hash = $tmpFile->getSha1Base36();
754 if ( $hash !== false ) {
755 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
756 $obj->sync_metadata(); // save to Swift
757 wfProfileOut( __METHOD__ );
758 return true; // success
759 }
760 }
761 }
762 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
763 wfProfileOut( __METHOD__ );
764 return false; // failed
765 }
766
767 /**
768 * @see FileBackendStore::doGetFileContentsMulti()
769 * @return Array
770 */
771 protected function doGetFileContentsMulti( array $params ) {
772 $contents = array();
773
774 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
775 // Blindly create tmp files and stream to them, catching any exception if the file does
776 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
777 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
778 $cfOps = array(); // (path => CF_Async_Op)
779
780 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
781 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
782 if ( $srcRel === null ) {
783 $contents[$path] = false;
784 continue;
785 }
786 $data = false;
787 try {
788 $sContObj = $this->getContainer( $srcCont );
789 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
790 // Get source file extension
791 $ext = FileBackend::extensionFromPath( $path );
792 // Create a new temporary memory file...
793 $handle = fopen( 'php://temp', 'wb' );
794 if ( $handle ) {
795 $headers = $this->headersFromParams( $params );
796 if ( count( $pathBatch ) > 1 ) {
797 $cfOps[$path] = $obj->stream_async( $handle, $headers );
798 $cfOps[$path]->_file_handle = $handle; // close this later
799 } else {
800 $obj->stream( $handle, $headers );
801 rewind( $handle ); // start from the beginning
802 $data = stream_get_contents( $handle );
803 fclose( $handle );
804 }
805 } else {
806 $data = false;
807 }
808 } catch ( NoSuchContainerException $e ) {
809 $data = false;
810 } catch ( NoSuchObjectException $e ) {
811 $data = false;
812 } catch ( CloudFilesException $e ) { // some other exception?
813 $data = false;
814 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
815 }
816 $contents[$path] = $data;
817 }
818
819 $batch = new CF_Async_Op_Batch( $cfOps );
820 $cfOps = $batch->execute();
821 foreach ( $cfOps as $path => $cfOp ) {
822 try {
823 $cfOp->getLastResponse();
824 rewind( $cfOp->_file_handle ); // start from the beginning
825 $contents[$path] = stream_get_contents( $cfOp->_file_handle );
826 } catch ( NoSuchContainerException $e ) {
827 $contents[$path] = false;
828 } catch ( NoSuchObjectException $e ) {
829 $contents[$path] = false;
830 } catch ( CloudFilesException $e ) { // some other exception?
831 $contents[$path] = false;
832 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
833 }
834 fclose( $cfOp->_file_handle ); // close open handle
835 }
836 }
837
838 return $contents;
839 }
840
841 /**
842 * @see FileBackendStore::doDirectoryExists()
843 * @return bool|null
844 */
845 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
846 try {
847 $container = $this->getContainer( $fullCont );
848 $prefix = ( $dir == '' ) ? null : "{$dir}/";
849 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
850 } catch ( NoSuchContainerException $e ) {
851 return false;
852 } catch ( CloudFilesException $e ) { // some other exception?
853 $this->handleException( $e, null, __METHOD__,
854 array( 'cont' => $fullCont, 'dir' => $dir ) );
855 }
856
857 return null; // error
858 }
859
860 /**
861 * @see FileBackendStore::getDirectoryListInternal()
862 * @return SwiftFileBackendDirList
863 */
864 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
865 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
866 }
867
868 /**
869 * @see FileBackendStore::getFileListInternal()
870 * @return SwiftFileBackendFileList
871 */
872 public function getFileListInternal( $fullCont, $dir, array $params ) {
873 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
874 }
875
876 /**
877 * Do not call this function outside of SwiftFileBackendFileList
878 *
879 * @param $fullCont string Resolved container name
880 * @param $dir string Resolved storage directory with no trailing slash
881 * @param $after string|null Storage path of file to list items after
882 * @param $limit integer Max number of items to list
883 * @param $params Array Includes flag for 'topOnly'
884 * @return Array List of relative paths of dirs directly under $dir
885 */
886 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
887 $dirs = array();
888 if ( $after === INF ) {
889 return $dirs; // nothing more
890 }
891 wfProfileIn( __METHOD__ . '-' . $this->name );
892
893 try {
894 $container = $this->getContainer( $fullCont );
895 $prefix = ( $dir == '' ) ? null : "{$dir}/";
896 // Non-recursive: only list dirs right under $dir
897 if ( !empty( $params['topOnly'] ) ) {
898 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
899 foreach ( $objects as $object ) { // files and dirs
900 if ( substr( $object, -1 ) === '/' ) {
901 $dirs[] = $object; // directories end in '/'
902 }
903 }
904 // Recursive: list all dirs under $dir and its subdirs
905 } else {
906 // Get directory from last item of prior page
907 $lastDir = $this->getParentDir( $after ); // must be first page
908 $objects = $container->list_objects( $limit, $after, $prefix );
909 foreach ( $objects as $object ) { // files
910 $objectDir = $this->getParentDir( $object ); // directory of object
911 if ( $objectDir !== false ) { // file has a parent dir
912 // Swift stores paths in UTF-8, using binary sorting.
913 // See function "create_container_table" in common/db.py.
914 // If a directory is not "greater" than the last one,
915 // then it was already listed by the calling iterator.
916 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
917 $pDir = $objectDir;
918 do { // add dir and all its parent dirs
919 $dirs[] = "{$pDir}/";
920 $pDir = $this->getParentDir( $pDir );
921 } while ( $pDir !== false // sanity
922 && strcmp( $pDir, $lastDir ) > 0 // not done already
923 && strlen( $pDir ) > strlen( $dir ) // within $dir
924 );
925 }
926 $lastDir = $objectDir;
927 }
928 }
929 }
930 if ( count( $objects ) < $limit ) {
931 $after = INF; // avoid a second RTT
932 } else {
933 $after = end( $objects ); // update last item
934 }
935 } catch ( NoSuchContainerException $e ) {
936 } catch ( CloudFilesException $e ) { // some other exception?
937 $this->handleException( $e, null, __METHOD__,
938 array( 'cont' => $fullCont, 'dir' => $dir ) );
939 }
940
941 wfProfileOut( __METHOD__ . '-' . $this->name );
942 return $dirs;
943 }
944
945 protected function getParentDir( $path ) {
946 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
947 }
948
949 /**
950 * Do not call this function outside of SwiftFileBackendFileList
951 *
952 * @param $fullCont string Resolved container name
953 * @param $dir string Resolved storage directory with no trailing slash
954 * @param $after string|null Storage path of file to list items after
955 * @param $limit integer Max number of items to list
956 * @param $params Array Includes flag for 'topOnly'
957 * @return Array List of relative paths of files under $dir
958 */
959 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
960 $files = array();
961 if ( $after === INF ) {
962 return $files; // nothing more
963 }
964 wfProfileIn( __METHOD__ . '-' . $this->name );
965
966 try {
967 $container = $this->getContainer( $fullCont );
968 $prefix = ( $dir == '' ) ? null : "{$dir}/";
969 // Non-recursive: only list files right under $dir
970 if ( !empty( $params['topOnly'] ) ) { // files and dirs
971 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
972 foreach ( $objects as $object ) {
973 if ( substr( $object, -1 ) !== '/' ) {
974 $files[] = $object; // directories end in '/'
975 }
976 }
977 // Recursive: list all files under $dir and its subdirs
978 } else { // files
979 $objects = $container->list_objects( $limit, $after, $prefix );
980 $files = $objects;
981 }
982 if ( count( $objects ) < $limit ) {
983 $after = INF; // avoid a second RTT
984 } else {
985 $after = end( $objects ); // update last item
986 }
987 } catch ( NoSuchContainerException $e ) {
988 } catch ( CloudFilesException $e ) { // some other exception?
989 $this->handleException( $e, null, __METHOD__,
990 array( 'cont' => $fullCont, 'dir' => $dir ) );
991 }
992
993 wfProfileOut( __METHOD__ . '-' . $this->name );
994 return $files;
995 }
996
997 /**
998 * @see FileBackendStore::doGetFileSha1base36()
999 * @return bool
1000 */
1001 protected function doGetFileSha1base36( array $params ) {
1002 $stat = $this->getFileStat( $params );
1003 if ( $stat ) {
1004 return $stat['sha1'];
1005 } else {
1006 return false;
1007 }
1008 }
1009
1010 /**
1011 * @see FileBackendStore::doStreamFile()
1012 * @return Status
1013 */
1014 protected function doStreamFile( array $params ) {
1015 $status = Status::newGood();
1016
1017 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1018 if ( $srcRel === null ) {
1019 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1020 }
1021
1022 try {
1023 $cont = $this->getContainer( $srcCont );
1024 } catch ( NoSuchContainerException $e ) {
1025 $status->fatal( 'backend-fail-stream', $params['src'] );
1026 return $status;
1027 } catch ( CloudFilesException $e ) { // some other exception?
1028 $this->handleException( $e, $status, __METHOD__, $params );
1029 return $status;
1030 }
1031
1032 try {
1033 $output = fopen( 'php://output', 'wb' );
1034 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1035 $obj->stream( $output, $this->headersFromParams( $params ) );
1036 } catch ( NoSuchObjectException $e ) {
1037 $status->fatal( 'backend-fail-stream', $params['src'] );
1038 } catch ( CloudFilesException $e ) { // some other exception?
1039 $this->handleException( $e, $status, __METHOD__, $params );
1040 }
1041
1042 return $status;
1043 }
1044
1045 /**
1046 * @see FileBackendStore::doGetLocalCopyMulti()
1047 * @return null|TempFSFile
1048 */
1049 protected function doGetLocalCopyMulti( array $params ) {
1050 $tmpFiles = array();
1051
1052 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1053 // Blindly create tmp files and stream to them, catching any exception if the file does
1054 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1055 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1056 $cfOps = array(); // (path => CF_Async_Op)
1057
1058 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1059 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1060 if ( $srcRel === null ) {
1061 $tmpFiles[$path] = null;
1062 continue;
1063 }
1064 $tmpFile = null;
1065 try {
1066 $sContObj = $this->getContainer( $srcCont );
1067 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1068 // Get source file extension
1069 $ext = FileBackend::extensionFromPath( $path );
1070 // Create a new temporary file...
1071 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1072 if ( $tmpFile ) {
1073 $handle = fopen( $tmpFile->getPath(), 'wb' );
1074 if ( $handle ) {
1075 $headers = $this->headersFromParams( $params );
1076 if ( count( $pathBatch ) > 1 ) {
1077 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1078 $cfOps[$path]->_file_handle = $handle; // close this later
1079 } else {
1080 $obj->stream( $handle, $headers );
1081 fclose( $handle );
1082 }
1083 } else {
1084 $tmpFile = null;
1085 }
1086 }
1087 } catch ( NoSuchContainerException $e ) {
1088 $tmpFile = null;
1089 } catch ( NoSuchObjectException $e ) {
1090 $tmpFile = null;
1091 } catch ( CloudFilesException $e ) { // some other exception?
1092 $tmpFile = null;
1093 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1094 }
1095 $tmpFiles[$path] = $tmpFile;
1096 }
1097
1098 $batch = new CF_Async_Op_Batch( $cfOps );
1099 $cfOps = $batch->execute();
1100 foreach ( $cfOps as $path => $cfOp ) {
1101 try {
1102 $cfOp->getLastResponse();
1103 } catch ( NoSuchContainerException $e ) {
1104 $tmpFiles[$path] = null;
1105 } catch ( NoSuchObjectException $e ) {
1106 $tmpFiles[$path] = null;
1107 } catch ( CloudFilesException $e ) { // some other exception?
1108 $tmpFiles[$path] = null;
1109 $this->handleException( $e, null, __METHOD__, array( 'src' => $path ) + $ep );
1110 }
1111 fclose( $cfOp->_file_handle ); // close open handle
1112 }
1113 }
1114
1115 return $tmpFiles;
1116 }
1117
1118 /**
1119 * @see FileBackendStore::directoriesAreVirtual()
1120 * @return bool
1121 */
1122 protected function directoriesAreVirtual() {
1123 return true;
1124 }
1125
1126 /**
1127 * Get headers to send to Swift when reading a file based
1128 * on a FileBackend params array, e.g. that of getLocalCopy().
1129 * $params is currently only checked for a 'latest' flag.
1130 *
1131 * @param $params Array
1132 * @return Array
1133 */
1134 protected function headersFromParams( array $params ) {
1135 $hdrs = array();
1136 if ( !empty( $params['latest'] ) ) {
1137 $hdrs[] = 'X-Newest: true';
1138 }
1139 return $hdrs;
1140 }
1141
1142 /**
1143 * @see FileBackendStore::doExecuteOpHandlesInternal()
1144 * @return Array List of corresponding Status objects
1145 */
1146 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1147 $statuses = array();
1148
1149 $cfOps = array(); // list of CF_Async_Op objects
1150 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1151 $cfOps[$index] = $fileOpHandle->cfOp;
1152 }
1153 $batch = new CF_Async_Op_Batch( $cfOps );
1154
1155 $cfOps = $batch->execute();
1156 foreach ( $cfOps as $index => $cfOp ) {
1157 $status = Status::newGood();
1158 try { // catch exceptions; update status
1159 $function = '_getResponse' . $fileOpHandles[$index]->call;
1160 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1161 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1162 } catch ( CloudFilesException $e ) { // some other exception?
1163 $this->handleException( $e, $status,
1164 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1165 }
1166 $statuses[$index] = $status;
1167 }
1168
1169 return $statuses;
1170 }
1171
1172 /**
1173 * Set read/write permissions for a Swift container.
1174 *
1175 * $readGrps is a list of the possible criteria for a request to have
1176 * access to read a container. Each item is one of the following formats:
1177 * - account:user : Grants access if the request is by the given user
1178 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1179 * matches the expression and the request is not for a listing.
1180 * Setting this to '*' effectively makes a container public.
1181 * -".rlistings:<regex>": Grants access if the request is from a referrer host that
1182 * matches the expression and the request for a listing.
1183 *
1184 * $writeGrps is a list of the possible criteria for a request to have
1185 * access to write to a container. Each item is of the following format:
1186 * - account:user : Grants access if the request is by the given user
1187 *
1188 * @see http://swift.openstack.org/misc.html#acls
1189 *
1190 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1191 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1192 *
1193 * @param $contObj CF_Container Swift container
1194 * @param $readGrps Array List of read access routes
1195 * @param $writeGrps Array List of write access routes
1196 * @return Status
1197 */
1198 protected function setContainerAccess(
1199 CF_Container $contObj, array $readGrps, array $writeGrps
1200 ) {
1201 $creds = $contObj->cfs_auth->export_credentials();
1202
1203 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1204
1205 // Note: 10 second timeout consistent with php-cloudfiles
1206 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1207 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1208 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1209 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1210
1211 return $req->execute(); // should return 204
1212 }
1213
1214 /**
1215 * Purge the CDN cache of affected objects if CDN caching is enabled.
1216 * This is for Rackspace/Akamai CDNs.
1217 *
1218 * @param $objects Array List of CF_Object items
1219 * @return void
1220 */
1221 public function purgeCDNCache( array $objects ) {
1222 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1223 foreach ( $objects as $object ) {
1224 try {
1225 $object->purge_from_cdn();
1226 } catch ( CDNNotEnabledException $e ) {
1227 // CDN not enabled; nothing to see here
1228 } catch ( CloudFilesException $e ) {
1229 $this->handleException( $e, null, __METHOD__,
1230 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1231 }
1232 }
1233 }
1234 }
1235
1236 /**
1237 * Get an authenticated connection handle to the Swift proxy
1238 *
1239 * @return CF_Connection|bool False on failure
1240 * @throws CloudFilesException
1241 */
1242 protected function getConnection() {
1243 if ( $this->connException instanceof CloudFilesException ) {
1244 if ( ( time() - $this->connErrorTime ) < 60 ) {
1245 throw $this->connException; // failed last attempt; don't bother
1246 } else { // actually retry this time
1247 $this->connException = null;
1248 $this->connErrorTime = 0;
1249 }
1250 }
1251 // Session keys expire after a while, so we renew them periodically
1252 $reAuth = ( ( time() - $this->sessionStarted ) > $this->authTTL );
1253 // Authenticate with proxy and get a session key...
1254 if ( !$this->conn || $reAuth ) {
1255 $this->sessionStarted = 0;
1256 $this->connContainerCache->clear();
1257 $cacheKey = $this->getCredsCacheKey( $this->auth->username );
1258 $creds = $this->srvCache->get( $cacheKey ); // credentials
1259 if ( is_array( $creds ) ) { // cache hit
1260 $this->auth->load_cached_credentials(
1261 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1262 $this->sessionStarted = time() - ceil( $this->authTTL/2 ); // skew for worst case
1263 } else { // cache miss
1264 try {
1265 $this->auth->authenticate();
1266 $creds = $this->auth->export_credentials();
1267 $this->srvCache->add( $cacheKey, $creds, ceil( $this->authTTL/2 ) ); // cache
1268 $this->sessionStarted = time();
1269 } catch ( CloudFilesException $e ) {
1270 $this->connException = $e; // don't keep re-trying
1271 $this->connErrorTime = time();
1272 throw $e; // throw it back
1273 }
1274 }
1275 if ( $this->conn ) { // re-authorizing?
1276 $this->conn->close(); // close active cURL handles in CF_Http object
1277 }
1278 $this->conn = new CF_Connection( $this->auth );
1279 }
1280 return $this->conn;
1281 }
1282
1283 /**
1284 * Close the connection to the Swift proxy
1285 *
1286 * @return void
1287 */
1288 protected function closeConnection() {
1289 if ( $this->conn ) {
1290 $this->conn->close(); // close active cURL handles in CF_Http object
1291 $this->sessionStarted = 0;
1292 $this->connContainerCache->clear();
1293 }
1294 }
1295
1296 /**
1297 * Get the cache key for a container
1298 *
1299 * @param $username string
1300 * @return string
1301 */
1302 private function getCredsCacheKey( $username ) {
1303 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1304 }
1305
1306 /**
1307 * Get a Swift container object, possibly from process cache.
1308 * Use $reCache if the file count or byte count is needed.
1309 *
1310 * @param $container string Container name
1311 * @param $bypassCache bool Bypass all caches and load from Swift
1312 * @return CF_Container
1313 * @throws CloudFilesException
1314 */
1315 protected function getContainer( $container, $bypassCache = false ) {
1316 $conn = $this->getConnection(); // Swift proxy connection
1317 if ( $bypassCache ) { // purge cache
1318 $this->connContainerCache->clear( $container );
1319 } elseif ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1320 $this->primeContainerCache( array( $container ) ); // check persistent cache
1321 }
1322 if ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1323 $contObj = $conn->get_container( $container );
1324 // NoSuchContainerException not thrown: container must exist
1325 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache it
1326 if ( !$bypassCache ) {
1327 $this->setContainerCache( $container, // update persistent cache
1328 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1329 );
1330 }
1331 }
1332 return $this->connContainerCache->get( $container, 'obj' );
1333 }
1334
1335 /**
1336 * Create a Swift container
1337 *
1338 * @param $container string Container name
1339 * @return CF_Container
1340 * @throws CloudFilesException
1341 */
1342 protected function createContainer( $container ) {
1343 $conn = $this->getConnection(); // Swift proxy connection
1344 $contObj = $conn->create_container( $container );
1345 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache
1346 return $contObj;
1347 }
1348
1349 /**
1350 * Delete a Swift container
1351 *
1352 * @param $container string Container name
1353 * @return void
1354 * @throws CloudFilesException
1355 */
1356 protected function deleteContainer( $container ) {
1357 $conn = $this->getConnection(); // Swift proxy connection
1358 $this->connContainerCache->clear( $container ); // purge
1359 $conn->delete_container( $container );
1360 }
1361
1362 /**
1363 * @see FileBackendStore::doPrimeContainerCache()
1364 * @return void
1365 */
1366 protected function doPrimeContainerCache( array $containerInfo ) {
1367 try {
1368 $conn = $this->getConnection(); // Swift proxy connection
1369 foreach ( $containerInfo as $container => $info ) {
1370 $contObj = new CF_Container( $conn->cfs_auth, $conn->cfs_http,
1371 $container, $info['count'], $info['bytes'] );
1372 $this->connContainerCache->set( $container, 'obj', $contObj );
1373 }
1374 } catch ( CloudFilesException $e ) { // some other exception?
1375 $this->handleException( $e, null, __METHOD__, array() );
1376 }
1377 }
1378
1379 /**
1380 * Log an unexpected exception for this backend.
1381 * This also sets the Status object to have a fatal error.
1382 *
1383 * @param $e Exception
1384 * @param $status Status|null
1385 * @param $func string
1386 * @param $params Array
1387 * @return void
1388 */
1389 protected function handleException( Exception $e, $status, $func, array $params ) {
1390 if ( $status instanceof Status ) {
1391 if ( $e instanceof AuthenticationException ) {
1392 $status->fatal( 'backend-fail-connect', $this->name );
1393 } else {
1394 $status->fatal( 'backend-fail-internal', $this->name );
1395 }
1396 }
1397 if ( $e->getMessage() ) {
1398 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1399 }
1400 if ( $e instanceof InvalidResponseException ) { // possibly a stale token
1401 $this->srvCache->delete( $this->getCredsCacheKey( $this->auth->username ) );
1402 $this->closeConnection(); // force a re-connect and re-auth next time
1403 }
1404 wfDebugLog( 'SwiftBackend',
1405 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1406 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1407 );
1408 }
1409 }
1410
1411 /**
1412 * @see FileBackendStoreOpHandle
1413 */
1414 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1415 /** @var CF_Async_Op */
1416 public $cfOp;
1417 /** @var Array */
1418 public $affectedObjects = array();
1419
1420 public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
1421 $this->backend = $backend;
1422 $this->params = $params;
1423 $this->call = $call;
1424 $this->cfOp = $cfOp;
1425 }
1426 }
1427
1428 /**
1429 * SwiftFileBackend helper class to page through listings.
1430 * Swift also has a listing limit of 10,000 objects for sanity.
1431 * Do not use this class from places outside SwiftFileBackend.
1432 *
1433 * @ingroup FileBackend
1434 */
1435 abstract class SwiftFileBackendList implements Iterator {
1436 /** @var Array */
1437 protected $bufferIter = array();
1438 protected $bufferAfter = null; // string; list items *after* this path
1439 protected $pos = 0; // integer
1440 /** @var Array */
1441 protected $params = array();
1442
1443 /** @var SwiftFileBackend */
1444 protected $backend;
1445 protected $container; // string; container name
1446 protected $dir; // string; storage directory
1447 protected $suffixStart; // integer
1448
1449 const PAGE_SIZE = 9000; // file listing buffer size
1450
1451 /**
1452 * @param $backend SwiftFileBackend
1453 * @param $fullCont string Resolved container name
1454 * @param $dir string Resolved directory relative to container
1455 * @param $params Array
1456 */
1457 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1458 $this->backend = $backend;
1459 $this->container = $fullCont;
1460 $this->dir = $dir;
1461 if ( substr( $this->dir, -1 ) === '/' ) {
1462 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1463 }
1464 if ( $this->dir == '' ) { // whole container
1465 $this->suffixStart = 0;
1466 } else { // dir within container
1467 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1468 }
1469 $this->params = $params;
1470 }
1471
1472 /**
1473 * @see Iterator::key()
1474 * @return integer
1475 */
1476 public function key() {
1477 return $this->pos;
1478 }
1479
1480 /**
1481 * @see Iterator::next()
1482 * @return void
1483 */
1484 public function next() {
1485 // Advance to the next file in the page
1486 next( $this->bufferIter );
1487 ++$this->pos;
1488 // Check if there are no files left in this page and
1489 // advance to the next page if this page was not empty.
1490 if ( !$this->valid() && count( $this->bufferIter ) ) {
1491 $this->bufferIter = $this->pageFromList(
1492 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1493 ); // updates $this->bufferAfter
1494 }
1495 }
1496
1497 /**
1498 * @see Iterator::rewind()
1499 * @return void
1500 */
1501 public function rewind() {
1502 $this->pos = 0;
1503 $this->bufferAfter = null;
1504 $this->bufferIter = $this->pageFromList(
1505 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1506 ); // updates $this->bufferAfter
1507 }
1508
1509 /**
1510 * @see Iterator::valid()
1511 * @return bool
1512 */
1513 public function valid() {
1514 if ( $this->bufferIter === null ) {
1515 return false; // some failure?
1516 } else {
1517 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1518 }
1519 }
1520
1521 /**
1522 * Get the given list portion (page)
1523 *
1524 * @param $container string Resolved container name
1525 * @param $dir string Resolved path relative to container
1526 * @param $after string|null
1527 * @param $limit integer
1528 * @param $params Array
1529 * @return Traversable|Array|null Returns null on failure
1530 */
1531 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1532 }
1533
1534 /**
1535 * Iterator for listing directories
1536 */
1537 class SwiftFileBackendDirList extends SwiftFileBackendList {
1538 /**
1539 * @see Iterator::current()
1540 * @return string|bool String (relative path) or false
1541 */
1542 public function current() {
1543 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1544 }
1545
1546 /**
1547 * @see SwiftFileBackendList::pageFromList()
1548 * @return Array|null
1549 */
1550 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1551 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1552 }
1553 }
1554
1555 /**
1556 * Iterator for listing regular files
1557 */
1558 class SwiftFileBackendFileList extends SwiftFileBackendList {
1559 /**
1560 * @see Iterator::current()
1561 * @return string|bool String (relative path) or false
1562 */
1563 public function current() {
1564 return substr( current( $this->bufferIter ), $this->suffixStart );
1565 }
1566
1567 /**
1568 * @see SwiftFileBackendList::pageFromList()
1569 * @return Array|null
1570 */
1571 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1572 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1573 }
1574 }