copyFileBackend.php 14 KB

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