repairlegacystorages.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <?php
  2. /**
  3. * @author Joas Schilling <nickvergessen@owncloud.com>
  4. * @author Morris Jobke <hey@morrisjobke.de>
  5. * @author Vincent Petry <pvince81@owncloud.com>
  6. *
  7. * @copyright Copyright (c) 2015, ownCloud, Inc.
  8. * @license AGPL-3.0
  9. *
  10. * This code is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License, version 3,
  12. * as published by the Free Software Foundation.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License, version 3,
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>
  21. *
  22. */
  23. namespace OC\Repair;
  24. use OC\Files\Cache\Storage;
  25. use OC\Hooks\BasicEmitter;
  26. use OC\RepairException;
  27. class RepairLegacyStorages extends BasicEmitter {
  28. /**
  29. * @var \OCP\IConfig
  30. */
  31. protected $config;
  32. /**
  33. * @var \OCP\IDBConnection
  34. */
  35. protected $connection;
  36. protected $findStorageInCacheStatement;
  37. protected $renameStorageStatement;
  38. /**
  39. * @param \OCP\IConfig $config
  40. * @param \OCP\IDBConnection $connection
  41. */
  42. public function __construct($config, $connection) {
  43. $this->connection = $connection;
  44. $this->config = $config;
  45. $this->findStorageInCacheStatement = $this->connection->prepare(
  46. 'SELECT DISTINCT `storage` FROM `*PREFIX*filecache`'
  47. . ' WHERE `storage` in (?, ?)'
  48. );
  49. $this->renameStorageStatement = $this->connection->prepare(
  50. 'UPDATE `*PREFIX*storages`'
  51. . ' SET `id` = ?'
  52. . ' WHERE `id` = ?'
  53. );
  54. }
  55. public function getName() {
  56. return 'Repair legacy storages';
  57. }
  58. /**
  59. * Extracts the user id from a legacy storage id
  60. *
  61. * @param string $storageId legacy storage id in the
  62. * format "local::/path/to/datadir/userid"
  63. * @return string user id extracted from the storage id
  64. */
  65. private function extractUserId($storageId) {
  66. $storageId = rtrim($storageId, '/');
  67. $pos = strrpos($storageId, '/');
  68. return substr($storageId, $pos + 1);
  69. }
  70. /**
  71. * Fix the given legacy storage by renaming the old id
  72. * to the new id. If the new id already exists, whichever
  73. * storage that has data in the file cache will be used.
  74. * If both have data, nothing will be done and false is
  75. * returned.
  76. *
  77. * @param string $oldId old storage id
  78. * @param int $oldNumericId old storage numeric id
  79. * @param string $userId
  80. * @return bool true if fixed, false otherwise
  81. * @throws RepairException
  82. */
  83. private function fixLegacyStorage($oldId, $oldNumericId, $userId = null) {
  84. // check whether the new storage already exists
  85. if (is_null($userId)) {
  86. $userId = $this->extractUserId($oldId);
  87. }
  88. $newId = 'home::' . $userId;
  89. // check if target id already exists
  90. $newNumericId = Storage::getNumericStorageId($newId);
  91. if (!is_null($newNumericId)) {
  92. $newNumericId = (int)$newNumericId;
  93. // try and resolve the conflict
  94. // check which one of "local::" or "home::" needs to be kept
  95. $this->findStorageInCacheStatement->execute(array($oldNumericId, $newNumericId));
  96. $row1 = $this->findStorageInCacheStatement->fetch();
  97. $row2 = $this->findStorageInCacheStatement->fetch();
  98. $this->findStorageInCacheStatement->closeCursor();
  99. if ($row2 !== false) {
  100. // two results means both storages have data, not auto-fixable
  101. throw new RepairException(
  102. 'Could not automatically fix legacy storage '
  103. . '"' . $oldId . '" => "' . $newId . '"'
  104. . ' because they both have data.'
  105. );
  106. }
  107. if ($row1 === false || (int)$row1['storage'] === $oldNumericId) {
  108. // old storage has data, then delete the empty new id
  109. $toDelete = $newId;
  110. } else if ((int)$row1['storage'] === $newNumericId) {
  111. // new storage has data, then delete the empty old id
  112. $toDelete = $oldId;
  113. } else {
  114. // unknown case, do not continue
  115. return false;
  116. }
  117. // delete storage including file cache
  118. Storage::remove($toDelete);
  119. // if we deleted the old id, the new id will be used
  120. // automatically
  121. if ($toDelete === $oldId) {
  122. // nothing more to do
  123. return true;
  124. }
  125. }
  126. // rename old id to new id
  127. $newId = Storage::adjustStorageId($newId);
  128. $oldId = Storage::adjustStorageId($oldId);
  129. $rowCount = $this->renameStorageStatement->execute(array($newId, $oldId));
  130. $this->renameStorageStatement->closeCursor();
  131. return ($rowCount === 1);
  132. }
  133. /**
  134. * Converts legacy home storage ids in the format
  135. * "local::/data/dir/path/userid/" to the new format "home::userid"
  136. */
  137. public function run() {
  138. // only run once
  139. if ($this->config->getAppValue('core', 'repairlegacystoragesdone') === 'yes') {
  140. return;
  141. }
  142. $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
  143. $dataDir = rtrim($dataDir, '/') . '/';
  144. $dataDirId = 'local::' . $dataDir;
  145. $count = 0;
  146. $hasWarnings = false;
  147. $this->connection->beginTransaction();
  148. // note: not doing a direct UPDATE with the REPLACE function
  149. // because regexp search/extract is needed and it is not guaranteed
  150. // to work on all database types
  151. $sql = 'SELECT `id`, `numeric_id` FROM `*PREFIX*storages`'
  152. . ' WHERE `id` LIKE ?'
  153. . ' ORDER BY `id`';
  154. $result = $this->connection->executeQuery($sql, array($dataDirId . '%'));
  155. while ($row = $result->fetch()) {
  156. $currentId = $row['id'];
  157. // one entry is the datadir itself
  158. if ($currentId === $dataDirId) {
  159. continue;
  160. }
  161. try {
  162. if ($this->fixLegacyStorage($currentId, (int)$row['numeric_id'])) {
  163. $count++;
  164. }
  165. }
  166. catch (RepairException $e) {
  167. $hasWarnings = true;
  168. $this->emit(
  169. '\OC\Repair',
  170. 'warning',
  171. array('Could not repair legacy storage ' . $currentId . ' automatically.')
  172. );
  173. }
  174. }
  175. // check for md5 ids, not in the format "prefix::"
  176. $sql = 'SELECT COUNT(*) AS "c" FROM `*PREFIX*storages`'
  177. . ' WHERE `id` NOT LIKE \'%::%\'';
  178. $result = $this->connection->executeQuery($sql);
  179. $row = $result->fetch();
  180. // find at least one to make sure it's worth
  181. // querying the user list
  182. if ((int)$row['c'] > 0) {
  183. $userManager = \OC::$server->getUserManager();
  184. // use chunks to avoid caching too many users in memory
  185. $limit = 30;
  186. $offset = 0;
  187. do {
  188. // query the next page of users
  189. $results = $userManager->search('', $limit, $offset);
  190. $storageIds = array();
  191. foreach ($results as $uid => $userObject) {
  192. $storageId = $dataDirId . $uid . '/';
  193. if (strlen($storageId) <= 64) {
  194. // skip short storage ids as they were handled in the previous section
  195. continue;
  196. }
  197. $storageIds[$uid] = $storageId;
  198. }
  199. if (count($storageIds) > 0) {
  200. // update the storages of these users
  201. foreach ($storageIds as $uid => $storageId) {
  202. $numericId = Storage::getNumericStorageId($storageId);
  203. try {
  204. if (!is_null($numericId) && $this->fixLegacyStorage($storageId, (int)$numericId)) {
  205. $count++;
  206. }
  207. }
  208. catch (RepairException $e) {
  209. $hasWarnings = true;
  210. $this->emit(
  211. '\OC\Repair',
  212. 'warning',
  213. array('Could not repair legacy storage ' . $storageId . ' automatically.')
  214. );
  215. }
  216. }
  217. }
  218. $offset += $limit;
  219. } while (count($results) >= $limit);
  220. }
  221. $this->emit('\OC\Repair', 'info', array('Updated ' . $count . ' legacy home storage ids'));
  222. $this->connection->commit();
  223. if ($hasWarnings) {
  224. $this->emit(
  225. '\OC\Repair',
  226. 'warning',
  227. array('Some legacy storages could not be repaired. Please manually fix them then re-run ./occ maintenance:repair')
  228. );
  229. } else {
  230. // if all were done, no need to redo the repair during next upgrade
  231. $this->config->setAppValue('core', 'repairlegacystoragesdone', 'yes');
  232. }
  233. }
  234. }