copyFileBackend.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <?php
  2. /**
  3. * Copy all files in some containers of one backend to another.
  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 Maintenance
  22. */
  23. require_once __DIR__ . '/Maintenance.php';
  24. /**
  25. * Copy all files in one container of one backend to another.
  26. *
  27. * This can also be used to re-shard the files for one backend using the
  28. * config of second backend. The second backend should have the same config
  29. * as the first, except for it having a different name and different sharding
  30. * configuration. The backend should be made read-only while this runs.
  31. * After this script finishes, the old files in the containers can be deleted.
  32. *
  33. * @ingroup Maintenance
  34. */
  35. class CopyFileBackend extends Maintenance {
  36. /** @var array|null (path sha1 => stat) Pre-computed dst stat entries from listings */
  37. protected $statCache = null;
  38. public function __construct() {
  39. parent::__construct();
  40. $this->addDescription( 'Copy files in one backend to another.' );
  41. $this->addOption( 'src', 'Backend containing the source files', true, true );
  42. $this->addOption( 'dst', 'Backend where files should be copied to', true, true );
  43. $this->addOption( 'containers', 'Pipe separated list of containers', true, true );
  44. $this->addOption( 'subdir', 'Only do items in this child directory', false, true );
  45. $this->addOption( 'ratefile', 'File to check periodically for batch size', false, true );
  46. $this->addOption( 'prestat', 'Stat the destination files first (try to use listings)' );
  47. $this->addOption( 'skiphash', 'Skip SHA-1 sync checks for files' );
  48. $this->addOption( 'missingonly', 'Only copy files missing from destination listing' );
  49. $this->addOption( 'syncviadelete', 'Delete destination files missing from source listing' );
  50. $this->addOption( 'utf8only', 'Skip source files that do not have valid UTF-8 names' );
  51. $this->setBatchSize( 50 );
  52. }
  53. public function execute() {
  54. $src = FileBackendGroup::singleton()->get( $this->getOption( 'src' ) );
  55. $dst = FileBackendGroup::singleton()->get( $this->getOption( 'dst' ) );
  56. $containers = explode( '|', $this->getOption( 'containers' ) );
  57. $subDir = rtrim( $this->getOption( 'subdir', '' ), '/' );
  58. $rateFile = $this->getOption( 'ratefile' );
  59. if ( $this->hasOption( 'utf8only' ) && !extension_loaded( 'mbstring' ) ) {
  60. $this->error( "Cannot check for UTF-8, mbstring extension missing.", 1 ); // die
  61. }
  62. foreach ( $containers as $container ) {
  63. if ( $subDir != '' ) {
  64. $backendRel = "$container/$subDir";
  65. $this->output( "Doing container '$container', directory '$subDir'...\n" );
  66. } else {
  67. $backendRel = $container;
  68. $this->output( "Doing container '$container'...\n" );
  69. }
  70. if ( $this->hasOption( 'missingonly' ) ) {
  71. $this->output( "\tBuilding list of missing files..." );
  72. $srcPathsRel = $this->getListingDiffRel( $src, $dst, $backendRel );
  73. $this->output( count( $srcPathsRel ) . " file(s) need to be copied.\n" );
  74. } else {
  75. $srcPathsRel = $src->getFileList( [
  76. 'dir' => $src->getRootStoragePath() . "/$backendRel",
  77. 'adviseStat' => true // avoid HEADs
  78. ] );
  79. if ( $srcPathsRel === null ) {
  80. $this->error( "Could not list files in $container.", 1 ); // die
  81. }
  82. }
  83. if ( $this->getOption( 'prestat' ) && !$this->hasOption( 'missingonly' ) ) {
  84. // Build the stat cache for the destination files
  85. $this->output( "\tBuilding destination stat cache..." );
  86. $dstPathsRel = $dst->getFileList( [
  87. 'dir' => $dst->getRootStoragePath() . "/$backendRel",
  88. 'adviseStat' => true // avoid HEADs
  89. ] );
  90. if ( $dstPathsRel === null ) {
  91. $this->error( "Could not list files in $container.", 1 ); // die
  92. }
  93. $this->statCache = [];
  94. foreach ( $dstPathsRel as $dstPathRel ) {
  95. $path = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
  96. $this->statCache[sha1( $path )] = $dst->getFileStat( [ 'src' => $path ] );
  97. }
  98. $this->output( "done [" . count( $this->statCache ) . " file(s)]\n" );
  99. }
  100. $this->output( "\tCopying file(s)...\n" );
  101. $count = 0;
  102. $batchPaths = [];
  103. foreach ( $srcPathsRel as $srcPathRel ) {
  104. // Check up on the rate file periodically to adjust the concurrency
  105. if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
  106. $this->mBatchSize = max( 1, (int)file_get_contents( $rateFile ) );
  107. $this->output( "\tBatch size is now {$this->mBatchSize}.\n" );
  108. }
  109. $batchPaths[$srcPathRel] = 1; // remove duplicates
  110. if ( count( $batchPaths ) >= $this->mBatchSize ) {
  111. $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
  112. $batchPaths = []; // done
  113. }
  114. ++$count;
  115. }
  116. if ( count( $batchPaths ) ) { // left-overs
  117. $this->copyFileBatch( array_keys( $batchPaths ), $backendRel, $src, $dst );
  118. $batchPaths = []; // done
  119. }
  120. $this->output( "\tCopied $count file(s).\n" );
  121. if ( $this->hasOption( 'syncviadelete' ) ) {
  122. $this->output( "\tBuilding list of excess destination files..." );
  123. $delPathsRel = $this->getListingDiffRel( $dst, $src, $backendRel );
  124. $this->output( count( $delPathsRel ) . " file(s) need to be deleted.\n" );
  125. $this->output( "\tDeleting file(s)...\n" );
  126. $count = 0;
  127. $batchPaths = [];
  128. foreach ( $delPathsRel as $delPathRel ) {
  129. // Check up on the rate file periodically to adjust the concurrency
  130. if ( $rateFile && ( !$count || ( $count % 500 ) == 0 ) ) {
  131. $this->mBatchSize = max( 1, (int)file_get_contents( $rateFile ) );
  132. $this->output( "\tBatch size is now {$this->mBatchSize}.\n" );
  133. }
  134. $batchPaths[$delPathRel] = 1; // remove duplicates
  135. if ( count( $batchPaths ) >= $this->mBatchSize ) {
  136. $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
  137. $batchPaths = []; // done
  138. }
  139. ++$count;
  140. }
  141. if ( count( $batchPaths ) ) { // left-overs
  142. $this->delFileBatch( array_keys( $batchPaths ), $backendRel, $dst );
  143. $batchPaths = []; // done
  144. }
  145. $this->output( "\tDeleted $count file(s).\n" );
  146. }
  147. if ( $subDir != '' ) {
  148. $this->output( "Finished container '$container', directory '$subDir'.\n" );
  149. } else {
  150. $this->output( "Finished container '$container'.\n" );
  151. }
  152. }
  153. $this->output( "Done.\n" );
  154. }
  155. /**
  156. * @param FileBackend $src
  157. * @param FileBackend $dst
  158. * @param string $backendRel
  159. * @return array (rel paths in $src minus those in $dst)
  160. */
  161. protected function getListingDiffRel( FileBackend $src, FileBackend $dst, $backendRel ) {
  162. $srcPathsRel = $src->getFileList( [
  163. 'dir' => $src->getRootStoragePath() . "/$backendRel" ] );
  164. if ( $srcPathsRel === null ) {
  165. $this->error( "Could not list files in source container.", 1 ); // die
  166. }
  167. $dstPathsRel = $dst->getFileList( [
  168. 'dir' => $dst->getRootStoragePath() . "/$backendRel" ] );
  169. if ( $dstPathsRel === null ) {
  170. $this->error( "Could not list files in destination container.", 1 ); // die
  171. }
  172. // Get the list of destination files
  173. $relFilesDstSha1 = [];
  174. foreach ( $dstPathsRel as $dstPathRel ) {
  175. $relFilesDstSha1[sha1( $dstPathRel )] = 1;
  176. }
  177. unset( $dstPathsRel ); // free
  178. // Get the list of missing files
  179. $missingPathsRel = [];
  180. foreach ( $srcPathsRel as $srcPathRel ) {
  181. if ( !isset( $relFilesDstSha1[sha1( $srcPathRel )] ) ) {
  182. $missingPathsRel[] = $srcPathRel;
  183. }
  184. }
  185. unset( $srcPathsRel ); // free
  186. return $missingPathsRel;
  187. }
  188. /**
  189. * @param array $srcPathsRel
  190. * @param string $backendRel
  191. * @param FileBackend $src
  192. * @param FileBackend $dst
  193. * @return void
  194. */
  195. protected function copyFileBatch(
  196. array $srcPathsRel, $backendRel, FileBackend $src, FileBackend $dst
  197. ) {
  198. $ops = [];
  199. $fsFiles = [];
  200. $copiedRel = []; // for output message
  201. $wikiId = $src->getWikiId();
  202. // Download the batch of source files into backend cache...
  203. if ( $this->hasOption( 'missingonly' ) ) {
  204. $srcPaths = [];
  205. foreach ( $srcPathsRel as $srcPathRel ) {
  206. $srcPaths[] = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
  207. }
  208. $t_start = microtime( true );
  209. $fsFiles = $src->getLocalReferenceMulti( [ 'srcs' => $srcPaths, 'latest' => 1 ] );
  210. $elapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
  211. $this->output( "\n\tDownloaded these file(s) [{$elapsed_ms}ms]:\n\t" .
  212. implode( "\n\t", $srcPaths ) . "\n\n" );
  213. }
  214. // Determine what files need to be copied over...
  215. foreach ( $srcPathsRel as $srcPathRel ) {
  216. $srcPath = $src->getRootStoragePath() . "/$backendRel/$srcPathRel";
  217. $dstPath = $dst->getRootStoragePath() . "/$backendRel/$srcPathRel";
  218. if ( $this->hasOption( 'utf8only' ) && !mb_check_encoding( $srcPath, 'UTF-8' ) ) {
  219. $this->error( "$wikiId: Detected illegal (non-UTF8) path for $srcPath." );
  220. continue;
  221. } elseif ( !$this->hasOption( 'missingonly' )
  222. && $this->filesAreSame( $src, $dst, $srcPath, $dstPath )
  223. ) {
  224. $this->output( "\tAlready have $srcPathRel.\n" );
  225. continue; // assume already copied...
  226. }
  227. $fsFile = array_key_exists( $srcPath, $fsFiles )
  228. ? $fsFiles[$srcPath]
  229. : $src->getLocalReference( [ 'src' => $srcPath, 'latest' => 1 ] );
  230. if ( !$fsFile ) {
  231. $src->clearCache( [ $srcPath ] );
  232. if ( $src->fileExists( [ 'src' => $srcPath, 'latest' => 1 ] ) === false ) {
  233. $this->error( "$wikiId: File '$srcPath' was listed but does not exist." );
  234. } else {
  235. $this->error( "$wikiId: Could not get local copy of $srcPath." );
  236. }
  237. continue;
  238. } elseif ( !$fsFile->exists() ) {
  239. // FSFileBackends just return the path for getLocalReference() and paths with
  240. // illegal slashes may get normalized to a different path. This can cause the
  241. // local reference to not exist...skip these broken files.
  242. $this->error( "$wikiId: Detected possible illegal path for $srcPath." );
  243. continue;
  244. }
  245. $fsFiles[] = $fsFile; // keep TempFSFile objects alive as needed
  246. // Note: prepare() is usually fast for key/value backends
  247. $status = $dst->prepare( [ 'dir' => dirname( $dstPath ), 'bypassReadOnly' => 1 ] );
  248. if ( !$status->isOK() ) {
  249. $this->error( print_r( $status->getErrorsArray(), true ) );
  250. $this->error( "$wikiId: Could not copy $srcPath to $dstPath.", 1 ); // die
  251. }
  252. $ops[] = [ 'op' => 'store',
  253. 'src' => $fsFile->getPath(), 'dst' => $dstPath, 'overwrite' => 1 ];
  254. $copiedRel[] = $srcPathRel;
  255. }
  256. // Copy in the batch of source files...
  257. $t_start = microtime( true );
  258. $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => 1 ] );
  259. if ( !$status->isOK() ) {
  260. sleep( 10 ); // wait and retry copy again
  261. $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => 1 ] );
  262. }
  263. $elapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
  264. if ( !$status->isOK() ) {
  265. $this->error( print_r( $status->getErrorsArray(), true ) );
  266. $this->error( "$wikiId: Could not copy file batch.", 1 ); // die
  267. } elseif ( count( $copiedRel ) ) {
  268. $this->output( "\n\tCopied these file(s) [{$elapsed_ms}ms]:\n\t" .
  269. implode( "\n\t", $copiedRel ) . "\n\n" );
  270. }
  271. }
  272. /**
  273. * @param array $dstPathsRel
  274. * @param string $backendRel
  275. * @param FileBackend $dst
  276. * @return void
  277. */
  278. protected function delFileBatch(
  279. array $dstPathsRel, $backendRel, FileBackend $dst
  280. ) {
  281. $ops = [];
  282. $deletedRel = []; // for output message
  283. $wikiId = $dst->getWikiId();
  284. // Determine what files need to be copied over...
  285. foreach ( $dstPathsRel as $dstPathRel ) {
  286. $dstPath = $dst->getRootStoragePath() . "/$backendRel/$dstPathRel";
  287. $ops[] = [ 'op' => 'delete', 'src' => $dstPath ];
  288. $deletedRel[] = $dstPathRel;
  289. }
  290. // Delete the batch of source files...
  291. $t_start = microtime( true );
  292. $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => 1 ] );
  293. if ( !$status->isOK() ) {
  294. sleep( 10 ); // wait and retry copy again
  295. $status = $dst->doQuickOperations( $ops, [ 'bypassReadOnly' => 1 ] );
  296. }
  297. $elapsed_ms = floor( ( microtime( true ) - $t_start ) * 1000 );
  298. if ( !$status->isOK() ) {
  299. $this->error( print_r( $status->getErrorsArray(), true ) );
  300. $this->error( "$wikiId: Could not delete file batch.", 1 ); // die
  301. } elseif ( count( $deletedRel ) ) {
  302. $this->output( "\n\tDeleted these file(s) [{$elapsed_ms}ms]:\n\t" .
  303. implode( "\n\t", $deletedRel ) . "\n\n" );
  304. }
  305. }
  306. /**
  307. * @param FileBackend $src
  308. * @param FileBackend $dst
  309. * @param string $sPath
  310. * @param string $dPath
  311. * @return bool
  312. */
  313. protected function filesAreSame( FileBackend $src, FileBackend $dst, $sPath, $dPath ) {
  314. $skipHash = $this->hasOption( 'skiphash' );
  315. $srcStat = $src->getFileStat( [ 'src' => $sPath ] );
  316. $dPathSha1 = sha1( $dPath );
  317. if ( $this->statCache !== null ) {
  318. // All dst files are already in stat cache
  319. $dstStat = isset( $this->statCache[$dPathSha1] )
  320. ? $this->statCache[$dPathSha1]
  321. : false;
  322. } else {
  323. $dstStat = $dst->getFileStat( [ 'src' => $dPath ] );
  324. }
  325. // Initial fast checks to see if files are obviously different
  326. $sameFast = (
  327. is_array( $srcStat ) // sanity check that source exists
  328. && is_array( $dstStat ) // dest exists
  329. && $srcStat['size'] === $dstStat['size']
  330. );
  331. // More thorough checks against files
  332. if ( !$sameFast ) {
  333. $same = false; // no need to look farther
  334. } elseif ( isset( $srcStat['md5'] ) && isset( $dstStat['md5'] ) ) {
  335. // If MD5 was already in the stat info, just use it.
  336. // This is useful as many objects stores can return this in object listing,
  337. // so we can use it to avoid slow per-file HEADs.
  338. $same = ( $srcStat['md5'] === $dstStat['md5'] );
  339. } elseif ( $skipHash ) {
  340. // This mode is good for copying to a backup location or resyncing clone
  341. // backends in FileBackendMultiWrite (since they get writes second, they have
  342. // higher timestamps). However, when copying the other way, this hits loads of
  343. // false positives (possibly 100%) and wastes a bunch of time on GETs/PUTs.
  344. $same = ( $srcStat['mtime'] <= $dstStat['mtime'] );
  345. } else {
  346. // This is the slowest method which does many per-file HEADs (unless an object
  347. // store tracks SHA-1 in listings).
  348. $same = ( $src->getFileSha1Base36( [ 'src' => $sPath, 'latest' => 1 ] )
  349. === $dst->getFileSha1Base36( [ 'src' => $dPath, 'latest' => 1 ] ) );
  350. }
  351. return $same;
  352. }
  353. }
  354. $maintClass = 'CopyFileBackend';
  355. require_once RUN_MAINTENANCE_IF_MAIN;