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