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