(bug 19195) Make user IDs more readily available with the API
[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::getFileListInternal()
540 * @return SwiftFileBackendFileList
541 */
542 public function getFileListInternal( $fullCont, $dir, array $params ) {
543 return new SwiftFileBackendFileList( $this, $fullCont, $dir );
544 }
545
546 /**
547 * Do not call this function outside of SwiftFileBackendFileList
548 *
549 * @param $fullCont string Resolved container name
550 * @param $dir string Resolved storage directory with no trailing slash
551 * @param $after string Storage path of file to list items after
552 * @param $limit integer Max number of items to list
553 * @return Array
554 */
555 public function getFileListPageInternal( $fullCont, $dir, $after, $limit ) {
556 $files = array();
557
558 try {
559 $container = $this->getContainer( $fullCont );
560 $prefix = ( $dir == '' ) ? null : "{$dir}/";
561 $files = $container->list_objects( $limit, $after, $prefix );
562 } catch ( NoSuchContainerException $e ) {
563 } catch ( InvalidResponseException $e ) {
564 } catch ( Exception $e ) { // some other exception?
565 $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
566 }
567
568 return $files;
569 }
570
571 /**
572 * @see FileBackendStore::doGetFileSha1base36()
573 * @return bool
574 */
575 protected function doGetFileSha1base36( array $params ) {
576 $stat = $this->getFileStat( $params );
577 if ( $stat ) {
578 return $stat['sha1'];
579 } else {
580 return false;
581 }
582 }
583
584 /**
585 * @see FileBackendStore::doStreamFile()
586 * @return Status
587 */
588 protected function doStreamFile( array $params ) {
589 $status = Status::newGood();
590
591 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
592 if ( $srcRel === null ) {
593 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
594 }
595
596 try {
597 $cont = $this->getContainer( $srcCont );
598 } catch ( NoSuchContainerException $e ) {
599 $status->fatal( 'backend-fail-stream', $params['src'] );
600 return $status;
601 } catch ( InvalidResponseException $e ) {
602 $status->fatal( 'backend-fail-connect', $this->name );
603 return $status;
604 } catch ( Exception $e ) { // some other exception?
605 $status->fatal( 'backend-fail-stream', $params['src'] );
606 $this->logException( $e, __METHOD__, $params );
607 return $status;
608 }
609
610 try {
611 $output = fopen( 'php://output', 'wb' );
612 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD request
613 $obj->stream( $output, $this->headersFromParams( $params ) );
614 } catch ( InvalidResponseException $e ) { // 404? connection problem?
615 $status->fatal( 'backend-fail-stream', $params['src'] );
616 } catch ( Exception $e ) { // some other exception?
617 $status->fatal( 'backend-fail-stream', $params['src'] );
618 $this->logException( $e, __METHOD__, $params );
619 }
620
621 return $status;
622 }
623
624 /**
625 * @see FileBackendStore::getLocalCopy()
626 * @return null|TempFSFile
627 */
628 public function getLocalCopy( array $params ) {
629 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
630 if ( $srcRel === null ) {
631 return null;
632 }
633
634 if ( !$this->fileExists( $params ) ) {
635 return null;
636 }
637
638 $tmpFile = null;
639 try {
640 $sContObj = $this->getContainer( $srcCont );
641 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
642 // Get source file extension
643 $ext = FileBackend::extensionFromPath( $srcRel );
644 // Create a new temporary file...
645 $tmpFile = TempFSFile::factory( wfBaseName( $srcRel ) . '_', $ext );
646 if ( $tmpFile ) {
647 $handle = fopen( $tmpFile->getPath(), 'wb' );
648 if ( $handle ) {
649 $obj->stream( $handle, $this->headersFromParams( $params ) );
650 fclose( $handle );
651 } else {
652 $tmpFile = null; // couldn't open temp file
653 }
654 }
655 } catch ( NoSuchContainerException $e ) {
656 $tmpFile = null;
657 } catch ( InvalidResponseException $e ) {
658 $tmpFile = null;
659 } catch ( Exception $e ) { // some other exception?
660 $tmpFile = null;
661 $this->logException( $e, __METHOD__, $params );
662 }
663
664 return $tmpFile;
665 }
666
667 /**
668 * Get headers to send to Swift when reading a file based
669 * on a FileBackend params array, e.g. that of getLocalCopy().
670 * $params is currently only checked for a 'latest' flag.
671 *
672 * @param $params Array
673 * @return Array
674 */
675 protected function headersFromParams( array $params ) {
676 $hdrs = array();
677 if ( !empty( $params['latest'] ) ) {
678 $hdrs[] = 'X-Newest: true';
679 }
680 return $hdrs;
681 }
682
683 /**
684 * Set read/write permissions for a Swift container
685 *
686 * @param $contObj CF_Container Swift container
687 * @param $readGrps Array Swift users who can read (account:user)
688 * @param $writeGrps Array Swift users who can write (account:user)
689 * @return Status
690 */
691 protected function setContainerAccess(
692 CF_Container $contObj, array $readGrps, array $writeGrps
693 ) {
694 $creds = $contObj->cfs_auth->export_credentials();
695
696 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
697
698 // Note: 10 second timeout consistent with php-cloudfiles
699 $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
700 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
701 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
702 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
703
704 return $req->execute(); // should return 204
705 }
706
707 /**
708 * Get a connection to the Swift proxy
709 *
710 * @return CF_Connection|bool False on failure
711 * @throws InvalidResponseException
712 */
713 protected function getConnection() {
714 if ( $this->conn === false ) {
715 throw new InvalidResponseException; // failed last attempt
716 }
717 // Session keys expire after a while, so we renew them periodically
718 if ( $this->conn && ( time() - $this->connStarted ) > $this->authTTL ) {
719 $this->conn->close(); // close active cURL connections
720 $this->conn = null;
721 }
722 // Authenticate with proxy and get a session key...
723 if ( $this->conn === null ) {
724 $this->connContainers = array();
725 try {
726 $this->auth->authenticate();
727 $this->conn = new CF_Connection( $this->auth );
728 $this->connStarted = time();
729 } catch ( AuthenticationException $e ) {
730 $this->conn = false; // don't keep re-trying
731 } catch ( InvalidResponseException $e ) {
732 $this->conn = false; // don't keep re-trying
733 }
734 }
735 if ( !$this->conn ) {
736 throw new InvalidResponseException; // auth/connection problem
737 }
738 return $this->conn;
739 }
740
741 /**
742 * @see FileBackendStore::doClearCache()
743 */
744 protected function doClearCache( array $paths = null ) {
745 $this->connContainers = array(); // clear container object cache
746 }
747
748 /**
749 * Get a Swift container object, possibly from process cache.
750 * Use $reCache if the file count or byte count is needed.
751 *
752 * @param $container string Container name
753 * @param $reCache bool Refresh the process cache
754 * @return CF_Container
755 */
756 protected function getContainer( $container, $reCache = false ) {
757 $conn = $this->getConnection(); // Swift proxy connection
758 if ( $reCache ) {
759 unset( $this->connContainers[$container] ); // purge cache
760 }
761 if ( !isset( $this->connContainers[$container] ) ) {
762 $contObj = $conn->get_container( $container );
763 // NoSuchContainerException not thrown: container must exist
764 if ( count( $this->connContainers ) >= $this->maxContCacheSize ) { // trim cache?
765 reset( $this->connContainers );
766 $key = key( $this->connContainers );
767 unset( $this->connContainers[$key] );
768 }
769 $this->connContainers[$container] = $contObj; // cache it
770 }
771 return $this->connContainers[$container];
772 }
773
774 /**
775 * Create a Swift container
776 *
777 * @param $container string Container name
778 * @return CF_Container
779 */
780 protected function createContainer( $container ) {
781 $conn = $this->getConnection(); // Swift proxy connection
782 $contObj = $conn->create_container( $container );
783 $this->connContainers[$container] = $contObj; // cache it
784 return $contObj;
785 }
786
787 /**
788 * Delete a Swift container
789 *
790 * @param $container string Container name
791 * @return void
792 */
793 protected function deleteContainer( $container ) {
794 $conn = $this->getConnection(); // Swift proxy connection
795 $conn->delete_container( $container );
796 unset( $this->connContainers[$container] ); // purge cache
797 }
798
799 /**
800 * Log an unexpected exception for this backend
801 *
802 * @param $e Exception
803 * @param $func string
804 * @param $params Array
805 * @return void
806 */
807 protected function logException( Exception $e, $func, array $params ) {
808 wfDebugLog( 'SwiftBackend',
809 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
810 ( $e instanceof InvalidResponseException
811 ? ": {$e->getMessage()}"
812 : ""
813 )
814 );
815 }
816 }
817
818 /**
819 * SwiftFileBackend helper class to page through object listings.
820 * Swift also has a listing limit of 10,000 objects for sanity.
821 * Do not use this class from places outside SwiftFileBackend.
822 *
823 * @ingroup FileBackend
824 */
825 class SwiftFileBackendFileList implements Iterator {
826 /** @var Array */
827 protected $bufferIter = array();
828 protected $bufferAfter = null; // string; list items *after* this path
829 protected $pos = 0; // integer
830
831 /** @var SwiftFileBackend */
832 protected $backend;
833 protected $container; //
834 protected $dir; // string storage directory
835 protected $suffixStart; // integer
836
837 const PAGE_SIZE = 5000; // file listing buffer size
838
839 /**
840 * @param $backend SwiftFileBackend
841 * @param $fullCont string Resolved container name
842 * @param $dir string Resolved directory relative to container
843 */
844 public function __construct( SwiftFileBackend $backend, $fullCont, $dir ) {
845 $this->backend = $backend;
846 $this->container = $fullCont;
847 $this->dir = $dir;
848 if ( substr( $this->dir, -1 ) === '/' ) {
849 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
850 }
851 if ( $this->dir == '' ) { // whole container
852 $this->suffixStart = 0;
853 } else { // dir within container
854 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
855 }
856 }
857
858 /**
859 * @see Iterator::current()
860 * @return string|bool String or false
861 */
862 public function current() {
863 return substr( current( $this->bufferIter ), $this->suffixStart );
864 }
865
866 /**
867 * @see Iterator::key()
868 * @return integer
869 */
870 public function key() {
871 return $this->pos;
872 }
873
874 /**
875 * @see Iterator::next()
876 * @return void
877 */
878 public function next() {
879 // Advance to the next file in the page
880 next( $this->bufferIter );
881 ++$this->pos;
882 // Check if there are no files left in this page and
883 // advance to the next page if this page was not empty.
884 if ( !$this->valid() && count( $this->bufferIter ) ) {
885 $this->bufferAfter = end( $this->bufferIter );
886 $this->bufferIter = $this->backend->getFileListPageInternal(
887 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE
888 );
889 }
890 }
891
892 /**
893 * @see Iterator::rewind()
894 * @return void
895 */
896 public function rewind() {
897 $this->pos = 0;
898 $this->bufferAfter = null;
899 $this->bufferIter = $this->backend->getFileListPageInternal(
900 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE
901 );
902 }
903
904 /**
905 * @see Iterator::valid()
906 * @return bool
907 */
908 public function valid() {
909 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
910 }
911 }