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