SymlinkDumper.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. <?php
  2. /*
  3. * This file is part of Packagist.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. * Nils Adermann <naderman@naderman.de>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Packagist\WebBundle\Package;
  12. use Symfony\Component\Filesystem\Filesystem;
  13. use Composer\Util\Filesystem as ComposerFilesystem;
  14. use Symfony\Bridge\Doctrine\RegistryInterface;
  15. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  16. use Symfony\Component\Finder\Finder;
  17. use Packagist\WebBundle\Entity\Version;
  18. use Packagist\WebBundle\Entity\Package;
  19. use Doctrine\DBAL\Connection;
  20. use Packagist\WebBundle\HealthCheck\MetadataDirCheck;
  21. use Predis\Client;
  22. use Graze\DogStatsD\Client as StatsDClient;
  23. /**
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. */
  26. class SymlinkDumper
  27. {
  28. /**
  29. * Doctrine
  30. * @var RegistryInterface
  31. */
  32. protected $doctrine;
  33. /**
  34. * @var Filesystem
  35. */
  36. protected $fs;
  37. /**
  38. * @var ComposerFilesystem
  39. */
  40. protected $cfs;
  41. /**
  42. * @var string
  43. */
  44. protected $webDir;
  45. /**
  46. * @var string
  47. */
  48. protected $buildDir;
  49. /**
  50. * @var UrlGeneratorInterface
  51. */
  52. protected $router;
  53. /**
  54. * @var Client
  55. */
  56. protected $redis;
  57. /**
  58. * Data cache
  59. * @var array
  60. */
  61. private $rootFile;
  62. /**
  63. * Data cache
  64. * @var array
  65. */
  66. private $listings = array();
  67. /**
  68. * Data cache
  69. * @var array
  70. */
  71. private $individualFiles = array();
  72. /**
  73. * Data cache
  74. * @var array
  75. */
  76. private $individualFilesV2 = array();
  77. /**
  78. * Modified times of individual files
  79. * @var array
  80. */
  81. private $individualFilesMtime = array();
  82. /**
  83. * Stores all the disk writes to be replicated in the second build dir after the symlink has been swapped
  84. * @var array
  85. */
  86. private $writeLog = array();
  87. /**
  88. * Generate compressed files.
  89. * @var int 0 disabled, 9 maximum.
  90. */
  91. private $compress;
  92. /**
  93. * @var array
  94. */
  95. private $awsMeta;
  96. /**
  97. * @var StatsDClient
  98. */
  99. private $statsd;
  100. /**
  101. * Constructor
  102. *
  103. * @param RegistryInterface $doctrine
  104. * @param Filesystem $filesystem
  105. * @param UrlGeneratorInterface $router
  106. * @param string $webDir web root
  107. * @param string $targetDir
  108. * @param int $compress
  109. */
  110. public function __construct(RegistryInterface $doctrine, Filesystem $filesystem, UrlGeneratorInterface $router, Client $redis, $webDir, $targetDir, $compress, $awsMetadata, StatsDClient $statsd)
  111. {
  112. $this->doctrine = $doctrine;
  113. $this->fs = $filesystem;
  114. $this->cfs = new ComposerFilesystem;
  115. $this->router = $router;
  116. $this->webDir = realpath($webDir);
  117. $this->buildDir = $targetDir;
  118. $this->compress = $compress;
  119. $this->redis = $redis;
  120. $this->awsMeta = $awsMetadata;
  121. $this->statsd = $statsd;
  122. }
  123. /**
  124. * Dump a set of packages to the web root
  125. *
  126. * @param array $packageIds
  127. * @param Boolean $force
  128. * @param Boolean $verbose
  129. */
  130. public function dump(array $packageIds, $force = false, $verbose = false)
  131. {
  132. if (!MetadataDirCheck::isMetadataStoreMounted($this->awsMeta)) {
  133. throw new \RuntimeException('Metadata store not mounted, can not dump metadata');
  134. }
  135. $cleanUpOldFiles = date('i') == 0;
  136. // prepare build dir
  137. $webDir = $this->webDir;
  138. $buildDirA = $this->buildDir.'/a';
  139. $buildDirB = $this->buildDir.'/b';
  140. $buildDirV2 = $this->buildDir.'/p2';
  141. // initialize
  142. $initialRun = false;
  143. if (!is_dir($buildDirA) || !is_dir($buildDirB)) {
  144. $initialRun = true;
  145. if (!$this->removeDirectory($buildDirA) || !$this->removeDirectory($buildDirB)) {
  146. throw new \RuntimeException('Failed to delete '.$buildDirA.' or '.$buildDirB);
  147. }
  148. $this->fs->mkdir($buildDirA);
  149. $this->fs->mkdir($buildDirB);
  150. }
  151. if (!is_dir($buildDirV2)) {
  152. $this->fs->mkdir($buildDirV2);
  153. }
  154. // set build dir to the not-active one
  155. if (realpath($webDir.'/p') === realpath($buildDirA)) {
  156. $buildDir = realpath($buildDirB);
  157. $oldBuildDir = realpath($buildDirA);
  158. } else {
  159. $buildDir = realpath($buildDirA);
  160. $oldBuildDir = realpath($buildDirB);
  161. }
  162. $buildDirV2 = realpath($buildDirV2);
  163. // copy existing stuff for smooth BC transition
  164. if ($initialRun && !$force) {
  165. if (!file_exists($webDir.'/p') || is_link($webDir.'/p')) {
  166. @rmdir($buildDir);
  167. @rmdir($oldBuildDir);
  168. throw new \RuntimeException('Run this again with --force the first time around to make sure it dumps all packages');
  169. }
  170. if ($verbose) {
  171. echo 'Copying existing files'.PHP_EOL;
  172. }
  173. foreach (array($buildDir, $oldBuildDir) as $dir) {
  174. $this->cloneDir($webDir.'/p', $dir);
  175. }
  176. }
  177. if ($verbose) {
  178. echo 'Web dir is '.$webDir.'/p ('.realpath($webDir.'/p').')'.PHP_EOL;
  179. echo 'Build dir is '.$buildDir.PHP_EOL;
  180. echo 'Build v2 dir is '.$buildDirV2.PHP_EOL;
  181. }
  182. // clean the build dir to start over if we are re-dumping everything
  183. if ($force) {
  184. // disable the write log since we copy everything at the end in forced mode
  185. $this->writeLog = false;
  186. if ($verbose) {
  187. echo 'Cleaning up existing files'.PHP_EOL;
  188. }
  189. if (!$this->clearDirectory($buildDir)) {
  190. return false;
  191. }
  192. }
  193. $dumpTimeUpdates = [];
  194. $versionRepo = $this->doctrine->getRepository('PackagistWebBundle:Version');
  195. try {
  196. $modifiedIndividualFiles = array();
  197. $modifiedV2Files = array();
  198. $total = count($packageIds);
  199. $current = 0;
  200. $step = 50;
  201. while ($packageIds) {
  202. $dumpTime = new \DateTime;
  203. $packages = $this->doctrine->getRepository('PackagistWebBundle:Package')->getPackagesWithVersions(array_splice($packageIds, 0, $step));
  204. if ($verbose) {
  205. echo '['.sprintf('%'.strlen($total).'d', $current).'/'.$total.'] Processing '.$step.' packages'.PHP_EOL;
  206. }
  207. $current += $step;
  208. // prepare packages in memory
  209. foreach ($packages as $package) {
  210. // skip spam packages in the dumper in case we do a forced full dump and prevent them from being dumped for a little while
  211. if ($package->isAbandoned() && $package->getReplacementPackage() === 'spam/spam') {
  212. $dumpTimeUpdates['2100-01-01 00:00:00'][] = $package->getId();
  213. continue;
  214. }
  215. $affectedFiles = array();
  216. $name = strtolower($package->getName());
  217. // clean up versions in individual files
  218. if (file_exists($buildDir.'/'.$name.'.files')) {
  219. $files = json_decode(file_get_contents($buildDir.'/'.$name.'.files'));
  220. foreach ($files as $file) {
  221. if (substr_count($file, '/') > 1) { // handle old .files with p/*/*.json paths
  222. $file = preg_replace('{^p/}', '', $file);
  223. }
  224. $this->loadIndividualFile($buildDir.'/'.$file, $file);
  225. if (isset($this->individualFiles[$file]['packages'][$name])) {
  226. unset($this->individualFiles[$file]['packages'][$name]);
  227. $modifiedIndividualFiles[$file] = true;
  228. }
  229. }
  230. }
  231. // (re)write versions in individual files
  232. $versionIds = [];
  233. foreach ($package->getVersions() as $version) {
  234. $versionIds[] = $version->getId();
  235. }
  236. $versionData = $versionRepo->getVersionData($versionIds);
  237. foreach ($package->getVersions() as $version) {
  238. foreach (array_slice($version->getNames($versionData), 0, 150) as $versionName) {
  239. if (!preg_match('{^[A-Za-z0-9_-][A-Za-z0-9_.-]*/[A-Za-z0-9_-][A-Za-z0-9_.-]*$}', $versionName) || strpos($versionName, '..')) {
  240. continue;
  241. }
  242. $file = $buildDir.'/'.$versionName.'.json';
  243. $key = $versionName.'.json';
  244. $this->dumpVersionToIndividualFile($version, $file, $key, $versionData);
  245. $modifiedIndividualFiles[$key] = true;
  246. $affectedFiles[$key] = true;
  247. }
  248. }
  249. // dump v2 format
  250. $key = $name.'.json';
  251. $keyDev = $name.'~dev.json';
  252. $this->dumpPackageToV2File($package, $versionData, $key, $keyDev);
  253. $modifiedV2Files[$key] = true;
  254. $modifiedV2Files[$keyDev] = true;
  255. // store affected files to clean up properly in the next update
  256. $this->fs->mkdir(dirname($buildDir.'/'.$name));
  257. $this->writeFileNonAtomic($buildDir.'/'.$name.'.files', json_encode(array_keys($affectedFiles)));
  258. $dumpTimeUpdates[$dumpTime->format('Y-m-d H:i:s')][] = $package->getId();
  259. }
  260. unset($packages, $package, $version);
  261. $this->doctrine->getManager()->clear();
  262. if ($current % 250 === 0 || !$packageIds) {
  263. if ($verbose) {
  264. echo 'Dumping individual files'.PHP_EOL;
  265. }
  266. $this->dumpIndividualFiles($buildDir);
  267. $this->dumpIndividualFilesV2($buildDirV2);
  268. }
  269. }
  270. // prepare individual files listings
  271. if ($verbose) {
  272. echo 'Preparing individual files listings'.PHP_EOL;
  273. }
  274. $safeFiles = array();
  275. $individualHashedListings = array();
  276. $finder = Finder::create()->files()->ignoreVCS(true)->name('*.json')->in($buildDir)->depth('1');
  277. foreach ($finder as $file) {
  278. // skip hashed files
  279. if (strpos($file, '$')) {
  280. continue;
  281. }
  282. $key = basename(dirname($file)).'/'.basename($file);
  283. if ($force && !isset($modifiedIndividualFiles[$key])) {
  284. continue;
  285. }
  286. // add hashed provider to listing
  287. $listing = $this->getTargetListing($file);
  288. $hash = hash_file('sha256', $file);
  289. $key = substr($key, 0, -5);
  290. $safeFiles[] = $key.'$'.$hash.'.json';
  291. $this->listings[$listing]['providers'][$key] = array('sha256' => $hash);
  292. $individualHashedListings[$listing] = true;
  293. }
  294. // prepare root file
  295. $rootFile = $buildDir.'/packages.json';
  296. $this->rootFile = array('packages' => array());
  297. $url = $this->router->generate('track_download', ['name' => 'VND/PKG'], UrlGeneratorInterface::ABSOLUTE_URL);
  298. $this->rootFile['notify'] = str_replace('VND/PKG', '%package%', $url);
  299. $this->rootFile['notify-batch'] = $this->router->generate('track_download_batch', [], UrlGeneratorInterface::ABSOLUTE_URL);
  300. $this->rootFile['providers-url'] = $this->router->generate('home', []) . 'p/%package%$%hash%.json';
  301. $this->rootFile['metadata-url'] = $this->router->generate('home', []) . 'p2/%package%.json';
  302. $this->rootFile['search'] = $this->router->generate('search', ['_format' => 'json'], UrlGeneratorInterface::ABSOLUTE_URL) . '?q=%query%&type=%type%';
  303. $this->rootFile['providers-api'] = str_replace('VND/PKG', '%package%', $this->router->generate('view_providers', ['name' => 'VND/PKG', '_format' => 'json'], UrlGeneratorInterface::ABSOLUTE_URL));
  304. if ($verbose) {
  305. echo 'Dumping individual listings'.PHP_EOL;
  306. }
  307. // dump listings to build dir
  308. foreach ($individualHashedListings as $listing => $dummy) {
  309. list($listingPath, $hash) = $this->dumpListing($buildDir.'/'.$listing);
  310. $hashedListing = basename($listingPath);
  311. $this->rootFile['provider-includes']['p/'.str_replace($hash, '%hash%', $hashedListing)] = array('sha256' => $hash);
  312. $safeFiles[] = $hashedListing;
  313. }
  314. if ($verbose) {
  315. echo 'Dumping root'.PHP_EOL;
  316. }
  317. $this->dumpRootFile($rootFile);
  318. } catch (\Exception $e) {
  319. // restore files as they were before we started
  320. $this->cloneDir($oldBuildDir, $buildDir);
  321. throw $e;
  322. }
  323. try {
  324. if ($verbose) {
  325. echo 'Putting new files in production'.PHP_EOL;
  326. }
  327. if (!file_exists($webDir.'/p2') && !@symlink($buildDirV2, $webDir.'/p2')) {
  328. echo 'Warning: Could not symlink the build dir v2 into the web dir';
  329. throw new \RuntimeException('Could not symlink the build dir v2 into the web dir');
  330. }
  331. // move away old files for BC update
  332. if ($initialRun && file_exists($webDir.'/p') && !is_link($webDir.'/p')) {
  333. rename($webDir.'/p', $webDir.'/p-old');
  334. }
  335. $this->switchActiveWebDir($webDir, $buildDir);
  336. } catch (\Exception $e) {
  337. @symlink($oldBuildDir, $webDir.'/p');
  338. throw $e;
  339. }
  340. try {
  341. if ($initialRun || !is_link($webDir.'/packages.json') || $force) {
  342. if ($verbose) {
  343. echo 'Writing/linking the packages.json'.PHP_EOL;
  344. }
  345. if (file_exists($webDir.'/packages.json')) {
  346. unlink($webDir.'/packages.json');
  347. }
  348. if (file_exists($webDir.'/packages.json.gz')) {
  349. unlink($webDir.'/packages.json.gz');
  350. }
  351. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  352. $sourcePath = $buildDir.'/packages.json';
  353. if (!copy($sourcePath, $webDir.'/packages.json')) {
  354. throw new \RuntimeException('Could not copy the packages.json file');
  355. }
  356. } else {
  357. $sourcePath = 'p/packages.json';
  358. if (!symlink($sourcePath, $webDir.'/packages.json')) {
  359. throw new \RuntimeException('Could not symlink the packages.json file');
  360. }
  361. if ($this->compress && !symlink($sourcePath.'.gz', $webDir.'/packages.json.gz')) {
  362. throw new \RuntimeException('Could not symlink the packages.json.gz file');
  363. }
  364. }
  365. }
  366. } catch (\Exception $e) {
  367. $this->switchActiveWebDir($webDir, $oldBuildDir);
  368. throw $e;
  369. }
  370. // clean up old dir if present on BC update
  371. if ($initialRun) {
  372. $this->removeDirectory($webDir.'/p-old');
  373. }
  374. // clean the old build dir if we re-dumped everything
  375. if ($force) {
  376. if ($verbose) {
  377. echo 'Cleaning up old build dir'.PHP_EOL;
  378. }
  379. if (!$this->clearDirectory($oldBuildDir)) {
  380. throw new \RuntimeException('Unrecoverable inconsistent state (old build dir could not be cleared), run with --force again to retry');
  381. }
  382. }
  383. // copy state to old active dir
  384. if ($force) {
  385. if ($verbose) {
  386. echo 'Copying new contents to old build dir to sync up'.PHP_EOL;
  387. }
  388. $this->cloneDir($buildDir, $oldBuildDir);
  389. } else {
  390. if ($verbose) {
  391. echo 'Replaying write log in old build dir'.PHP_EOL;
  392. }
  393. $this->copyWriteLog($buildDir, $oldBuildDir);
  394. }
  395. // clean up old files once an hour
  396. if (!$force && $cleanUpOldFiles) {
  397. if ($verbose) {
  398. echo 'Cleaning up old files'.PHP_EOL;
  399. }
  400. $this->cleanOldFiles($buildDir, $oldBuildDir, $safeFiles);
  401. }
  402. if ($verbose) {
  403. echo 'Updating package dump times'.PHP_EOL;
  404. }
  405. $maxDumpTime = 0;
  406. foreach ($dumpTimeUpdates as $dt => $ids) {
  407. $retries = 5;
  408. // retry loop in case of a lock timeout
  409. while ($retries--) {
  410. try {
  411. $this->doctrine->getManager()->getConnection()->executeQuery(
  412. 'UPDATE package SET dumpedAt=:dumped WHERE id IN (:ids)',
  413. [
  414. 'ids' => $ids,
  415. 'dumped' => $dt,
  416. ],
  417. ['ids' => Connection::PARAM_INT_ARRAY]
  418. );
  419. break;
  420. } catch (\Exception $e) {
  421. if (!$retries) {
  422. throw $e;
  423. }
  424. sleep(2);
  425. }
  426. }
  427. if ($dt !== '2100-01-01 00:00:00') {
  428. $maxDumpTime = max($maxDumpTime, strtotime($dt));
  429. }
  430. }
  431. if ($maxDumpTime !== 0) {
  432. $this->redis->set('last_metadata_dump_time', $maxDumpTime + 1);
  433. // make sure no next dumper has a chance to start and dump things within the same second as $maxDumpTime
  434. // as in updatedSince we will return the updates from the next second only (the +1 above) to avoid serving the same updates twice
  435. if (time() === $maxDumpTime) {
  436. sleep(1);
  437. }
  438. }
  439. $this->statsd->increment('packagist.metadata_dump');
  440. // TODO when a package is deleted, it should be removed from provider files, or marked for removal at least
  441. return true;
  442. }
  443. private function switchActiveWebDir($webDir, $buildDir)
  444. {
  445. $newLink = $webDir.'/p-new';
  446. $oldLink = $webDir.'/p';
  447. if (file_exists($newLink)) {
  448. unlink($newLink);
  449. }
  450. if (!symlink($buildDir, $newLink)) {
  451. echo 'Warning: Could not symlink the build dir into the web dir';
  452. throw new \RuntimeException('Could not symlink the build dir into the web dir');
  453. }
  454. if (!rename($newLink, $oldLink)) {
  455. echo 'Warning: Could not replace the old symlink with the new one in the web dir';
  456. throw new \RuntimeException('Could not replace the old symlink with the new one in the web dir');
  457. }
  458. }
  459. private function cloneDir($source, $target)
  460. {
  461. $this->removeDirectory($target);
  462. exec('cp -rpf '.escapeshellarg($source).' '.escapeshellarg($target), $output, $exit);
  463. if (0 !== $exit) {
  464. echo 'Warning, cloning a directory using the php fallback does not keep filemtime, invalid behavior may occur';
  465. $this->fs->mirror($source, $target, null, array('override' => true));
  466. }
  467. }
  468. private function cleanOldFiles($buildDir, $oldBuildDir, $safeFiles)
  469. {
  470. $time = (time() - 86400) * 10000;
  471. $this->redis->set('metadata-oldest', $time);
  472. $this->redis->zremrangebyscore('metadata-dumps', 0, $time-1);
  473. $this->redis->zremrangebyscore('metadata-deletes', 0, $time-1);
  474. $finder = Finder::create()->directories()->ignoreVCS(true)->in($buildDir);
  475. foreach ($finder as $vendorDir) {
  476. $vendorFiles = Finder::create()->files()->ignoreVCS(true)
  477. ->name('/\$[a-f0-9]+\.json$/')
  478. ->date('until 10minutes ago')
  479. ->in((string) $vendorDir);
  480. foreach ($vendorFiles as $file) {
  481. $key = strtr(str_replace($buildDir.DIRECTORY_SEPARATOR, '', $file), '\\', '/');
  482. if (!in_array($key, $safeFiles, true)) {
  483. unlink((string) $file);
  484. if (file_exists($altDirFile = str_replace($buildDir, $oldBuildDir, (string) $file))) {
  485. unlink($altDirFile);
  486. }
  487. }
  488. }
  489. }
  490. // clean up old provider listings
  491. $finder = Finder::create()->depth(0)->files()->name('provider-*.json')->ignoreVCS(true)->in($buildDir)->date('until 10minutes ago');
  492. foreach ($finder as $provider) {
  493. $key = strtr(str_replace($buildDir.DIRECTORY_SEPARATOR, '', $provider), '\\', '/');
  494. if (!in_array($key, $safeFiles, true)) {
  495. $path = (string) $provider;
  496. unlink($path);
  497. if (file_exists($path.'.gz')) {
  498. unlink($path.'.gz');
  499. }
  500. if (file_exists($altDirFile = str_replace($buildDir, $oldBuildDir, $path))) {
  501. unlink($altDirFile);
  502. if (file_exists($altDirFile.'.gz')) {
  503. unlink($altDirFile.'.gz');
  504. }
  505. }
  506. }
  507. }
  508. // clean up old root listings
  509. $finder = Finder::create()->depth(0)->files()->name('packages.json-*')->ignoreVCS(true)->in($buildDir)->date('until 10minutes ago');
  510. foreach ($finder as $rootFile) {
  511. $path = (string) $rootFile;
  512. unlink($path);
  513. if (file_exists($path.'.gz')) {
  514. unlink($path.'.gz');
  515. }
  516. if (file_exists($altDirFile = str_replace($buildDir, $oldBuildDir, $path))) {
  517. unlink($altDirFile);
  518. if (file_exists($altDirFile.'.gz')) {
  519. unlink($altDirFile.'.gz');
  520. }
  521. }
  522. }
  523. }
  524. private function dumpRootFile($file)
  525. {
  526. // sort all versions and packages to make sha1 consistent
  527. ksort($this->rootFile['packages']);
  528. ksort($this->rootFile['provider-includes']);
  529. foreach ($this->rootFile['packages'] as $package => $versions) {
  530. ksort($this->rootFile['packages'][$package]);
  531. }
  532. $json = json_encode($this->rootFile, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  533. $time = time();
  534. $this->writeFile($file, $json, $time);
  535. if ($this->compress) {
  536. $this->writeFile($file . '.gz', gzencode($json, $this->compress), $time);
  537. }
  538. }
  539. private function dumpListing($path)
  540. {
  541. $key = basename($path);
  542. // sort files to make hash consistent
  543. ksort($this->listings[$key]['providers']);
  544. $json = json_encode($this->listings[$key], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  545. $hash = hash('sha256', $json);
  546. $path = substr($path, 0, -5) . '$' . $hash . '.json';
  547. $time = time();
  548. if (!file_exists($path)) {
  549. $this->writeFile($path, $json, $time);
  550. if ($this->compress) {
  551. $this->writeFile($path . '.gz', gzencode($json, $this->compress), $time);
  552. }
  553. }
  554. return array($path, $hash);
  555. }
  556. private function loadIndividualFile($path, $key)
  557. {
  558. if (isset($this->individualFiles[$key])) {
  559. return;
  560. }
  561. if (file_exists($path)) {
  562. $this->individualFiles[$key] = json_decode(file_get_contents($path), true);
  563. $this->individualFilesMtime[$key] = filemtime($path);
  564. } else {
  565. $this->individualFiles[$key] = array();
  566. $this->individualFilesMtime[$key] = 0;
  567. }
  568. }
  569. private function dumpIndividualFiles($buildDir)
  570. {
  571. // dump individual files to build dir
  572. foreach ($this->individualFiles as $file => $dummy) {
  573. $this->dumpIndividualFile($buildDir.'/'.$file, $file);
  574. }
  575. $this->individualFiles = array();
  576. $this->individualFilesMtime = array();
  577. }
  578. private function dumpIndividualFile($path, $key)
  579. {
  580. // sort all versions and packages to make sha1 consistent
  581. ksort($this->individualFiles[$key]['packages']);
  582. foreach ($this->individualFiles[$key]['packages'] as $package => $versions) {
  583. ksort($this->individualFiles[$key]['packages'][$package]);
  584. }
  585. $this->fs->mkdir(dirname($path));
  586. $json = json_encode($this->individualFiles[$key], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  587. $this->writeFile($path, $json, $this->individualFilesMtime[$key]);
  588. // write the hashed provider file
  589. $hashedFile = substr($path, 0, -5) . '$' . hash('sha256', $json) . '.json';
  590. $this->writeFile($hashedFile, $json);
  591. }
  592. private function dumpVersionToIndividualFile(Version $version, $file, $key, $versionData)
  593. {
  594. $this->loadIndividualFile($file, $key);
  595. $data = $version->toArray($versionData);
  596. $data['uid'] = $version->getId();
  597. $this->individualFiles[$key]['packages'][strtolower($version->getName())][$version->getVersion()] = $data;
  598. $timestamp = $version->getReleasedAt() ? $version->getReleasedAt()->getTimestamp() : time();
  599. if (!isset($this->individualFilesMtime[$key]) || $this->individualFilesMtime[$key] < $timestamp) {
  600. $this->individualFilesMtime[$key] = $timestamp;
  601. }
  602. }
  603. private function dumpIndividualFilesV2($dir)
  604. {
  605. // dump individual files to build dir
  606. foreach ($this->individualFilesV2 as $key => $data) {
  607. $path = $dir . '/' . $key;
  608. $this->fs->mkdir(dirname($path));
  609. $json = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  610. $this->writeV2File($path, $json);
  611. }
  612. $this->individualFilesV2 = array();
  613. }
  614. private function dumpPackageToV2File(Package $package, $versionData, string $packageKey, string $packageKeyDev)
  615. {
  616. $versions = $package->getVersions();
  617. if (is_object($versions)) {
  618. $versions = $versions->toArray();
  619. }
  620. usort($versions, Package::class.'::sortVersions');
  621. $tags = [];
  622. $branches = [];
  623. foreach ($versions as $version) {
  624. if ($version->isDevelopment()) {
  625. $branches[] = $version;
  626. } else {
  627. $tags[] = $version;
  628. }
  629. }
  630. $this->dumpVersionsToV2File($package, $tags, $versionData, $packageKey);
  631. $this->dumpVersionsToV2File($package, $branches, $versionData, $packageKeyDev);
  632. }
  633. private function dumpVersionsToV2File(Package $package, $versions, $versionData, string $packageKey)
  634. {
  635. $minifiedVersions = [];
  636. $lastKnownVersionData = null;
  637. foreach ($versions as $version) {
  638. $versionArray = $version->toV2Array($versionData);
  639. if (!$lastKnownVersionData) {
  640. $lastKnownVersionData = $versionArray;
  641. $minifiedVersions[] = $versionArray;
  642. continue;
  643. }
  644. $minifiedVersion = [];
  645. // add any changes from the previous version
  646. foreach ($versionArray as $key => $val) {
  647. if (!isset($lastKnownVersionData[$key]) || $lastKnownVersionData[$key] !== $val) {
  648. $minifiedVersion[$key] = $val;
  649. $lastKnownVersionData[$key] = $val;
  650. }
  651. }
  652. // store any deletions from the previous version for keys missing in current one
  653. foreach ($lastKnownVersionData as $key => $val) {
  654. if (!isset($versionArray[$key])) {
  655. $minifiedVersion[$key] = "__unset";
  656. unset($lastKnownVersionData[$key]);
  657. }
  658. }
  659. $minifiedVersions[] = $minifiedVersion;
  660. }
  661. $this->individualFilesV2[$packageKey]['packages'][strtolower($package->getName())] = $minifiedVersions;
  662. $this->individualFilesV2[$packageKey]['minified'] = 'composer/2.0';
  663. }
  664. private function clearDirectory($path)
  665. {
  666. if (!$this->removeDirectory($path)) {
  667. echo 'Could not remove the build dir entirely, aborting';
  668. return false;
  669. }
  670. $this->fs->mkdir($path);
  671. return true;
  672. }
  673. private function removeDirectory($path)
  674. {
  675. $retries = 5;
  676. do {
  677. if (!$this->cfs->removeDirectory($path)) {
  678. usleep(200);
  679. }
  680. clearstatcache();
  681. } while (is_dir($path) && $retries--);
  682. return !is_dir($path);
  683. }
  684. private function getTargetListingBlocks($now)
  685. {
  686. $blocks = array();
  687. // monday last week
  688. $blocks['latest'] = strtotime('monday last week', $now);
  689. $month = date('n', $now);
  690. $month = ceil($month / 3) * 3 - 2; // 1 for months 1-3, 10 for months 10-12
  691. $block = new \DateTime(date('Y', $now).'-'.$month.'-01'); // 1st day of current trimester
  692. // split last 12 months in 4 trimesters
  693. for ($i=0; $i < 4; $i++) {
  694. $blocks[$block->format('Y-m')] = $block->getTimestamp();
  695. $block->sub(new \DateInterval('P3M'));
  696. }
  697. $year = (int) $block->format('Y');
  698. while ($year >= 2013) {
  699. $blocks[''.$year] = strtotime($year.'-01-01');
  700. $year--;
  701. }
  702. return $blocks;
  703. }
  704. private function getTargetListing($file)
  705. {
  706. static $blocks;
  707. if (!$blocks) {
  708. $blocks = $this->getTargetListingBlocks(time());
  709. }
  710. $mtime = filemtime($file);
  711. foreach ($blocks as $label => $block) {
  712. if ($mtime >= $block) {
  713. return "provider-${label}.json";
  714. }
  715. }
  716. return "provider-archived.json";
  717. }
  718. private function writeFile($path, $contents, $mtime = null)
  719. {
  720. file_put_contents($path.'.tmp', $contents);
  721. if ($mtime !== null) {
  722. touch($path.'.tmp', $mtime);
  723. }
  724. rename($path.'.tmp', $path);
  725. if (is_array($this->writeLog)) {
  726. $this->writeLog[$path] = array($contents, $mtime);
  727. }
  728. }
  729. private function writeV2File($path, $contents)
  730. {
  731. if (file_exists($path) && file_get_contents($path) === $contents) {
  732. return;
  733. }
  734. // get time before file_put_contents to be sure we return a time at least as old as the filemtime, if it is older it doesn't matter
  735. $timestamp = round(microtime(true)*10000);
  736. file_put_contents($path.'.tmp', $contents);
  737. rename($path.'.tmp', $path);
  738. if (!preg_match('{/([^/]+/[^/]+?(~dev)?)\.json$}', $path, $match)) {
  739. throw new \LogicException('Could not match package name from '.$path);
  740. }
  741. $this->redis->zadd('metadata-dumps', $timestamp, $match[1]);
  742. }
  743. private function writeFileNonAtomic($path, $contents)
  744. {
  745. file_put_contents($path, $contents);
  746. if (is_array($this->writeLog)) {
  747. $this->writeLog[$path] = array($contents, null);
  748. }
  749. }
  750. private function copyWriteLog($from, $to)
  751. {
  752. foreach ($this->writeLog as $path => $op) {
  753. $path = str_replace($from, $to, $path);
  754. $this->fs->mkdir(dirname($path));
  755. file_put_contents($path, $op[0]);
  756. if ($op[1] !== null) {
  757. touch($path, $op[1]);
  758. }
  759. }
  760. }
  761. }