Updater.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC;
  9. use OC\App\AppManager;
  10. use OC\App\AppStore\Fetcher\AppFetcher;
  11. use OC\DB\Connection;
  12. use OC\DB\MigrationService;
  13. use OC\DB\MigratorExecuteSqlEvent;
  14. use OC\Hooks\BasicEmitter;
  15. use OC\IntegrityCheck\Checker;
  16. use OC\Repair\Events\RepairAdvanceEvent;
  17. use OC\Repair\Events\RepairErrorEvent;
  18. use OC\Repair\Events\RepairFinishEvent;
  19. use OC\Repair\Events\RepairInfoEvent;
  20. use OC\Repair\Events\RepairStartEvent;
  21. use OC\Repair\Events\RepairStepEvent;
  22. use OC\Repair\Events\RepairWarningEvent;
  23. use OC_App;
  24. use OCP\App\IAppManager;
  25. use OCP\EventDispatcher\Event;
  26. use OCP\EventDispatcher\IEventDispatcher;
  27. use OCP\HintException;
  28. use OCP\IAppConfig;
  29. use OCP\IConfig;
  30. use OCP\ILogger;
  31. use OCP\Util;
  32. use Psr\Log\LoggerInterface;
  33. /**
  34. * Class that handles autoupdating of ownCloud
  35. *
  36. * Hooks provided in scope \OC\Updater
  37. * - maintenanceStart()
  38. * - maintenanceEnd()
  39. * - dbUpgrade()
  40. * - failure(string $message)
  41. */
  42. class Updater extends BasicEmitter {
  43. private array $logLevelNames = [
  44. 0 => 'Debug',
  45. 1 => 'Info',
  46. 2 => 'Warning',
  47. 3 => 'Error',
  48. 4 => 'Fatal',
  49. ];
  50. public function __construct(
  51. private IConfig $config,
  52. private IAppConfig $appConfig,
  53. private Checker $checker,
  54. private ?LoggerInterface $log,
  55. private Installer $installer
  56. ) {
  57. }
  58. /**
  59. * runs the update actions in maintenance mode, does not upgrade the source files
  60. * except the main .htaccess file
  61. *
  62. * @return bool true if the operation succeeded, false otherwise
  63. */
  64. public function upgrade(): bool {
  65. $this->logAllEvents();
  66. $logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
  67. $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
  68. $this->config->setSystemValue('loglevel', ILogger::DEBUG);
  69. $wasMaintenanceModeEnabled = $this->config->getSystemValueBool('maintenance');
  70. if (!$wasMaintenanceModeEnabled) {
  71. $this->config->setSystemValue('maintenance', true);
  72. $this->emit('\OC\Updater', 'maintenanceEnabled');
  73. }
  74. // Clear CAN_INSTALL file if not on git
  75. if (\OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL')) {
  76. if (!unlink(\OC::$configDir . '/CAN_INSTALL')) {
  77. $this->log->error('Could not cleanup CAN_INSTALL from your config folder. Please remove this file manually.');
  78. }
  79. }
  80. $installedVersion = $this->config->getSystemValueString('version', '0.0.0');
  81. $currentVersion = implode('.', \OCP\Util::getVersion());
  82. $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, ['app' => 'core']);
  83. $success = true;
  84. try {
  85. $this->doUpgrade($currentVersion, $installedVersion);
  86. } catch (HintException $exception) {
  87. $this->log->error($exception->getMessage(), [
  88. 'exception' => $exception,
  89. ]);
  90. $this->emit('\OC\Updater', 'failure', [$exception->getMessage() . ': ' .$exception->getHint()]);
  91. $success = false;
  92. } catch (\Exception $exception) {
  93. $this->log->error($exception->getMessage(), [
  94. 'exception' => $exception,
  95. ]);
  96. $this->emit('\OC\Updater', 'failure', [get_class($exception) . ': ' .$exception->getMessage()]);
  97. $success = false;
  98. }
  99. $this->emit('\OC\Updater', 'updateEnd', [$success]);
  100. if (!$wasMaintenanceModeEnabled && $success) {
  101. $this->config->setSystemValue('maintenance', false);
  102. $this->emit('\OC\Updater', 'maintenanceDisabled');
  103. } else {
  104. $this->emit('\OC\Updater', 'maintenanceActive');
  105. }
  106. $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
  107. $this->config->setSystemValue('loglevel', $logLevel);
  108. $this->config->setSystemValue('installed', true);
  109. return $success;
  110. }
  111. /**
  112. * Return version from which this version is allowed to upgrade from
  113. *
  114. * @return array allowed previous versions per vendor
  115. */
  116. private function getAllowedPreviousVersions(): array {
  117. // this should really be a JSON file
  118. require \OC::$SERVERROOT . '/version.php';
  119. /** @var array $OC_VersionCanBeUpgradedFrom */
  120. return $OC_VersionCanBeUpgradedFrom;
  121. }
  122. /**
  123. * Return vendor from which this version was published
  124. *
  125. * @return string Get the vendor
  126. */
  127. private function getVendor(): string {
  128. // this should really be a JSON file
  129. require \OC::$SERVERROOT . '/version.php';
  130. /** @var string $vendor */
  131. return (string) $vendor;
  132. }
  133. /**
  134. * Whether an upgrade to a specified version is possible
  135. * @param string $oldVersion
  136. * @param string $newVersion
  137. * @param array $allowedPreviousVersions
  138. * @return bool
  139. */
  140. public function isUpgradePossible(string $oldVersion, string $newVersion, array $allowedPreviousVersions): bool {
  141. $version = explode('.', $oldVersion);
  142. $majorMinor = $version[0] . '.' . $version[1];
  143. $currentVendor = $this->config->getAppValue('core', 'vendor', '');
  144. // Vendor was not set correctly on install, so we have to white-list known versions
  145. if ($currentVendor === '' && (
  146. isset($allowedPreviousVersions['owncloud'][$oldVersion]) ||
  147. isset($allowedPreviousVersions['owncloud'][$majorMinor])
  148. )) {
  149. $currentVendor = 'owncloud';
  150. $this->config->setAppValue('core', 'vendor', $currentVendor);
  151. }
  152. if ($currentVendor === 'nextcloud') {
  153. return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
  154. && (version_compare($oldVersion, $newVersion, '<=') ||
  155. $this->config->getSystemValueBool('debug', false));
  156. }
  157. // Check if the instance can be migrated
  158. return isset($allowedPreviousVersions[$currentVendor][$majorMinor]) ||
  159. isset($allowedPreviousVersions[$currentVendor][$oldVersion]);
  160. }
  161. /**
  162. * runs the update actions in maintenance mode, does not upgrade the source files
  163. * except the main .htaccess file
  164. *
  165. * @param string $currentVersion current version to upgrade to
  166. * @param string $installedVersion previous version from which to upgrade from
  167. *
  168. * @throws \Exception
  169. */
  170. private function doUpgrade(string $currentVersion, string $installedVersion): void {
  171. // Stop update if the update is over several major versions
  172. $allowedPreviousVersions = $this->getAllowedPreviousVersions();
  173. if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
  174. throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
  175. }
  176. // Update .htaccess files
  177. try {
  178. Setup::updateHtaccess();
  179. Setup::protectDataDirectory();
  180. } catch (\Exception $e) {
  181. throw new \Exception($e->getMessage());
  182. }
  183. // create empty file in data dir, so we can later find
  184. // out that this is indeed a Nextcloud data directory
  185. // (in case it didn't exist before)
  186. file_put_contents(
  187. $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/.ncdata',
  188. "# Nextcloud data directory\n# Do not change this file",
  189. );
  190. // pre-upgrade repairs
  191. $repair = \OCP\Server::get(Repair::class);
  192. $repair->setRepairSteps(Repair::getBeforeUpgradeRepairSteps());
  193. $repair->run();
  194. $this->doCoreUpgrade();
  195. try {
  196. // TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
  197. Setup::installBackgroundJobs();
  198. } catch (\Exception $e) {
  199. throw new \Exception($e->getMessage());
  200. }
  201. // update all shipped apps
  202. $this->checkAppsRequirements();
  203. $this->doAppUpgrade();
  204. // Update the appfetchers version so it downloads the correct list from the appstore
  205. \OC::$server->get(AppFetcher::class)->setVersion($currentVersion);
  206. /** @var AppManager $appManager */
  207. $appManager = \OC::$server->getAppManager();
  208. // upgrade appstore apps
  209. $this->upgradeAppStoreApps($appManager->getInstalledApps());
  210. $autoDisabledApps = $appManager->getAutoDisabledApps();
  211. if (!empty($autoDisabledApps)) {
  212. $this->upgradeAppStoreApps(array_keys($autoDisabledApps), $autoDisabledApps);
  213. }
  214. // install new shipped apps on upgrade
  215. $errors = Installer::installShippedApps(true);
  216. foreach ($errors as $appId => $exception) {
  217. /** @var \Exception $exception */
  218. $this->log->error($exception->getMessage(), [
  219. 'exception' => $exception,
  220. 'app' => $appId,
  221. ]);
  222. $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
  223. }
  224. // post-upgrade repairs
  225. $repair = \OCP\Server::get(Repair::class);
  226. $repair->setRepairSteps(Repair::getRepairSteps());
  227. $repair->run();
  228. //Invalidate update feed
  229. $this->appConfig->setValueInt('core', 'lastupdatedat', 0);
  230. // Check for code integrity if not disabled
  231. if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
  232. $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
  233. $this->checker->runInstanceVerification();
  234. $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
  235. }
  236. // only set the final version if everything went well
  237. $this->config->setSystemValue('version', implode('.', Util::getVersion()));
  238. $this->config->setAppValue('core', 'vendor', $this->getVendor());
  239. }
  240. protected function doCoreUpgrade(): void {
  241. $this->emit('\OC\Updater', 'dbUpgradeBefore');
  242. // execute core migrations
  243. $ms = new MigrationService('core', \OC::$server->get(Connection::class));
  244. $ms->migrate();
  245. $this->emit('\OC\Updater', 'dbUpgrade');
  246. }
  247. /**
  248. * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
  249. * (types authentication, filesystem, logging, in that order) afterwards.
  250. *
  251. * @throws NeedsUpdateException
  252. */
  253. protected function doAppUpgrade(): void {
  254. $apps = \OC_App::getEnabledApps();
  255. $priorityTypes = ['authentication', 'extended_authentication', 'filesystem', 'logging'];
  256. $pseudoOtherType = 'other';
  257. $stacks = [$pseudoOtherType => []];
  258. foreach ($apps as $appId) {
  259. $priorityType = false;
  260. foreach ($priorityTypes as $type) {
  261. if (!isset($stacks[$type])) {
  262. $stacks[$type] = [];
  263. }
  264. if (\OC_App::isType($appId, [$type])) {
  265. $stacks[$type][] = $appId;
  266. $priorityType = true;
  267. break;
  268. }
  269. }
  270. if (!$priorityType) {
  271. $stacks[$pseudoOtherType][] = $appId;
  272. }
  273. }
  274. foreach (array_merge($priorityTypes, [$pseudoOtherType]) as $type) {
  275. $stack = $stacks[$type];
  276. foreach ($stack as $appId) {
  277. if (\OC_App::shouldUpgrade($appId)) {
  278. $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OCP\Server::get(IAppManager::class)->getAppVersion($appId)]);
  279. \OC_App::updateApp($appId);
  280. $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OCP\Server::get(IAppManager::class)->getAppVersion($appId)]);
  281. }
  282. if ($type !== $pseudoOtherType) {
  283. // load authentication, filesystem and logging apps after
  284. // upgrading them. Other apps my need to rely on modifying
  285. // user and/or filesystem aspects.
  286. \OC_App::loadApp($appId);
  287. }
  288. }
  289. }
  290. }
  291. /**
  292. * check if the current enabled apps are compatible with the current
  293. * ownCloud version. disable them if not.
  294. * This is important if you upgrade ownCloud and have non ported 3rd
  295. * party apps installed.
  296. *
  297. * @throws \Exception
  298. */
  299. private function checkAppsRequirements(): void {
  300. $isCoreUpgrade = $this->isCodeUpgrade();
  301. $apps = OC_App::getEnabledApps();
  302. $version = implode('.', Util::getVersion());
  303. $appManager = \OC::$server->getAppManager();
  304. foreach ($apps as $app) {
  305. // check if the app is compatible with this version of Nextcloud
  306. $info = $appManager->getAppInfo($app);
  307. if ($info === null || !OC_App::isAppCompatible($version, $info)) {
  308. if ($appManager->isShipped($app)) {
  309. throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
  310. }
  311. $appManager->disableApp($app, true);
  312. $this->emit('\OC\Updater', 'incompatibleAppDisabled', [$app]);
  313. }
  314. }
  315. }
  316. /**
  317. * @return bool
  318. */
  319. private function isCodeUpgrade(): bool {
  320. $installedVersion = $this->config->getSystemValueString('version', '0.0.0');
  321. $currentVersion = implode('.', Util::getVersion());
  322. if (version_compare($currentVersion, $installedVersion, '>')) {
  323. return true;
  324. }
  325. return false;
  326. }
  327. /**
  328. * @param array $apps
  329. * @param array $previousEnableStates
  330. * @throws \Exception
  331. */
  332. private function upgradeAppStoreApps(array $apps, array $previousEnableStates = []): void {
  333. foreach ($apps as $app) {
  334. try {
  335. $this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
  336. if ($this->installer->isUpdateAvailable($app)) {
  337. $this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
  338. $this->installer->updateAppstoreApp($app);
  339. }
  340. $this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
  341. if (!empty($previousEnableStates)) {
  342. $ocApp = new \OC_App();
  343. if (!empty($previousEnableStates[$app]) && is_array($previousEnableStates[$app])) {
  344. $ocApp->enable($app, $previousEnableStates[$app]);
  345. } else {
  346. $ocApp->enable($app);
  347. }
  348. }
  349. } catch (\Exception $ex) {
  350. $this->log->error($ex->getMessage(), [
  351. 'exception' => $ex,
  352. ]);
  353. }
  354. }
  355. }
  356. private function logAllEvents(): void {
  357. $log = $this->log;
  358. /** @var IEventDispatcher $dispatcher */
  359. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  360. $dispatcher->addListener(
  361. MigratorExecuteSqlEvent::class,
  362. function (MigratorExecuteSqlEvent $event) use ($log): void {
  363. $log->info(get_class($event).': ' . $event->getSql() . ' (' . $event->getCurrentStep() . ' of ' . $event->getMaxStep() . ')', ['app' => 'updater']);
  364. }
  365. );
  366. $repairListener = function (Event $event) use ($log): void {
  367. if ($event instanceof RepairStartEvent) {
  368. $log->info(get_class($event).': Starting ... ' . $event->getMaxStep() . ' (' . $event->getCurrentStepName() . ')', ['app' => 'updater']);
  369. } elseif ($event instanceof RepairAdvanceEvent) {
  370. $desc = $event->getDescription();
  371. if (empty($desc)) {
  372. $desc = '';
  373. }
  374. $log->info(get_class($event).': ' . $desc . ' (' . $event->getIncrement() . ')', ['app' => 'updater']);
  375. } elseif ($event instanceof RepairFinishEvent) {
  376. $log->info(get_class($event), ['app' => 'updater']);
  377. } elseif ($event instanceof RepairStepEvent) {
  378. $log->info(get_class($event).': Repair step: ' . $event->getStepName(), ['app' => 'updater']);
  379. } elseif ($event instanceof RepairInfoEvent) {
  380. $log->info(get_class($event).': Repair info: ' . $event->getMessage(), ['app' => 'updater']);
  381. } elseif ($event instanceof RepairWarningEvent) {
  382. $log->warning(get_class($event).': Repair warning: ' . $event->getMessage(), ['app' => 'updater']);
  383. } elseif ($event instanceof RepairErrorEvent) {
  384. $log->error(get_class($event).': Repair error: ' . $event->getMessage(), ['app' => 'updater']);
  385. }
  386. };
  387. $dispatcher->addListener(RepairStartEvent::class, $repairListener);
  388. $dispatcher->addListener(RepairAdvanceEvent::class, $repairListener);
  389. $dispatcher->addListener(RepairFinishEvent::class, $repairListener);
  390. $dispatcher->addListener(RepairStepEvent::class, $repairListener);
  391. $dispatcher->addListener(RepairInfoEvent::class, $repairListener);
  392. $dispatcher->addListener(RepairWarningEvent::class, $repairListener);
  393. $dispatcher->addListener(RepairErrorEvent::class, $repairListener);
  394. $this->listen('\OC\Updater', 'maintenanceEnabled', function () use ($log) {
  395. $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
  396. });
  397. $this->listen('\OC\Updater', 'maintenanceDisabled', function () use ($log) {
  398. $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
  399. });
  400. $this->listen('\OC\Updater', 'maintenanceActive', function () use ($log) {
  401. $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
  402. });
  403. $this->listen('\OC\Updater', 'updateEnd', function ($success) use ($log) {
  404. if ($success) {
  405. $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
  406. } else {
  407. $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
  408. }
  409. });
  410. $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($log) {
  411. $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
  412. });
  413. $this->listen('\OC\Updater', 'dbUpgrade', function () use ($log) {
  414. $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
  415. });
  416. $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($log) {
  417. $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
  418. });
  419. $this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($log) {
  420. $log->debug('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
  421. });
  422. $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($log) {
  423. $log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
  424. });
  425. $this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($log) {
  426. $log->debug('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
  427. });
  428. $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
  429. $log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
  430. });
  431. $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
  432. $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
  433. });
  434. $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
  435. $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
  436. });
  437. $this->listen('\OC\Updater', 'failure', function ($message) use ($log) {
  438. $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
  439. });
  440. $this->listen('\OC\Updater', 'setDebugLogLevel', function () use ($log) {
  441. $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
  442. });
  443. $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($log) {
  444. $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
  445. });
  446. $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($log) {
  447. $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
  448. });
  449. $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log) {
  450. $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
  451. });
  452. }
  453. }