Merge "[FileBackend] Avoid stat call in getFileContents() for swift."
[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 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
788 if ( $tmpFile ) {
789 $hash = $tmpFile->getSha1Base36();
790 if ( $hash !== false ) {
791 $obj->metadata['Sha1base36'] = $hash;
792 $obj->sync_metadata(); // save to Swift
793 wfProfileOut( __METHOD__ );
794 return true; // success
795 }
796 }
797 }
798 $obj->metadata['Sha1base36'] = false;
799 wfProfileOut( __METHOD__ );
800 return false; // failed
801 }
802
803 /**
804 * @see FileBackend::getFileContents()
805 * @return bool|string
806 */
807 public function getFileContents( array $params ) {
808 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
809 if ( $srcRel === null ) {
810 return false; // invalid storage path
811 }
812
813 $data = false;
814 try {
815 $sContObj = $this->getContainer( $srcCont );
816 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
817 $data = $obj->read( $this->headersFromParams( $params ) );
818 } catch ( NoSuchContainerException $e ) {
819 } catch ( NoSuchObjectException $e ) {
820 } catch ( CloudFilesException $e ) { // some other exception?
821 $this->handleException( $e, null, __METHOD__, $params );
822 }
823
824 return $data;
825 }
826
827 /**
828 * @see FileBackendStore::doDirectoryExists()
829 * @return bool|null
830 */
831 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
832 try {
833 $container = $this->getContainer( $fullCont );
834 $prefix = ( $dir == '' ) ? null : "{$dir}/";
835 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
836 } catch ( NoSuchContainerException $e ) {
837 return false;
838 } catch ( CloudFilesException $e ) { // some other exception?
839 $this->handleException( $e, null, __METHOD__,
840 array( 'cont' => $fullCont, 'dir' => $dir ) );
841 }
842
843 return null; // error
844 }
845
846 /**
847 * @see FileBackendStore::getDirectoryListInternal()
848 * @return SwiftFileBackendDirList
849 */
850 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
851 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
852 }
853
854 /**
855 * @see FileBackendStore::getFileListInternal()
856 * @return SwiftFileBackendFileList
857 */
858 public function getFileListInternal( $fullCont, $dir, array $params ) {
859 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
860 }
861
862 /**
863 * Do not call this function outside of SwiftFileBackendFileList
864 *
865 * @param $fullCont string Resolved container name
866 * @param $dir string Resolved storage directory with no trailing slash
867 * @param $after string|null Storage path of file to list items after
868 * @param $limit integer Max number of items to list
869 * @param $params Array Includes flag for 'topOnly'
870 * @return Array List of relative paths of dirs directly under $dir
871 */
872 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
873 $dirs = array();
874 if ( $after === INF ) {
875 return $dirs; // nothing more
876 }
877 wfProfileIn( __METHOD__ . '-' . $this->name );
878
879 try {
880 $container = $this->getContainer( $fullCont );
881 $prefix = ( $dir == '' ) ? null : "{$dir}/";
882 // Non-recursive: only list dirs right under $dir
883 if ( !empty( $params['topOnly'] ) ) {
884 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
885 foreach ( $objects as $object ) { // files and dirs
886 if ( substr( $object, -1 ) === '/' ) {
887 $dirs[] = $object; // directories end in '/'
888 }
889 }
890 // Recursive: list all dirs under $dir and its subdirs
891 } else {
892 // Get directory from last item of prior page
893 $lastDir = $this->getParentDir( $after ); // must be first page
894 $objects = $container->list_objects( $limit, $after, $prefix );
895 foreach ( $objects as $object ) { // files
896 $objectDir = $this->getParentDir( $object ); // directory of object
897 if ( $objectDir !== false ) { // file has a parent dir
898 // Swift stores paths in UTF-8, using binary sorting.
899 // See function "create_container_table" in common/db.py.
900 // If a directory is not "greater" than the last one,
901 // then it was already listed by the calling iterator.
902 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
903 $pDir = $objectDir;
904 do { // add dir and all its parent dirs
905 $dirs[] = "{$pDir}/";
906 $pDir = $this->getParentDir( $pDir );
907 } while ( $pDir !== false // sanity
908 && strcmp( $pDir, $lastDir ) > 0 // not done already
909 && strlen( $pDir ) > strlen( $dir ) // within $dir
910 );
911 }
912 $lastDir = $objectDir;
913 }
914 }
915 }
916 if ( count( $objects ) < $limit ) {
917 $after = INF; // avoid a second RTT
918 } else {
919 $after = end( $objects ); // update last item
920 }
921 } catch ( NoSuchContainerException $e ) {
922 } catch ( CloudFilesException $e ) { // some other exception?
923 $this->handleException( $e, null, __METHOD__,
924 array( 'cont' => $fullCont, 'dir' => $dir ) );
925 }
926
927 wfProfileOut( __METHOD__ . '-' . $this->name );
928 return $dirs;
929 }
930
931 protected function getParentDir( $path ) {
932 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
933 }
934
935 /**
936 * Do not call this function outside of SwiftFileBackendFileList
937 *
938 * @param $fullCont string Resolved container name
939 * @param $dir string Resolved storage directory with no trailing slash
940 * @param $after string|null Storage path of file to list items after
941 * @param $limit integer Max number of items to list
942 * @param $params Array Includes flag for 'topOnly'
943 * @return Array List of relative paths of files under $dir
944 */
945 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
946 $files = array();
947 if ( $after === INF ) {
948 return $files; // nothing more
949 }
950 wfProfileIn( __METHOD__ . '-' . $this->name );
951
952 try {
953 $container = $this->getContainer( $fullCont );
954 $prefix = ( $dir == '' ) ? null : "{$dir}/";
955 // Non-recursive: only list files right under $dir
956 if ( !empty( $params['topOnly'] ) ) { // files and dirs
957 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
958 foreach ( $objects as $object ) {
959 if ( substr( $object, -1 ) !== '/' ) {
960 $files[] = $object; // directories end in '/'
961 }
962 }
963 // Recursive: list all files under $dir and its subdirs
964 } else { // files
965 $objects = $container->list_objects( $limit, $after, $prefix );
966 $files = $objects;
967 }
968 if ( count( $objects ) < $limit ) {
969 $after = INF; // avoid a second RTT
970 } else {
971 $after = end( $objects ); // update last item
972 }
973 } catch ( NoSuchContainerException $e ) {
974 } catch ( CloudFilesException $e ) { // some other exception?
975 $this->handleException( $e, null, __METHOD__,
976 array( 'cont' => $fullCont, 'dir' => $dir ) );
977 }
978
979 wfProfileOut( __METHOD__ . '-' . $this->name );
980 return $files;
981 }
982
983 /**
984 * @see FileBackendStore::doGetFileSha1base36()
985 * @return bool
986 */
987 protected function doGetFileSha1base36( array $params ) {
988 $stat = $this->getFileStat( $params );
989 if ( $stat ) {
990 return $stat['sha1'];
991 } else {
992 return false;
993 }
994 }
995
996 /**
997 * @see FileBackendStore::doStreamFile()
998 * @return Status
999 */
1000 protected function doStreamFile( array $params ) {
1001 $status = Status::newGood();
1002
1003 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1004 if ( $srcRel === null ) {
1005 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1006 }
1007
1008 try {
1009 $cont = $this->getContainer( $srcCont );
1010 } catch ( NoSuchContainerException $e ) {
1011 $status->fatal( 'backend-fail-stream', $params['src'] );
1012 return $status;
1013 } catch ( CloudFilesException $e ) { // some other exception?
1014 $this->handleException( $e, $status, __METHOD__, $params );
1015 return $status;
1016 }
1017
1018 try {
1019 $output = fopen( 'php://output', 'wb' );
1020 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1021 $obj->stream( $output, $this->headersFromParams( $params ) );
1022 } catch ( NoSuchObjectException $e ) {
1023 $status->fatal( 'backend-fail-stream', $params['src'] );
1024 } catch ( CloudFilesException $e ) { // some other exception?
1025 $this->handleException( $e, $status, __METHOD__, $params );
1026 }
1027
1028 return $status;
1029 }
1030
1031 /**
1032 * @see FileBackendStore::getLocalCopy()
1033 * @return null|TempFSFile
1034 */
1035 public function getLocalCopy( array $params ) {
1036 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1037 if ( $srcRel === null ) {
1038 return null;
1039 }
1040
1041 // Blindly create a tmp file and stream to it, catching any exception if the file does
1042 // not exist. Also, doing a stat here will cause infinite loops in addMissingMetadata().
1043 $tmpFile = null;
1044 try {
1045 $sContObj = $this->getContainer( $srcCont );
1046 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1047 // Get source file extension
1048 $ext = FileBackend::extensionFromPath( $srcRel );
1049 // Create a new temporary file...
1050 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1051 if ( $tmpFile ) {
1052 $handle = fopen( $tmpFile->getPath(), 'wb' );
1053 if ( $handle ) {
1054 $obj->stream( $handle, $this->headersFromParams( $params ) );
1055 fclose( $handle );
1056 } else {
1057 $tmpFile = null; // couldn't open temp file
1058 }
1059 }
1060 } catch ( NoSuchContainerException $e ) {
1061 $tmpFile = null;
1062 } catch ( NoSuchObjectException $e ) {
1063 $tmpFile = null;
1064 } catch ( CloudFilesException $e ) { // some other exception?
1065 $tmpFile = null;
1066 $this->handleException( $e, null, __METHOD__, $params );
1067 }
1068
1069 return $tmpFile;
1070 }
1071
1072 /**
1073 * @see FileBackendStore::directoriesAreVirtual()
1074 * @return bool
1075 */
1076 protected function directoriesAreVirtual() {
1077 return true;
1078 }
1079
1080 /**
1081 * Get headers to send to Swift when reading a file based
1082 * on a FileBackend params array, e.g. that of getLocalCopy().
1083 * $params is currently only checked for a 'latest' flag.
1084 *
1085 * @param $params Array
1086 * @return Array
1087 */
1088 protected function headersFromParams( array $params ) {
1089 $hdrs = array();
1090 if ( !empty( $params['latest'] ) ) {
1091 $hdrs[] = 'X-Newest: true';
1092 }
1093 return $hdrs;
1094 }
1095
1096 /**
1097 * @see FileBackendStore::doExecuteOpHandlesInternal()
1098 * @return Array List of corresponding Status objects
1099 */
1100 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1101 $statuses = array();
1102
1103 $cfOps = array(); // list of CF_Async_Op objects
1104 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1105 $cfOps[$index] = $fileOpHandle->cfOp;
1106 }
1107 $batch = new CF_Async_Op_Batch( $cfOps );
1108
1109 $cfOps = $batch->execute();
1110 foreach ( $cfOps as $index => $cfOp ) {
1111 $status = Status::newGood();
1112 try { // catch exceptions; update status
1113 $function = '_getResponse' . $fileOpHandles[$index]->call;
1114 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1115 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1116 } catch ( CloudFilesException $e ) { // some other exception?
1117 $this->handleException( $e, $status,
1118 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1119 }
1120 $statuses[$index] = $status;
1121 }
1122
1123 return $statuses;
1124 }
1125
1126 /**
1127 * Set read/write permissions for a Swift container.
1128 *
1129 * $readGrps is a list of the possible criteria for a request to have
1130 * access to read a container. Each item is one of the following formats:
1131 * - account:user : Grants access if the request is by the given user
1132 * - .r:<regex> : Grants access if the request is from a referrer host that
1133 * matches the expression and the request is not for a listing.
1134 * Setting this to '*' effectively makes a container public.
1135 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1136 * matches the expression and the request for a listing.
1137 *
1138 * $writeGrps is a list of the possible criteria for a request to have
1139 * access to write to a container. Each item is of the following format:
1140 * - account:user : Grants access if the request is by the given user
1141 *
1142 * @see http://swift.openstack.org/misc.html#acls
1143 *
1144 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1145 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1146 *
1147 * @param $contObj CF_Container Swift container
1148 * @param $readGrps Array List of read access routes
1149 * @param $writeGrps Array List of write access routes
1150 * @return Status
1151 */
1152 protected function setContainerAccess(
1153 CF_Container $contObj, array $readGrps, array $writeGrps
1154 ) {
1155 $creds = $contObj->cfs_auth->export_credentials();
1156
1157 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1158
1159 // Note: 10 second timeout consistent with php-cloudfiles
1160 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1161 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1162 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1163 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1164
1165 return $req->execute(); // should return 204
1166 }
1167
1168 /**
1169 * Purge the CDN cache of affected objects if CDN caching is enabled.
1170 * This is for Rackspace/Akamai CDNs.
1171 *
1172 * @param $objects Array List of CF_Object items
1173 * @return void
1174 */
1175 public function purgeCDNCache( array $objects ) {
1176 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1177 foreach ( $objects as $object ) {
1178 try {
1179 $object->purge_from_cdn();
1180 } catch ( CDNNotEnabledException $e ) {
1181 // CDN not enabled; nothing to see here
1182 } catch ( CloudFilesException $e ) {
1183 $this->handleException( $e, null, __METHOD__,
1184 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1185 }
1186 }
1187 }
1188 }
1189
1190 /**
1191 * Get an authenticated connection handle to the Swift proxy
1192 *
1193 * @return CF_Connection|bool False on failure
1194 * @throws CloudFilesException
1195 */
1196 protected function getConnection() {
1197 if ( $this->connException instanceof CloudFilesException ) {
1198 if ( ( time() - $this->connErrorTime ) < 60 ) {
1199 throw $this->connException; // failed last attempt; don't bother
1200 } else { // actually retry this time
1201 $this->connException = null;
1202 $this->connErrorTime = 0;
1203 }
1204 }
1205 // Session keys expire after a while, so we renew them periodically
1206 $reAuth = ( ( time() - $this->sessionStarted ) > $this->authTTL );
1207 // Authenticate with proxy and get a session key...
1208 if ( !$this->conn || $reAuth ) {
1209 $this->sessionStarted = 0;
1210 $this->connContainerCache->clear();
1211 $cacheKey = $this->getCredsCacheKey( $this->auth->username );
1212 $creds = $this->srvCache->get( $cacheKey ); // credentials
1213 if ( is_array( $creds ) ) { // cache hit
1214 $this->auth->load_cached_credentials(
1215 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1216 $this->sessionStarted = time() - ceil( $this->authTTL/2 ); // skew for worst case
1217 } else { // cache miss
1218 try {
1219 $this->auth->authenticate();
1220 $creds = $this->auth->export_credentials();
1221 $this->srvCache->add( $cacheKey, $creds, ceil( $this->authTTL/2 ) ); // cache
1222 $this->sessionStarted = time();
1223 } catch ( CloudFilesException $e ) {
1224 $this->connException = $e; // don't keep re-trying
1225 $this->connErrorTime = time();
1226 throw $e; // throw it back
1227 }
1228 }
1229 if ( $this->conn ) { // re-authorizing?
1230 $this->conn->close(); // close active cURL handles in CF_Http object
1231 }
1232 $this->conn = new CF_Connection( $this->auth );
1233 }
1234 return $this->conn;
1235 }
1236
1237 /**
1238 * Close the connection to the Swift proxy
1239 *
1240 * @return void
1241 */
1242 protected function closeConnection() {
1243 if ( $this->conn ) {
1244 $this->conn->close(); // close active cURL handles in CF_Http object
1245 $this->sessionStarted = 0;
1246 $this->connContainerCache->clear();
1247 }
1248 }
1249
1250 /**
1251 * Get the cache key for a container
1252 *
1253 * @param $username string
1254 * @return string
1255 */
1256 private function getCredsCacheKey( $username ) {
1257 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1258 }
1259
1260 /**
1261 * @see FileBackendStore::doClearCache()
1262 */
1263 protected function doClearCache( array $paths = null ) {
1264 $this->connContainerCache->clear(); // clear container object cache
1265 }
1266
1267 /**
1268 * Get a Swift container object, possibly from process cache.
1269 * Use $reCache if the file count or byte count is needed.
1270 *
1271 * @param $container string Container name
1272 * @param $bypassCache bool Bypass all caches and load from Swift
1273 * @return CF_Container
1274 * @throws CloudFilesException
1275 */
1276 protected function getContainer( $container, $bypassCache = false ) {
1277 $conn = $this->getConnection(); // Swift proxy connection
1278 if ( $bypassCache ) { // purge cache
1279 $this->connContainerCache->clear( $container );
1280 } elseif ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1281 $this->primeContainerCache( array( $container ) ); // check persistent cache
1282 }
1283 if ( !$this->connContainerCache->has( $container, 'obj' ) ) {
1284 $contObj = $conn->get_container( $container );
1285 // NoSuchContainerException not thrown: container must exist
1286 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache it
1287 if ( !$bypassCache ) {
1288 $this->setContainerCache( $container, // update persistent cache
1289 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1290 );
1291 }
1292 }
1293 return $this->connContainerCache->get( $container, 'obj' );
1294 }
1295
1296 /**
1297 * Create a Swift container
1298 *
1299 * @param $container string Container name
1300 * @return CF_Container
1301 * @throws CloudFilesException
1302 */
1303 protected function createContainer( $container ) {
1304 $conn = $this->getConnection(); // Swift proxy connection
1305 $contObj = $conn->create_container( $container );
1306 $this->connContainerCache->set( $container, 'obj', $contObj ); // cache
1307 return $contObj;
1308 }
1309
1310 /**
1311 * Delete a Swift container
1312 *
1313 * @param $container string Container name
1314 * @return void
1315 * @throws CloudFilesException
1316 */
1317 protected function deleteContainer( $container ) {
1318 $conn = $this->getConnection(); // Swift proxy connection
1319 $this->connContainerCache->clear( $container ); // purge
1320 $conn->delete_container( $container );
1321 }
1322
1323 /**
1324 * @see FileBackendStore::doPrimeContainerCache()
1325 * @return void
1326 */
1327 protected function doPrimeContainerCache( array $containerInfo ) {
1328 try {
1329 $conn = $this->getConnection(); // Swift proxy connection
1330 foreach ( $containerInfo as $container => $info ) {
1331 $contObj = new CF_Container( $conn->cfs_auth, $conn->cfs_http,
1332 $container, $info['count'], $info['bytes'] );
1333 $this->connContainerCache->set( $container, 'obj', $contObj );
1334 }
1335 } catch ( CloudFilesException $e ) { // some other exception?
1336 $this->handleException( $e, null, __METHOD__, array() );
1337 }
1338 }
1339
1340 /**
1341 * Log an unexpected exception for this backend.
1342 * This also sets the Status object to have a fatal error.
1343 *
1344 * @param $e Exception
1345 * @param $status Status|null
1346 * @param $func string
1347 * @param $params Array
1348 * @return void
1349 */
1350 protected function handleException( Exception $e, $status, $func, array $params ) {
1351 if ( $status instanceof Status ) {
1352 if ( $e instanceof AuthenticationException ) {
1353 $status->fatal( 'backend-fail-connect', $this->name );
1354 } else {
1355 $status->fatal( 'backend-fail-internal', $this->name );
1356 }
1357 }
1358 if ( $e->getMessage() ) {
1359 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1360 }
1361 if ( $e instanceof InvalidResponseException ) { // possibly a stale token
1362 $this->srvCache->delete( $this->getCredsCacheKey( $this->auth->username ) );
1363 $this->closeConnection(); // force a re-connect and re-auth next time
1364 }
1365 wfDebugLog( 'SwiftBackend',
1366 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1367 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1368 );
1369 }
1370 }
1371
1372 /**
1373 * @see FileBackendStoreOpHandle
1374 */
1375 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1376 /** @var CF_Async_Op */
1377 public $cfOp;
1378 /** @var Array */
1379 public $affectedObjects = array();
1380
1381 public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
1382 $this->backend = $backend;
1383 $this->params = $params;
1384 $this->call = $call;
1385 $this->cfOp = $cfOp;
1386 }
1387 }
1388
1389 /**
1390 * SwiftFileBackend helper class to page through listings.
1391 * Swift also has a listing limit of 10,000 objects for sanity.
1392 * Do not use this class from places outside SwiftFileBackend.
1393 *
1394 * @ingroup FileBackend
1395 */
1396 abstract class SwiftFileBackendList implements Iterator {
1397 /** @var Array */
1398 protected $bufferIter = array();
1399 protected $bufferAfter = null; // string; list items *after* this path
1400 protected $pos = 0; // integer
1401 /** @var Array */
1402 protected $params = array();
1403
1404 /** @var SwiftFileBackend */
1405 protected $backend;
1406 protected $container; // string; container name
1407 protected $dir; // string; storage directory
1408 protected $suffixStart; // integer
1409
1410 const PAGE_SIZE = 9000; // file listing buffer size
1411
1412 /**
1413 * @param $backend SwiftFileBackend
1414 * @param $fullCont string Resolved container name
1415 * @param $dir string Resolved directory relative to container
1416 * @param $params Array
1417 */
1418 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1419 $this->backend = $backend;
1420 $this->container = $fullCont;
1421 $this->dir = $dir;
1422 if ( substr( $this->dir, -1 ) === '/' ) {
1423 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1424 }
1425 if ( $this->dir == '' ) { // whole container
1426 $this->suffixStart = 0;
1427 } else { // dir within container
1428 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1429 }
1430 $this->params = $params;
1431 }
1432
1433 /**
1434 * @see Iterator::key()
1435 * @return integer
1436 */
1437 public function key() {
1438 return $this->pos;
1439 }
1440
1441 /**
1442 * @see Iterator::next()
1443 * @return void
1444 */
1445 public function next() {
1446 // Advance to the next file in the page
1447 next( $this->bufferIter );
1448 ++$this->pos;
1449 // Check if there are no files left in this page and
1450 // advance to the next page if this page was not empty.
1451 if ( !$this->valid() && count( $this->bufferIter ) ) {
1452 $this->bufferIter = $this->pageFromList(
1453 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1454 ); // updates $this->bufferAfter
1455 }
1456 }
1457
1458 /**
1459 * @see Iterator::rewind()
1460 * @return void
1461 */
1462 public function rewind() {
1463 $this->pos = 0;
1464 $this->bufferAfter = null;
1465 $this->bufferIter = $this->pageFromList(
1466 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1467 ); // updates $this->bufferAfter
1468 }
1469
1470 /**
1471 * @see Iterator::valid()
1472 * @return bool
1473 */
1474 public function valid() {
1475 if ( $this->bufferIter === null ) {
1476 return false; // some failure?
1477 } else {
1478 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1479 }
1480 }
1481
1482 /**
1483 * Get the given list portion (page)
1484 *
1485 * @param $container string Resolved container name
1486 * @param $dir string Resolved path relative to container
1487 * @param $after string|null
1488 * @param $limit integer
1489 * @param $params Array
1490 * @return Traversable|Array|null Returns null on failure
1491 */
1492 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1493 }
1494
1495 /**
1496 * Iterator for listing directories
1497 */
1498 class SwiftFileBackendDirList extends SwiftFileBackendList {
1499 /**
1500 * @see Iterator::current()
1501 * @return string|bool String (relative path) or false
1502 */
1503 public function current() {
1504 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1505 }
1506
1507 /**
1508 * @see SwiftFileBackendList::pageFromList()
1509 * @return Array|null
1510 */
1511 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1512 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1513 }
1514 }
1515
1516 /**
1517 * Iterator for listing regular files
1518 */
1519 class SwiftFileBackendFileList extends SwiftFileBackendList {
1520 /**
1521 * @see Iterator::current()
1522 * @return string|bool String (relative path) or false
1523 */
1524 public function current() {
1525 return substr( current( $this->bufferIter ), $this->suffixStart );
1526 }
1527
1528 /**
1529 * @see SwiftFileBackendList::pageFromList()
1530 * @return Array|null
1531 */
1532 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1533 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1534 }
1535 }