Updater.php 19 KB

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