Updater.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 an ownCloud data directory
  185. // (in case it didn't exist before)
  186. file_put_contents($this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
  187. // pre-upgrade repairs
  188. $repair = \OCP\Server::get(Repair::class);
  189. $repair->setRepairSteps(Repair::getBeforeUpgradeRepairSteps());
  190. $repair->run();
  191. $this->doCoreUpgrade();
  192. try {
  193. // TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
  194. Setup::installBackgroundJobs();
  195. } catch (\Exception $e) {
  196. throw new \Exception($e->getMessage());
  197. }
  198. // update all shipped apps
  199. $this->checkAppsRequirements();
  200. $this->doAppUpgrade();
  201. // Update the appfetchers version so it downloads the correct list from the appstore
  202. \OC::$server->get(AppFetcher::class)->setVersion($currentVersion);
  203. /** @var AppManager $appManager */
  204. $appManager = \OC::$server->getAppManager();
  205. // upgrade appstore apps
  206. $this->upgradeAppStoreApps($appManager->getInstalledApps());
  207. $autoDisabledApps = $appManager->getAutoDisabledApps();
  208. if (!empty($autoDisabledApps)) {
  209. $this->upgradeAppStoreApps(array_keys($autoDisabledApps), $autoDisabledApps);
  210. }
  211. // install new shipped apps on upgrade
  212. $errors = Installer::installShippedApps(true);
  213. foreach ($errors as $appId => $exception) {
  214. /** @var \Exception $exception */
  215. $this->log->error($exception->getMessage(), [
  216. 'exception' => $exception,
  217. 'app' => $appId,
  218. ]);
  219. $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
  220. }
  221. // post-upgrade repairs
  222. $repair = \OCP\Server::get(Repair::class);
  223. $repair->setRepairSteps(Repair::getRepairSteps());
  224. $repair->run();
  225. //Invalidate update feed
  226. $this->appConfig->setValueInt('core', 'lastupdatedat', 0);
  227. // Check for code integrity if not disabled
  228. if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
  229. $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
  230. $this->checker->runInstanceVerification();
  231. $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
  232. }
  233. // only set the final version if everything went well
  234. $this->config->setSystemValue('version', implode('.', Util::getVersion()));
  235. $this->config->setAppValue('core', 'vendor', $this->getVendor());
  236. }
  237. protected function doCoreUpgrade(): void {
  238. $this->emit('\OC\Updater', 'dbUpgradeBefore');
  239. // execute core migrations
  240. $ms = new MigrationService('core', \OC::$server->get(Connection::class));
  241. $ms->migrate();
  242. $this->emit('\OC\Updater', 'dbUpgrade');
  243. }
  244. /**
  245. * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
  246. * (types authentication, filesystem, logging, in that order) afterwards.
  247. *
  248. * @throws NeedsUpdateException
  249. */
  250. protected function doAppUpgrade(): void {
  251. $apps = \OC_App::getEnabledApps();
  252. $priorityTypes = ['authentication', 'extended_authentication', 'filesystem', 'logging'];
  253. $pseudoOtherType = 'other';
  254. $stacks = [$pseudoOtherType => []];
  255. foreach ($apps as $appId) {
  256. $priorityType = false;
  257. foreach ($priorityTypes as $type) {
  258. if (!isset($stacks[$type])) {
  259. $stacks[$type] = [];
  260. }
  261. if (\OC_App::isType($appId, [$type])) {
  262. $stacks[$type][] = $appId;
  263. $priorityType = true;
  264. break;
  265. }
  266. }
  267. if (!$priorityType) {
  268. $stacks[$pseudoOtherType][] = $appId;
  269. }
  270. }
  271. foreach (array_merge($priorityTypes, [$pseudoOtherType]) as $type) {
  272. $stack = $stacks[$type];
  273. foreach ($stack as $appId) {
  274. if (\OC_App::shouldUpgrade($appId)) {
  275. $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OCP\Server::get(IAppManager::class)->getAppVersion($appId)]);
  276. \OC_App::updateApp($appId);
  277. $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OCP\Server::get(IAppManager::class)->getAppVersion($appId)]);
  278. }
  279. if ($type !== $pseudoOtherType) {
  280. // load authentication, filesystem and logging apps after
  281. // upgrading them. Other apps my need to rely on modifying
  282. // user and/or filesystem aspects.
  283. \OC_App::loadApp($appId);
  284. }
  285. }
  286. }
  287. }
  288. /**
  289. * check if the current enabled apps are compatible with the current
  290. * ownCloud version. disable them if not.
  291. * This is important if you upgrade ownCloud and have non ported 3rd
  292. * party apps installed.
  293. *
  294. * @throws \Exception
  295. */
  296. private function checkAppsRequirements(): void {
  297. $isCoreUpgrade = $this->isCodeUpgrade();
  298. $apps = OC_App::getEnabledApps();
  299. $version = implode('.', Util::getVersion());
  300. $appManager = \OC::$server->getAppManager();
  301. foreach ($apps as $app) {
  302. // check if the app is compatible with this version of Nextcloud
  303. $info = $appManager->getAppInfo($app);
  304. if ($info === null || !OC_App::isAppCompatible($version, $info)) {
  305. if ($appManager->isShipped($app)) {
  306. throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
  307. }
  308. $appManager->disableApp($app, true);
  309. $this->emit('\OC\Updater', 'incompatibleAppDisabled', [$app]);
  310. }
  311. }
  312. }
  313. /**
  314. * @return bool
  315. */
  316. private function isCodeUpgrade(): bool {
  317. $installedVersion = $this->config->getSystemValueString('version', '0.0.0');
  318. $currentVersion = implode('.', Util::getVersion());
  319. if (version_compare($currentVersion, $installedVersion, '>')) {
  320. return true;
  321. }
  322. return false;
  323. }
  324. /**
  325. * @param array $apps
  326. * @param array $previousEnableStates
  327. * @throws \Exception
  328. */
  329. private function upgradeAppStoreApps(array $apps, array $previousEnableStates = []): void {
  330. foreach ($apps as $app) {
  331. try {
  332. $this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
  333. if ($this->installer->isUpdateAvailable($app)) {
  334. $this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
  335. $this->installer->updateAppstoreApp($app);
  336. }
  337. $this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
  338. if (!empty($previousEnableStates)) {
  339. $ocApp = new \OC_App();
  340. if (!empty($previousEnableStates[$app]) && is_array($previousEnableStates[$app])) {
  341. $ocApp->enable($app, $previousEnableStates[$app]);
  342. } else {
  343. $ocApp->enable($app);
  344. }
  345. }
  346. } catch (\Exception $ex) {
  347. $this->log->error($ex->getMessage(), [
  348. 'exception' => $ex,
  349. ]);
  350. }
  351. }
  352. }
  353. private function logAllEvents(): void {
  354. $log = $this->log;
  355. /** @var IEventDispatcher $dispatcher */
  356. $dispatcher = \OC::$server->get(IEventDispatcher::class);
  357. $dispatcher->addListener(
  358. MigratorExecuteSqlEvent::class,
  359. function (MigratorExecuteSqlEvent $event) use ($log): void {
  360. $log->info(get_class($event).': ' . $event->getSql() . ' (' . $event->getCurrentStep() . ' of ' . $event->getMaxStep() . ')', ['app' => 'updater']);
  361. }
  362. );
  363. $repairListener = function (Event $event) use ($log): void {
  364. if ($event instanceof RepairStartEvent) {
  365. $log->info(get_class($event).': Starting ... ' . $event->getMaxStep() . ' (' . $event->getCurrentStepName() . ')', ['app' => 'updater']);
  366. } elseif ($event instanceof RepairAdvanceEvent) {
  367. $desc = $event->getDescription();
  368. if (empty($desc)) {
  369. $desc = '';
  370. }
  371. $log->info(get_class($event).': ' . $desc . ' (' . $event->getIncrement() . ')', ['app' => 'updater']);
  372. } elseif ($event instanceof RepairFinishEvent) {
  373. $log->info(get_class($event), ['app' => 'updater']);
  374. } elseif ($event instanceof RepairStepEvent) {
  375. $log->info(get_class($event).': Repair step: ' . $event->getStepName(), ['app' => 'updater']);
  376. } elseif ($event instanceof RepairInfoEvent) {
  377. $log->info(get_class($event).': Repair info: ' . $event->getMessage(), ['app' => 'updater']);
  378. } elseif ($event instanceof RepairWarningEvent) {
  379. $log->warning(get_class($event).': Repair warning: ' . $event->getMessage(), ['app' => 'updater']);
  380. } elseif ($event instanceof RepairErrorEvent) {
  381. $log->error(get_class($event).': Repair error: ' . $event->getMessage(), ['app' => 'updater']);
  382. }
  383. };
  384. $dispatcher->addListener(RepairStartEvent::class, $repairListener);
  385. $dispatcher->addListener(RepairAdvanceEvent::class, $repairListener);
  386. $dispatcher->addListener(RepairFinishEvent::class, $repairListener);
  387. $dispatcher->addListener(RepairStepEvent::class, $repairListener);
  388. $dispatcher->addListener(RepairInfoEvent::class, $repairListener);
  389. $dispatcher->addListener(RepairWarningEvent::class, $repairListener);
  390. $dispatcher->addListener(RepairErrorEvent::class, $repairListener);
  391. $this->listen('\OC\Updater', 'maintenanceEnabled', function () use ($log) {
  392. $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
  393. });
  394. $this->listen('\OC\Updater', 'maintenanceDisabled', function () use ($log) {
  395. $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
  396. });
  397. $this->listen('\OC\Updater', 'maintenanceActive', function () use ($log) {
  398. $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
  399. });
  400. $this->listen('\OC\Updater', 'updateEnd', function ($success) use ($log) {
  401. if ($success) {
  402. $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
  403. } else {
  404. $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
  405. }
  406. });
  407. $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use ($log) {
  408. $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
  409. });
  410. $this->listen('\OC\Updater', 'dbUpgrade', function () use ($log) {
  411. $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
  412. });
  413. $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use ($log) {
  414. $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
  415. });
  416. $this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($log) {
  417. $log->debug('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
  418. });
  419. $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($log) {
  420. $log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
  421. });
  422. $this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($log) {
  423. $log->debug('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
  424. });
  425. $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
  426. $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']);
  427. });
  428. $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
  429. $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
  430. });
  431. $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
  432. $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
  433. });
  434. $this->listen('\OC\Updater', 'failure', function ($message) use ($log) {
  435. $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
  436. });
  437. $this->listen('\OC\Updater', 'setDebugLogLevel', function () use ($log) {
  438. $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
  439. });
  440. $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use ($log) {
  441. $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
  442. });
  443. $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use ($log) {
  444. $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
  445. });
  446. $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use ($log) {
  447. $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
  448. });
  449. }
  450. }