Merge "(bug 32537) Pre-register default-loaded RL modules in the client-side loader."
[lhc/web/wiklou.git] / includes / filerepo / backend / SwiftFileBackend.php
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 * @author Russ Nelson
6 * @author Aaron Schulz
7 */
8
9 /**
10 * @brief Class for an OpenStack Swift based file backend.
11 *
12 * This requires the SwiftCloudFiles MediaWiki extension, which includes
13 * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
14 * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
15 *
16 * Status messages should avoid mentioning the Swift account name.
17 * Likewise, error suppression should be used to avoid path disclosure.
18 *
19 * @ingroup FileBackend
20 * @since 1.19
21 */
22 class SwiftFileBackend extends FileBackendStore {
23 /** @var CF_Authentication */
24 protected $auth; // Swift authentication handler
25 protected $authTTL; // integer seconds
26 protected $swiftAnonUser; // string; username to handle unauthenticated requests
27 protected $maxContCacheSize = 100; // integer; max containers with entries
28
29 /** @var CF_Connection */
30 protected $conn; // Swift connection handle
31 protected $connStarted = 0; // integer UNIX timestamp
32 protected $connContainers = array(); // container object cache
33
34 /**
35 * @see FileBackendStore::__construct()
36 * Additional $config params include:
37 * swiftAuthUrl : Swift authentication server URL
38 * swiftUser : Swift user used by MediaWiki (account:username)
39 * swiftKey : Swift authentication key for the above user
40 * swiftAuthTTL : Swift authentication TTL (seconds)
41 * swiftAnonUser : Swift user used for end-user requests (account:username)
42 * shardViaHashLevels : Map of container names to sharding config with:
43 * 'base' : base of hash characters, 16 or 36
44 * 'levels' : the number of hash levels (and digits)
45 * 'repeat' : hash subdirectories are prefixed with all the
46 * parent hash directory names (e.g. "a/ab/abc")
47 */
48 public function __construct( array $config ) {
49 parent::__construct( $config );
50 // Required settings
51 $this->auth = new CF_Authentication(
52 $config['swiftUser'],
53 $config['swiftKey'],
54 null, // account; unused
55 $config['swiftAuthUrl']
56 );
57 // Optional settings
58 $this->authTTL = isset( $config['swiftAuthTTL'] )
59 ? $config['swiftAuthTTL']
60 : 120; // some sane number
61 $this->swiftAnonUser = isset( $config['swiftAnonUser'] )
62 ? $config['swiftAnonUser']
63 : '';
64 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
65 ? $config['shardViaHashLevels']
66 : '';
67 }
68
69 /**
70 * @see FileBackendStore::resolveContainerPath()
71 * @return null
72 */
73 protected function resolveContainerPath( $container, $relStoragePath ) {
74 if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
75 return null; // too long for Swift
76 }
77 return $relStoragePath;
78 }
79
80 /**
81 * @see FileBackendStore::isPathUsableInternal()
82 * @return bool
83 */
84 public function isPathUsableInternal( $storagePath ) {
85 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
86 if ( $rel === null ) {
87 return false; // invalid
88 }
89
90 try {
91 $this->getContainer( $container );
92 return true; // container exists
93 } catch ( NoSuchContainerException $e ) {
94 } catch ( InvalidResponseException $e ) {
95 } catch ( Exception $e ) { // some other exception?
96 $this->logException( $e, __METHOD__, array( 'path' => $storagePath ) );
97 }
98
99 return false;
100 }
101
102 /**
103 * @see FileBackendStore::doCreateInternal()
104 * @return Status
105 */
106 protected function doCreateInternal( array $params ) {
107 $status = Status::newGood();
108
109 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
110 if ( $dstRel === null ) {
111 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
112 return $status;
113 }
114
115 // (a) Check the destination container and object
116 try {
117 $dContObj = $this->getContainer( $dstCont );
118 if ( empty( $params['overwrite'] ) &&
119 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
120 {
121 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
122 return $status;
123 }
124 } catch ( NoSuchContainerException $e ) {
125 $status->fatal( 'backend-fail-create', $params['dst'] );
126 return $status;
127 } catch ( InvalidResponseException $e ) {
128 $status->fatal( 'backend-fail-connect', $this->name );
129 return $status;
130 } catch ( Exception $e ) { // some other exception?
131 $status->fatal( 'backend-fail-internal', $this->name );
132 $this->logException( $e, __METHOD__, $params );
133 return $status;
134 }
135
136 // (b) Get a SHA-1 hash of the object
137 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
138
139 // (c) Actually create the object
140 try {
141 // Create a fresh CF_Object with no fields preloaded.
142 // We don't want to preserve headers, metadata, and such.
143 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
144 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
145 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
146 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
147 // The MD5 here will be checked within Swift against its own MD5.
148 $obj->set_etag( md5( $params['content'] ) );
149 // Use the same content type as StreamFile for security
150 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
151 // Actually write the object in Swift
152 $obj->write( $params['content'] );
153 } catch ( BadContentTypeException $e ) {
154 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
155 } catch ( InvalidResponseException $e ) {
156 $status->fatal( 'backend-fail-connect', $this->name );
157 } catch ( Exception $e ) { // some other exception?
158 $status->fatal( 'backend-fail-internal', $this->name );
159 $this->logException( $e, __METHOD__, $params );
160 }
161
162 return $status;
163 }
164
165 /**
166 * @see FileBackendStore::doStoreInternal()
167 * @return Status
168 */
169 protected function doStoreInternal( array $params ) {
170 $status = Status::newGood();
171
172 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
173 if ( $dstRel === null ) {
174 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
175 return $status;
176 }
177
178 // (a) Check the destination container and object
179 try {
180 $dContObj = $this->getContainer( $dstCont );
181 if ( empty( $params['overwrite'] ) &&
182 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
183 {
184 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
185 return $status;
186 }
187 } catch ( NoSuchContainerException $e ) {
188 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
189 return $status;
190 } catch ( InvalidResponseException $e ) {
191 $status->fatal( 'backend-fail-connect', $this->name );
192 return $status;
193 } catch ( Exception $e ) { // some other exception?
194 $status->fatal( 'backend-fail-internal', $this->name );
195 $this->logException( $e, __METHOD__, $params );
196 return $status;
197 }
198
199 // (b) Get a SHA-1 hash of the object
200 $sha1Hash = sha1_file( $params['src'] );
201 if ( $sha1Hash === false ) { // source doesn't exist?
202 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
203 return $status;
204 }
205 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
206
207 // (c) Actually store the object
208 try {
209 // Create a fresh CF_Object with no fields preloaded.
210 // We don't want to preserve headers, metadata, and such.
211 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
212 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
213 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
214 // The MD5 here will be checked within Swift against its own MD5.
215 $obj->set_etag( md5_file( $params['src'] ) );
216 // Use the same content type as StreamFile for security
217 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
218 // Actually write the object in Swift
219 $obj->load_from_filename( $params['src'], True ); // calls $obj->write()
220 } catch ( BadContentTypeException $e ) {
221 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
222 } catch ( IOException $e ) {
223 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
224 } catch ( InvalidResponseException $e ) {
225 $status->fatal( 'backend-fail-connect', $this->name );
226 } catch ( Exception $e ) { // some other exception?
227 $status->fatal( 'backend-fail-internal', $this->name );
228 $this->logException( $e, __METHOD__, $params );
229 }
230
231 return $status;
232 }
233
234 /**
235 * @see FileBackendStore::doCopyInternal()
236 * @return Status
237 */
238 protected function doCopyInternal( array $params ) {
239 $status = Status::newGood();
240
241 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
242 if ( $srcRel === null ) {
243 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
244 return $status;
245 }
246
247 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
248 if ( $dstRel === null ) {
249 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
250 return $status;
251 }
252
253 // (a) Check the source/destination containers and destination object
254 try {
255 $sContObj = $this->getContainer( $srcCont );
256 $dContObj = $this->getContainer( $dstCont );
257 if ( empty( $params['overwrite'] ) &&
258 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
259 {
260 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
261 return $status;
262 }
263 } catch ( NoSuchContainerException $e ) {
264 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
265 return $status;
266 } catch ( InvalidResponseException $e ) {
267 $status->fatal( 'backend-fail-connect', $this->name );
268 return $status;
269 } catch ( Exception $e ) { // some other exception?
270 $status->fatal( 'backend-fail-internal', $this->name );
271 $this->logException( $e, __METHOD__, $params );
272 return $status;
273 }
274
275 // (b) Actually copy the file to the destination
276 try {
277 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
278 } catch ( NoSuchObjectException $e ) { // source object does not exist
279 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
280 } catch ( InvalidResponseException $e ) {
281 $status->fatal( 'backend-fail-connect', $this->name );
282 } catch ( Exception $e ) { // some other exception?
283 $status->fatal( 'backend-fail-internal', $this->name );
284 $this->logException( $e, __METHOD__, $params );
285 }
286
287 return $status;
288 }
289
290 /**
291 * @see FileBackendStore::doDeleteInternal()
292 * @return Status
293 */
294 protected function doDeleteInternal( array $params ) {
295 $status = Status::newGood();
296
297 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
298 if ( $srcRel === null ) {
299 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
300 return $status;
301 }
302
303 try {
304 $sContObj = $this->getContainer( $srcCont );
305 $sContObj->delete_object( $srcRel );
306 } catch ( NoSuchContainerException $e ) {
307 $status->fatal( 'backend-fail-delete', $params['src'] );
308 } catch ( NoSuchObjectException $e ) {
309 if ( empty( $params['ignoreMissingSource'] ) ) {
310 $status->fatal( 'backend-fail-delete', $params['src'] );
311 }
312 } catch ( InvalidResponseException $e ) {
313 $status->fatal( 'backend-fail-connect', $this->name );
314 } catch ( Exception $e ) { // some other exception?
315 $status->fatal( 'backend-fail-internal', $this->name );
316 $this->logException( $e, __METHOD__, $params );
317 }
318
319 return $status;
320 }
321
322 /**
323 * @see FileBackendStore::doPrepareInternal()
324 * @return Status
325 */
326 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
327 $status = Status::newGood();
328
329 // (a) Check if container already exists
330 try {
331 $contObj = $this->getContainer( $fullCont );
332 // NoSuchContainerException not thrown: container must exist
333 return $status; // already exists
334 } catch ( NoSuchContainerException $e ) {
335 // NoSuchContainerException thrown: container does not exist
336 } catch ( InvalidResponseException $e ) {
337 $status->fatal( 'backend-fail-connect', $this->name );
338 return $status;
339 } catch ( Exception $e ) { // some other exception?
340 $status->fatal( 'backend-fail-internal', $this->name );
341 $this->logException( $e, __METHOD__, $params );
342 return $status;
343 }
344
345 // (b) Create container as needed
346 try {
347 $contObj = $this->createContainer( $fullCont );
348 if ( $this->swiftAnonUser != '' ) {
349 // Make container public to end-users...
350 $status->merge( $this->setContainerAccess(
351 $contObj,
352 array( $this->auth->username, $this->swiftAnonUser ), // read
353 array( $this->auth->username ) // write
354 ) );
355 }
356 } catch ( InvalidResponseException $e ) {
357 $status->fatal( 'backend-fail-connect', $this->name );
358 return $status;
359 } catch ( Exception $e ) { // some other exception?
360 $status->fatal( 'backend-fail-internal', $this->name );
361 $this->logException( $e, __METHOD__, $params );
362 return $status;
363 }
364
365 return $status;
366 }
367
368 /**
369 * @see FileBackendStore::doSecureInternal()
370 * @return Status
371 */
372 protected function doSecureInternal( $fullCont, $dir, array $params ) {
373 $status = Status::newGood();
374
375 if ( $this->swiftAnonUser != '' ) {
376 // Restrict container from end-users...
377 try {
378 // doPrepareInternal() should have been called,
379 // so the Swift container should already exist...
380 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
381 // NoSuchContainerException not thrown: container must exist
382 if ( !isset( $contObj->mw_wasSecured ) ) {
383 $status->merge( $this->setContainerAccess(
384 $contObj,
385 array( $this->auth->username ), // read
386 array( $this->auth->username ) // write
387 ) );
388 // @TODO: when php-cloudfiles supports container
389 // metadata, we can make use of that to avoid RTTs
390 $contObj->mw_wasSecured = true; // avoid useless RTTs
391 }
392 } catch ( InvalidResponseException $e ) {
393 $status->fatal( 'backend-fail-connect', $this->name );
394 } catch ( Exception $e ) { // some other exception?
395 $status->fatal( 'backend-fail-internal', $this->name );
396 $this->logException( $e, __METHOD__, $params );
397 }
398 }
399
400 return $status;
401 }
402
403 /**
404 * @see FileBackendStore::doCleanInternal()
405 * @return Status
406 */
407 protected function doCleanInternal( $fullCont, $dir, array $params ) {
408 $status = Status::newGood();
409
410 // Only containers themselves can be removed, all else is virtual
411 if ( $dir != '' ) {
412 return $status; // nothing to do
413 }
414
415 // (a) Check the container
416 try {
417 $contObj = $this->getContainer( $fullCont, true );
418 } catch ( NoSuchContainerException $e ) {
419 return $status; // ok, nothing to do
420 } catch ( InvalidResponseException $e ) {
421 $status->fatal( 'backend-fail-connect', $this->name );
422 return $status;
423 } catch ( Exception $e ) { // some other exception?
424 $status->fatal( 'backend-fail-internal', $this->name );
425 $this->logException( $e, __METHOD__, $params );
426 return $status;
427 }
428
429 // (b) Delete the container if empty
430 if ( $contObj->object_count == 0 ) {
431 try {
432 $this->deleteContainer( $fullCont );
433 } catch ( NoSuchContainerException $e ) {
434 return $status; // race?
435 } catch ( InvalidResponseException $e ) {
436 $status->fatal( 'backend-fail-connect', $this->name );
437 return $status;
438 } catch ( Exception $e ) { // some other exception?
439 $status->fatal( 'backend-fail-internal', $this->name );
440 $this->logException( $e, __METHOD__, $params );
441 return $status;
442 }
443 }
444
445 return $status;
446 }
447
448 /**
449 * @see FileBackendStore::doFileExists()
450 * @return array|bool|null
451 */
452 protected function doGetFileStat( array $params ) {
453 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
454 if ( $srcRel === null ) {
455 return false; // invalid storage path
456 }
457
458 $stat = false;
459 try {
460 $contObj = $this->getContainer( $srcCont );
461 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
462 $this->addMissingMetadata( $srcObj, $params['src'] );
463 $stat = array(
464 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
465 'mtime' => wfTimestamp( TS_MW, $srcObj->last_modified ),
466 'size' => $srcObj->content_length,
467 'sha1' => $srcObj->metadata['Sha1base36']
468 );
469 } catch ( NoSuchContainerException $e ) {
470 } catch ( NoSuchObjectException $e ) {
471 } catch ( InvalidResponseException $e ) {
472 $stat = null;
473 } catch ( Exception $e ) { // some other exception?
474 $stat = null;
475 $this->logException( $e, __METHOD__, $params );
476 }
477
478 return $stat;
479 }
480
481 /**
482 * Fill in any missing object metadata and save it to Swift
483 *
484 * @param $obj CF_Object
485 * @param $path string Storage path to object
486 * @return bool Success
487 * @throws Exception cloudfiles exceptions
488 */
489 protected function addMissingMetadata( CF_Object $obj, $path ) {
490 if ( isset( $obj->metadata['Sha1base36'] ) ) {
491 return true; // nothing to do
492 }
493 $status = Status::newGood();
494 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
495 if ( $status->isOK() ) {
496 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
497 if ( $tmpFile ) {
498 $hash = $tmpFile->getSha1Base36();
499 if ( $hash !== false ) {
500 $obj->metadata['Sha1base36'] = $hash;
501 $obj->sync_metadata(); // save to Swift
502 return true; // success
503 }
504 }
505 }
506 $obj->metadata['Sha1base36'] = false;
507 return false; // failed
508 }
509
510 /**
511 * @see FileBackend::getFileContents()
512 * @return bool|null|string
513 */
514 public function getFileContents( array $params ) {
515 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
516 if ( $srcRel === null ) {
517 return false; // invalid storage path
518 }
519
520 if ( !$this->fileExists( $params ) ) {
521 return null;
522 }
523
524 $data = false;
525 try {
526 $sContObj = $this->getContainer( $srcCont );
527 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD request
528 $data = $obj->read( $this->headersFromParams( $params ) );
529 } catch ( NoSuchContainerException $e ) {
530 } catch ( InvalidResponseException $e ) {
531 } catch ( Exception $e ) { // some other exception?
532 $this->logException( $e, __METHOD__, $params );
533 }
534
535 return $data;
536 }
537
538 /**
539 * @see FileBackendStore::doDirectoryExists()
540 * @return bool|null
541 */
542 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
543 try {
544 $container = $this->getContainer( $fullCont );
545 $prefix = ( $dir == '' ) ? null : "{$dir}/";
546 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
547 } catch ( NoSuchContainerException $e ) {
548 return false;
549 } catch ( InvalidResponseException $e ) {
550 } catch ( Exception $e ) { // some other exception?
551 $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
552 }
553
554 return null; // error
555 }
556
557 /**
558 * @see FileBackendStore::getDirectoryListInternal()
559 * @return SwiftFileBackendDirList
560 */
561 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
562 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
563 }
564
565 /**
566 * @see FileBackendStore::getFileListInternal()
567 * @return SwiftFileBackendFileList
568 */
569 public function getFileListInternal( $fullCont, $dir, array $params ) {
570 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
571 }
572
573 /**
574 * Do not call this function outside of SwiftFileBackendFileList
575 *
576 * @param $fullCont string Resolved container name
577 * @param $dir string Resolved storage directory with no trailing slash
578 * @param $after string|null Storage path of file to list items after
579 * @param $limit integer Max number of items to list
580 * @param $params Array Includes flag for 'topOnly'
581 * @return Array List of relative paths of dirs directly under $dir
582 */
583 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
584 $dirs = array();
585
586 try {
587 $container = $this->getContainer( $fullCont );
588 $prefix = ( $dir == '' ) ? null : "{$dir}/";
589 // Non-recursive: only list dirs right under $dir
590 if ( !empty( $params['topOnly'] ) ) {
591 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
592 foreach ( $objects as $object ) { // files and dirs
593 if ( substr( $object, -1 ) === '/' ) {
594 $dirs[] = $object; // directories end in '/'
595 }
596 $after = $object; // update last item
597 }
598 // Recursive: list all dirs under $dir and its subdirs
599 } else {
600 // Get directory from last item of prior page
601 $lastDir = $this->getParentDir( $after ); // must be first page
602 $objects = $container->list_objects( $limit, $after, $prefix );
603 foreach ( $objects as $object ) { // files
604 $objectDir = $this->getParentDir( $object ); // directory of object
605 if ( $objectDir !== false ) { // file has a parent dir
606 // Swift stores paths in UTF-8, using binary sorting.
607 // See function "create_container_table" in common/db.py.
608 // If a directory is not "greater" than the last one,
609 // then it was already listed by the calling iterator.
610 if ( $objectDir > $lastDir ) {
611 $pDir = $objectDir;
612 do { // add dir and all its parent dirs
613 $dirs[] = "{$pDir}/";
614 $pDir = $this->getParentDir( $pDir );
615 } while ( $pDir !== false // sanity
616 && $pDir > $lastDir // not done already
617 && strlen( $pDir ) > strlen( $dir ) // within $dir
618 );
619 }
620 $lastDir = $objectDir;
621 }
622 $after = $object; // update last item
623 }
624 }
625 } catch ( NoSuchContainerException $e ) {
626 } catch ( InvalidResponseException $e ) {
627 } catch ( Exception $e ) { // some other exception?
628 $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
629 }
630
631 return $dirs;
632 }
633
634 protected function getParentDir( $path ) {
635 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
636 }
637
638 /**
639 * Do not call this function outside of SwiftFileBackendFileList
640 *
641 * @param $fullCont string Resolved container name
642 * @param $dir string Resolved storage directory with no trailing slash
643 * @param $after string|null Storage path of file to list items after
644 * @param $limit integer Max number of items to list
645 * @param $params Array Includes flag for 'topOnly'
646 * @return Array List of relative paths of files under $dir
647 */
648 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
649 $files = array();
650
651 try {
652 $container = $this->getContainer( $fullCont );
653 $prefix = ( $dir == '' ) ? null : "{$dir}/";
654 // Non-recursive: only list files right under $dir
655 if ( !empty( $params['topOnly'] ) ) { // files and dirs
656 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
657 foreach ( $objects as $object ) {
658 if ( substr( $object, -1 ) !== '/' ) {
659 $files[] = $object; // directories end in '/'
660 }
661 }
662 // Recursive: list all files under $dir and its subdirs
663 } else { // files
664 $files = $container->list_objects( $limit, $after, $prefix );
665 }
666 $after = end( $files ); // update last item
667 reset( $files ); // reset pointer
668 } catch ( NoSuchContainerException $e ) {
669 } catch ( InvalidResponseException $e ) {
670 } catch ( Exception $e ) { // some other exception?
671 $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
672 }
673
674 return $files;
675 }
676
677 /**
678 * @see FileBackendStore::doGetFileSha1base36()
679 * @return bool
680 */
681 protected function doGetFileSha1base36( array $params ) {
682 $stat = $this->getFileStat( $params );
683 if ( $stat ) {
684 return $stat['sha1'];
685 } else {
686 return false;
687 }
688 }
689
690 /**
691 * @see FileBackendStore::doStreamFile()
692 * @return Status
693 */
694 protected function doStreamFile( array $params ) {
695 $status = Status::newGood();
696
697 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
698 if ( $srcRel === null ) {
699 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
700 }
701
702 try {
703 $cont = $this->getContainer( $srcCont );
704 } catch ( NoSuchContainerException $e ) {
705 $status->fatal( 'backend-fail-stream', $params['src'] );
706 return $status;
707 } catch ( InvalidResponseException $e ) {
708 $status->fatal( 'backend-fail-connect', $this->name );
709 return $status;
710 } catch ( Exception $e ) { // some other exception?
711 $status->fatal( 'backend-fail-stream', $params['src'] );
712 $this->logException( $e, __METHOD__, $params );
713 return $status;
714 }
715
716 try {
717 $output = fopen( 'php://output', 'wb' );
718 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD request
719 $obj->stream( $output, $this->headersFromParams( $params ) );
720 } catch ( InvalidResponseException $e ) { // 404? connection problem?
721 $status->fatal( 'backend-fail-stream', $params['src'] );
722 } catch ( Exception $e ) { // some other exception?
723 $status->fatal( 'backend-fail-stream', $params['src'] );
724 $this->logException( $e, __METHOD__, $params );
725 }
726
727 return $status;
728 }
729
730 /**
731 * @see FileBackendStore::getLocalCopy()
732 * @return null|TempFSFile
733 */
734 public function getLocalCopy( array $params ) {
735 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
736 if ( $srcRel === null ) {
737 return null;
738 }
739
740 if ( !$this->fileExists( $params ) ) {
741 return null;
742 }
743
744 $tmpFile = null;
745 try {
746 $sContObj = $this->getContainer( $srcCont );
747 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
748 // Get source file extension
749 $ext = FileBackend::extensionFromPath( $srcRel );
750 // Create a new temporary file...
751 $tmpFile = TempFSFile::factory( wfBaseName( $srcRel ) . '_', $ext );
752 if ( $tmpFile ) {
753 $handle = fopen( $tmpFile->getPath(), 'wb' );
754 if ( $handle ) {
755 $obj->stream( $handle, $this->headersFromParams( $params ) );
756 fclose( $handle );
757 } else {
758 $tmpFile = null; // couldn't open temp file
759 }
760 }
761 } catch ( NoSuchContainerException $e ) {
762 $tmpFile = null;
763 } catch ( InvalidResponseException $e ) {
764 $tmpFile = null;
765 } catch ( Exception $e ) { // some other exception?
766 $tmpFile = null;
767 $this->logException( $e, __METHOD__, $params );
768 }
769
770 return $tmpFile;
771 }
772
773 /**
774 * Get headers to send to Swift when reading a file based
775 * on a FileBackend params array, e.g. that of getLocalCopy().
776 * $params is currently only checked for a 'latest' flag.
777 *
778 * @param $params Array
779 * @return Array
780 */
781 protected function headersFromParams( array $params ) {
782 $hdrs = array();
783 if ( !empty( $params['latest'] ) ) {
784 $hdrs[] = 'X-Newest: true';
785 }
786 return $hdrs;
787 }
788
789 /**
790 * Set read/write permissions for a Swift container
791 *
792 * @param $contObj CF_Container Swift container
793 * @param $readGrps Array Swift users who can read (account:user)
794 * @param $writeGrps Array Swift users who can write (account:user)
795 * @return Status
796 */
797 protected function setContainerAccess(
798 CF_Container $contObj, array $readGrps, array $writeGrps
799 ) {
800 $creds = $contObj->cfs_auth->export_credentials();
801
802 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
803
804 // Note: 10 second timeout consistent with php-cloudfiles
805 $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
806 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
807 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
808 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
809
810 return $req->execute(); // should return 204
811 }
812
813 /**
814 * Get a connection to the Swift proxy
815 *
816 * @return CF_Connection|bool False on failure
817 * @throws InvalidResponseException
818 */
819 protected function getConnection() {
820 if ( $this->conn === false ) {
821 throw new InvalidResponseException; // failed last attempt
822 }
823 // Session keys expire after a while, so we renew them periodically
824 if ( $this->conn && ( time() - $this->connStarted ) > $this->authTTL ) {
825 $this->conn->close(); // close active cURL connections
826 $this->conn = null;
827 }
828 // Authenticate with proxy and get a session key...
829 if ( $this->conn === null ) {
830 $this->connContainers = array();
831 try {
832 $this->auth->authenticate();
833 $this->conn = new CF_Connection( $this->auth );
834 $this->connStarted = time();
835 } catch ( AuthenticationException $e ) {
836 $this->conn = false; // don't keep re-trying
837 } catch ( InvalidResponseException $e ) {
838 $this->conn = false; // don't keep re-trying
839 }
840 }
841 if ( !$this->conn ) {
842 throw new InvalidResponseException; // auth/connection problem
843 }
844 return $this->conn;
845 }
846
847 /**
848 * @see FileBackendStore::doClearCache()
849 */
850 protected function doClearCache( array $paths = null ) {
851 $this->connContainers = array(); // clear container object cache
852 }
853
854 /**
855 * Get a Swift container object, possibly from process cache.
856 * Use $reCache if the file count or byte count is needed.
857 *
858 * @param $container string Container name
859 * @param $reCache bool Refresh the process cache
860 * @return CF_Container
861 */
862 protected function getContainer( $container, $reCache = false ) {
863 $conn = $this->getConnection(); // Swift proxy connection
864 if ( $reCache ) {
865 unset( $this->connContainers[$container] ); // purge cache
866 }
867 if ( !isset( $this->connContainers[$container] ) ) {
868 $contObj = $conn->get_container( $container );
869 // NoSuchContainerException not thrown: container must exist
870 if ( count( $this->connContainers ) >= $this->maxContCacheSize ) { // trim cache?
871 reset( $this->connContainers );
872 $key = key( $this->connContainers );
873 unset( $this->connContainers[$key] );
874 }
875 $this->connContainers[$container] = $contObj; // cache it
876 }
877 return $this->connContainers[$container];
878 }
879
880 /**
881 * Create a Swift container
882 *
883 * @param $container string Container name
884 * @return CF_Container
885 */
886 protected function createContainer( $container ) {
887 $conn = $this->getConnection(); // Swift proxy connection
888 $contObj = $conn->create_container( $container );
889 $this->connContainers[$container] = $contObj; // cache it
890 return $contObj;
891 }
892
893 /**
894 * Delete a Swift container
895 *
896 * @param $container string Container name
897 * @return void
898 */
899 protected function deleteContainer( $container ) {
900 $conn = $this->getConnection(); // Swift proxy connection
901 $conn->delete_container( $container );
902 unset( $this->connContainers[$container] ); // purge cache
903 }
904
905 /**
906 * Log an unexpected exception for this backend
907 *
908 * @param $e Exception
909 * @param $func string
910 * @param $params Array
911 * @return void
912 */
913 protected function logException( Exception $e, $func, array $params ) {
914 wfDebugLog( 'SwiftBackend',
915 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
916 ( $e instanceof InvalidResponseException
917 ? ": {$e->getMessage()}"
918 : ""
919 )
920 );
921 }
922 }
923
924 /**
925 * SwiftFileBackend helper class to page through listings.
926 * Swift also has a listing limit of 10,000 objects for sanity.
927 * Do not use this class from places outside SwiftFileBackend.
928 *
929 * @ingroup FileBackend
930 */
931 abstract class SwiftFileBackendList implements Iterator {
932 /** @var Array */
933 protected $bufferIter = array();
934 protected $bufferAfter = null; // string; list items *after* this path
935 protected $pos = 0; // integer
936 /** @var Array */
937 protected $params = array();
938
939 /** @var SwiftFileBackend */
940 protected $backend;
941 protected $container; // string; container name
942 protected $dir; // string; storage directory
943 protected $suffixStart; // integer
944
945 const PAGE_SIZE = 5000; // file listing buffer size
946
947 /**
948 * @param $backend SwiftFileBackend
949 * @param $fullCont string Resolved container name
950 * @param $dir string Resolved directory relative to container
951 * @param $params Array
952 */
953 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
954 $this->backend = $backend;
955 $this->container = $fullCont;
956 $this->dir = $dir;
957 if ( substr( $this->dir, -1 ) === '/' ) {
958 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
959 }
960 if ( $this->dir == '' ) { // whole container
961 $this->suffixStart = 0;
962 } else { // dir within container
963 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
964 }
965 $this->params = $params;
966 }
967
968 /**
969 * @see Iterator::key()
970 * @return integer
971 */
972 public function key() {
973 return $this->pos;
974 }
975
976 /**
977 * @see Iterator::next()
978 * @return void
979 */
980 public function next() {
981 // Advance to the next file in the page
982 next( $this->bufferIter );
983 ++$this->pos;
984 // Check if there are no files left in this page and
985 // advance to the next page if this page was not empty.
986 if ( !$this->valid() && count( $this->bufferIter ) ) {
987 $this->bufferIter = $this->pageFromList(
988 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
989 ); // updates $this->bufferAfter
990 }
991 }
992
993 /**
994 * @see Iterator::rewind()
995 * @return void
996 */
997 public function rewind() {
998 $this->pos = 0;
999 $this->bufferAfter = null;
1000 $this->bufferIter = $this->pageFromList(
1001 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1002 ); // updates $this->bufferAfter
1003 }
1004
1005 /**
1006 * @see Iterator::valid()
1007 * @return bool
1008 */
1009 public function valid() {
1010 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1011 }
1012
1013 /**
1014 * Get the given list portion (page)
1015 *
1016 * @param $container string Resolved container name
1017 * @param $dir string Resolved path relative to container
1018 * @param $after string|null
1019 * @param $limit integer
1020 * @param $params Array
1021 * @return Traversable|Array|null
1022 */
1023 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1024 }
1025
1026 /**
1027 * Iterator for listing directories
1028 */
1029 class SwiftFileBackendDirList extends SwiftFileBackendList {
1030 /**
1031 * @see Iterator::current()
1032 * @return string|bool String (relative path) or false
1033 */
1034 public function current() {
1035 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1036 }
1037
1038 /**
1039 * @see SwiftFileBackendList::pageFromList()
1040 * @return Array
1041 */
1042 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1043 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1044 }
1045 }
1046
1047 /**
1048 * Iterator for listing regular files
1049 */
1050 class SwiftFileBackendFileList extends SwiftFileBackendList {
1051 /**
1052 * @see Iterator::current()
1053 * @return string|bool String (relative path) or false
1054 */
1055 public function current() {
1056 return substr( current( $this->bufferIter ), $this->suffixStart );
1057 }
1058
1059 /**
1060 * @see SwiftFileBackendList::pageFromList()
1061 * @return Array
1062 */
1063 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1064 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1065 }
1066 }