MediaWiki  REL1_24
copyFileBackend.php
Go to the documentation of this file.
00001 <?php
00024 require_once __DIR__ . '/Maintenance.php';
00025 
00037 class CopyFileBackend extends Maintenance {
00039     protected $statCache = null;
00040 
00041     public function __construct() {
00042         parent::__construct();
00043         $this->mDescription = "Copy files in one backend to another.";
00044         $this->addOption( 'src', 'Backend containing the source files', true, true );
00045         $this->addOption( 'dst', 'Backend where files should be copied to', true, true );
00046         $this->addOption( 'containers', 'Pipe separated list of containers', true, true );
00047         $this->addOption( 'subdir', 'Only do items in this child directory', false, true );
00048         $this->addOption( 'ratefile', 'File to check periodically for batch size', false, true );
00049         $this->addOption( 'prestat', 'Stat the destination files first (try to use listings)' );
00050         $this->addOption( 'skiphash', 'Skip SHA-1 sync checks for files' );
00051         $this->addOption( 'missingonly', 'Only copy files missing from destination listing' );
00052         $this->addOption( 'syncviadelete', 'Delete destination files missing from source listing' );
00053         $this->addOption( 'utf8only', 'Skip source files that do not have valid UTF-8 names' );
00054         $this->setBatchSize( 50 );
00055     }
00056 
00057     public function execute() {
00058         $src = FileBackendGroup::singleton()->get( $this->getOption( 'src' ) );
00059         $dst = FileBackendGroup::singleton()->get( $this->getOption( 'dst' ) );
00060         $containers = explode( '|', $this->getOption( 'containers' ) );
00061         $subDir = rtrim( $this->getOption( 'subdir', '' ), '/' );
00062 
00063         $rateFile = $this->getOption( 'ratefile' );
00064 
00065         if ( $this->hasOption( 'utf8only' ) && !extension_loaded( 'mbstring' ) ) {
00066             $this->error( "Cannot check for UTF-8, mbstring extension missing.", 1 ); // die
00067         }
00068 
00069         foreach ( $containers as $container ) {
00070             if ( $subDir != '' ) {
00071                 $backendRel = "$container/$subDir";
00072                 $this->output( "Doing container '$container', directory '$subDir'...\n" );
00073             } else {
00074                 $backendRel = $container;
00075                 $this->output( "Doing container '$container'...\n" );
00076             }
00077 
00078             if ( $this->hasOption( 'missingonly' ) ) {
00079                 $this->output( "\tBuilding list of missing files..." );
00080                 $srcPathsRel = $this->getListingDiffRel( $src, $dst, $backendRel );
00081                 $this->output( count( $srcPathsRel ) . " file(s) need to be copied.\n" );
00082             } else {
00083                 $srcPathsRel = $src->getFileList( array(
00084                     'dir' => $src->getRootStoragePath() . "/$backendRel",
00085                     'adviseStat' => true // avoid HEADs
00086                 ) );
00087                 if ( $srcPathsRel === null ) {
00088                     $this->error( "Could not list files in $container.", 1 ); // die
00089                 }
00090             }
00091 
00092             if ( $this->getOption( 'prestat' ) && !$this->hasOption( 'missingonly' ) ) {
00093                 // Build the stat cache for the destination files
00094                 $this->output( "\tBuilding destination stat cache..." );
00095                 $dstPathsRel = $dst->getFileList( array(
00096                     'dir' => $dst->getRootStoragePath() . "/$backendRel",
00097                     'adviseStat' => true // avoid HEADs
00098                 ) );
00099                 if ( $dstPathsRel === null ) {
00100                     $this->error( "Could not list files in $container.", 1 ); // die
00101                 }
00102                 $this->statCache = array();
00103                 foreach ( $dstPathsRel as $dstPathRel ) {
00104                     $path = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
00105                     $this->statCache[sha1( $path )] = $dst->getFileStat( array( 'src' => $path ) );
00106                 }
00107                 $this->output( "done [" . count( $this->statCache ) . " file(s)]\n" );
00108             }
00109 
00110             $this->output( "\tCopying file(s)...\n" );
00111             $count = 0;
00112             $batchPaths = array();
00113             foreach ( $srcPathsRel as $srcPathRel ) {
00114                 // Check up on the rate file periodically to adjust the concurrency
00115                 if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
00116                     $this->mBatchSize = max( 1, (int)file_get_contents( $rateFile ) );
00117                     $this->output( "\tBatch size is now {$this->mBatchSize}.\n" );
00118                 }
00119                 $batchPaths[$srcPathRel] = 1; // remove duplicates
00120                 if ( count( $batchPaths ) >= $this->mBatchSize ) {
00121                     $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
00122                     $batchPaths = array(); // done
00123                 }
00124                 ++$count;
00125             }
00126             if ( count( $batchPaths ) ) { // left-overs
00127                 $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
00128                 $batchPaths = array(); // done
00129             }
00130             $this->output( "\tCopied $count file(s).\n" );
00131 
00132             if ( $this->hasOption( 'syncviadelete' ) ) {
00133                 $this->output( "\tBuilding list of excess destination files..." );
00134                 $delPathsRel = $this->getListingDiffRel( $dst, $src, $backendRel );
00135                 $this->output( count( $delPathsRel ) . " file(s) need to be deleted.\n" );
00136 
00137                 $this->output( "\tDeleting file(s)...\n" );
00138                 $count = 0;
00139                 $batchPaths = array();
00140                 foreach ( $delPathsRel as $delPathRel ) {
00141                     // Check up on the rate file periodically to adjust the concurrency
00142                     if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
00143                         $this->mBatchSize = max( 1, (int)file_get_contents( $rateFile ) );
00144                         $this->output( "\tBatch size is now {$this->mBatchSize}.\n" );
00145                     }
00146                     $batchPaths[$delPathRel] = 1; // remove duplicates
00147                     if ( count( $batchPaths ) >= $this->mBatchSize ) {
00148                         $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
00149                         $batchPaths = array(); // done
00150                     }
00151                     ++$count;
00152                 }
00153                 if ( count( $batchPaths ) ) { // left-overs
00154                     $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
00155                     $batchPaths = array(); // done
00156                 }
00157 
00158                 $this->output( "\tDeleted $count file(s).\n" );
00159             }
00160 
00161             if ( $subDir != '' ) {
00162                 $this->output( "Finished container '$container', directory '$subDir'.\n" );
00163             } else {
00164                 $this->output( "Finished container '$container'.\n" );
00165             }
00166         }
00167 
00168         $this->output( "Done.\n" );
00169     }
00170 
00177     protected function getListingDiffRel( FileBackend $src, FileBackend $dst, $backendRel ) {
00178         $srcPathsRel = $src->getFileList( array(
00179             'dir' => $src->getRootStoragePath() . "/$backendRel" ) );
00180         if ( $srcPathsRel === null ) {
00181             $this->error( "Could not list files in source container.", 1 ); // die
00182         }
00183         $dstPathsRel = $dst->getFileList( array(
00184             'dir' => $dst->getRootStoragePath() . "/$backendRel" ) );
00185         if ( $dstPathsRel === null ) {
00186             $this->error( "Could not list files in destination container.", 1 ); // die
00187         }
00188         // Get the list of destination files
00189         $relFilesDstSha1 = array();
00190         foreach ( $dstPathsRel as $dstPathRel ) {
00191             $relFilesDstSha1[sha1( $dstPathRel )] = 1;
00192         }
00193         unset( $dstPathsRel ); // free
00194         // Get the list of missing files
00195         $missingPathsRel = array();
00196         foreach ( $srcPathsRel as $srcPathRel ) {
00197             if ( !isset( $relFilesDstSha1[sha1( $srcPathRel )] ) ) {
00198                 $missingPathsRel[] = $srcPathRel;
00199             }
00200         }
00201         unset( $srcPathsRel ); // free
00202 
00203         return $missingPathsRel;
00204     }
00205 
00213     protected function copyFileBatch(
00214         array $srcPathsRel, $backendRel, FileBackend $src, FileBackend $dst
00215     ) {
00216         $ops = array();
00217         $fsFiles = array();
00218         $copiedRel = array(); // for output message
00219         $wikiId = $src->getWikiId();
00220 
00221         // Download the batch of source files into backend cache...
00222         if ( $this->hasOption( 'missingonly' ) ) {
00223             $srcPaths = array();
00224             foreach ( $srcPathsRel as $srcPathRel ) {
00225                 $srcPaths[] = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
00226             }
00227             $t_start = microtime( true );
00228             $fsFiles = $src->getLocalReferenceMulti( array( 'srcs' => $srcPaths, 'latest' => 1 ) );
00229             $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
00230             $this->output( "\n\tDownloaded these file(s) [{$ellapsed_ms}ms]:\n\t" .
00231                 implode( "\n\t", $srcPaths ) . "\n\n" );
00232         }
00233 
00234         // Determine what files need to be copied over...
00235         foreach ( $srcPathsRel as $srcPathRel ) {
00236             $srcPath = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
00237             $dstPath = $dst->getRootStoragePath() . "/$backendRel/$srcPathRel";
00238             if ( $this->hasOption( 'utf8only' ) && !mb_check_encoding( $srcPath, 'UTF-8' ) ) {
00239                 $this->error( "$wikiId: Detected illegal (non-UTF8) path for $srcPath." );
00240                 continue;
00241             } elseif ( !$this->hasOption( 'missingonly' )
00242                 && $this->filesAreSame( $src, $dst, $srcPath, $dstPath )
00243             ) {
00244                 $this->output( "\tAlready have $srcPathRel.\n" );
00245                 continue; // assume already copied...
00246             }
00247             $fsFile = array_key_exists( $srcPath, $fsFiles )
00248                 ? $fsFiles[$srcPath]
00249                 : $src->getLocalReference( array( 'src' => $srcPath, 'latest' => 1 ) );
00250             if ( !$fsFile ) {
00251                 $src->clearCache( array( $srcPath ) );
00252                 if ( $src->fileExists( array( 'src' => $srcPath, 'latest' => 1 ) ) === false ) {
00253                     $this->error( "$wikiId: File '$srcPath' was listed but does not exist." );
00254                 } else {
00255                     $this->error( "$wikiId: Could not get local copy of $srcPath." );
00256                 }
00257                 continue;
00258             } elseif ( !$fsFile->exists() ) {
00259                 // FSFileBackends just return the path for getLocalReference() and paths with
00260                 // illegal slashes may get normalized to a different path. This can cause the
00261                 // local reference to not exist...skip these broken files.
00262                 $this->error( "$wikiId: Detected possible illegal path for $srcPath." );
00263                 continue;
00264             }
00265             $fsFiles[] = $fsFile; // keep TempFSFile objects alive as needed
00266             // Note: prepare() is usually fast for key/value backends
00267             $status = $dst->prepare( array( 'dir' => dirname( $dstPath ), 'bypassReadOnly' => 1 ) );
00268             if ( !$status->isOK() ) {
00269                 $this->error( print_r( $status->getErrorsArray(), true ) );
00270                 $this->error( "$wikiId: Could not copy $srcPath to $dstPath.", 1 ); // die
00271             }
00272             $ops[] = array( 'op' => 'store',
00273                 'src' => $fsFile->getPath(), 'dst' => $dstPath, 'overwrite' => 1 );
00274             $copiedRel[] = $srcPathRel;
00275         }
00276 
00277         // Copy in the batch of source files...
00278         $t_start = microtime( true );
00279         $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
00280         if ( !$status->isOK() ) {
00281             sleep( 10 ); // wait and retry copy again
00282             $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
00283         }
00284         $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
00285         if ( !$status->isOK() ) {
00286             $this->error( print_r( $status->getErrorsArray(), true ) );
00287             $this->error( "$wikiId: Could not copy file batch.", 1 ); // die
00288         } elseif ( count( $copiedRel ) ) {
00289             $this->output( "\n\tCopied these file(s) [{$ellapsed_ms}ms]:\n\t" .
00290                 implode( "\n\t", $copiedRel ) . "\n\n" );
00291         }
00292     }
00293 
00300     protected function delFileBatch(
00301         array $dstPathsRel, $backendRel, FileBackend $dst
00302     ) {
00303         $ops = array();
00304         $deletedRel = array(); // for output message
00305         $wikiId = $dst->getWikiId();
00306 
00307         // Determine what files need to be copied over...
00308         foreach ( $dstPathsRel as $dstPathRel ) {
00309             $dstPath = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
00310             $ops[] = array( 'op' => 'delete', 'src' => $dstPath );
00311             $deletedRel[] = $dstPathRel;
00312         }
00313 
00314         // Delete the batch of source files...
00315         $t_start = microtime( true );
00316         $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
00317         if ( !$status->isOK() ) {
00318             sleep( 10 ); // wait and retry copy again
00319             $status = $dst->doQuickOperations( $ops, array( 'bypassReadOnly' => 1 ) );
00320         }
00321         $ellapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
00322         if ( !$status->isOK() ) {
00323             $this->error( print_r( $status->getErrorsArray(), true ) );
00324             $this->error( "$wikiId: Could not delete file batch.", 1 ); // die
00325         } elseif ( count( $deletedRel ) ) {
00326             $this->output( "\n\tDeleted these file(s) [{$ellapsed_ms}ms]:\n\t" .
00327                 implode( "\n\t", $deletedRel ) . "\n\n" );
00328         }
00329     }
00330 
00338     protected function filesAreSame( FileBackend $src, FileBackend $dst, $sPath, $dPath ) {
00339         $skipHash = $this->hasOption( 'skiphash' );
00340         $srcStat = $src->getFileStat( array( 'src' => $sPath ) );
00341         $dPathSha1 = sha1( $dPath );
00342         if ( $this->statCache !== null ) {
00343             // All dst files are already in stat cache
00344             $dstStat = isset( $this->statCache[$dPathSha1] )
00345                 ? $this->statCache[$dPathSha1]
00346                 : false;
00347         } else {
00348             $dstStat = $dst->getFileStat( array( 'src' => $dPath ) );
00349         }
00350         // Initial fast checks to see if files are obviously different
00351         $sameFast = (
00352             is_array( $srcStat ) // sanity check that source exists
00353             && is_array( $dstStat ) // dest exists
00354             && $srcStat['size'] === $dstStat['size']
00355         );
00356         // More thorough checks against files
00357         if ( !$sameFast ) {
00358             $same = false; // no need to look farther
00359         } elseif ( isset( $srcStat['md5'] ) && isset( $dstStat['md5'] ) ) {
00360             // If MD5 was already in the stat info, just use it.
00361             // This is useful as many objects stores can return this in object listing,
00362             // so we can use it to avoid slow per-file HEADs.
00363             $same = ( $srcStat['md5'] === $dstStat['md5'] );
00364         } elseif ( $skipHash ) {
00365             // This mode is good for copying to a backup location or resyncing clone
00366             // backends in FileBackendMultiWrite (since they get writes second, they have
00367             // higher timestamps). However, when copying the other way, this hits loads of
00368             // false positives (possibly 100%) and wastes a bunch of time on GETs/PUTs.
00369             $same = ( $srcStat['mtime'] <= $dstStat['mtime'] );
00370         } else {
00371             // This is the slowest method which does many per-file HEADs (unless an object
00372             // store tracks SHA-1 in listings).
00373             $same = ( $src->getFileSha1Base36( array( 'src' => $sPath, 'latest' => 1 ) )
00374                 === $dst->getFileSha1Base36( array( 'src' => $dPath, 'latest' => 1 ) ) );
00375         }
00376 
00377         return $same;
00378     }
00379 }
00380 
00381 $maintClass = 'CopyFileBackend';
00382 require_once RUN_MAINTENANCE_IF_MAIN;