SymlinkDumper.php 31 KB

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