import.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /**
  2. * @typedef {import("@types/unzip-stream").Parse} Parse
  3. * @typedef {import("@types/unzip-stream").Entry} Entry
  4. */
  5. import fs from 'fs';
  6. import path from 'path';
  7. import { Writable, Transform } from 'stream';
  8. import JSONStream from 'JSONStream';
  9. import gc from 'expose-gc/function';
  10. import mongoose from 'mongoose';
  11. import streamToPromise from 'stream-to-promise';
  12. import unzipStream from 'unzip-stream';
  13. import { setupIndependentModels } from '~/server/crowi/setup-models';
  14. import loggerFactory from '~/utils/logger';
  15. import CollectionProgressingStatus from '../../models/vo/collection-progressing-status';
  16. import { createBatchStream } from '../../util/batch-stream';
  17. import { constructConvertMap } from './construct-convert-map';
  18. import { getModelFromCollectionName } from './get-model-from-collection-name';
  19. import { keepOriginal } from './overwrite-function';
  20. const logger = loggerFactory('growi:services:ImportService'); // eslint-disable-line no-unused-vars
  21. const BULK_IMPORT_SIZE = 100;
  22. class ImportingCollectionError extends Error {
  23. constructor(collectionProgress, error) {
  24. super(error);
  25. this.collectionProgress = collectionProgress;
  26. }
  27. }
  28. export class ImportService {
  29. constructor(crowi) {
  30. this.crowi = crowi;
  31. this.growiBridgeService = crowi.growiBridgeService;
  32. this.getFile = this.growiBridgeService.getFile.bind(this);
  33. this.baseDir = path.join(crowi.tmpDir, 'imports');
  34. this.adminEvent = crowi.event('admin');
  35. this.currentProgressingStatus = null;
  36. }
  37. /**
  38. * parse all zip files in downloads dir
  39. *
  40. * @memberOf ExportService
  41. * @return {object} info for zip files and whether currentProgressingStatus exists
  42. */
  43. async getStatus() {
  44. const zipFiles = fs.readdirSync(this.baseDir).filter(file => path.extname(file) === '.zip');
  45. // process serially so as not to waste memory
  46. const zipFileStats = [];
  47. const parseZipFilePromises = zipFiles.map((file) => {
  48. const zipFile = this.getFile(file);
  49. return this.growiBridgeService.parseZipFile(zipFile);
  50. });
  51. for await (const stat of parseZipFilePromises) {
  52. zipFileStats.push(stat);
  53. }
  54. // filter null object (broken zip)
  55. const filtered = zipFileStats
  56. .filter(zipFileStat => zipFileStat != null);
  57. // sort with ctime("Change Time" - Time when file status was last changed (inode data modification).)
  58. filtered.sort((a, b) => { return a.fileStat.ctime - b.fileStat.ctime });
  59. const isImporting = this.currentProgressingStatus != null;
  60. const zipFileStat = filtered.pop();
  61. let isTheSameVersion = false;
  62. if (zipFileStat != null) {
  63. try {
  64. this.validate(zipFileStat.meta);
  65. isTheSameVersion = true;
  66. }
  67. catch (err) {
  68. isTheSameVersion = false;
  69. logger.error('the versions are not met', err);
  70. }
  71. }
  72. return {
  73. isTheSameVersion,
  74. zipFileStat,
  75. isImporting,
  76. progressList: isImporting ? this.currentProgressingStatus.progressList : null,
  77. };
  78. }
  79. async preImport() {
  80. await setupIndependentModels();
  81. // initialize convertMap
  82. /** @type {import('./construct-convert-map').ConvertMap} */
  83. this.convertMap = constructConvertMap();
  84. }
  85. /**
  86. * import collections from json
  87. *
  88. * @param {string[]} collections MongoDB collection name
  89. * @param {{ [collectionName: string]: ImportSettings }} importSettingsMap key: collection name, value: ImportSettings instance
  90. * @return {Promise<void>}
  91. */
  92. async import(collections, importSettingsMap) {
  93. await this.preImport();
  94. // init status object
  95. this.currentProgressingStatus = new CollectionProgressingStatus(collections);
  96. // process serially so as not to waste memory
  97. const promises = collections.map((collectionName) => {
  98. const importSettings = importSettingsMap[collectionName];
  99. return this.importCollection(collectionName, importSettings);
  100. });
  101. for await (const promise of promises) {
  102. try {
  103. await promise;
  104. }
  105. // catch ImportingCollectionError
  106. catch (err) {
  107. const { collectionProgress } = err;
  108. logger.error(`failed to import to ${collectionProgress.collectionName}`, err);
  109. this.emitProgressEvent(collectionProgress, { message: err.message });
  110. }
  111. }
  112. this.currentProgressingStatus = null;
  113. this.emitTerminateEvent();
  114. await this.crowi.configManager.loadConfigs();
  115. const currentIsV5Compatible = this.crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  116. const isImportPagesCollection = collections.includes('pages');
  117. const shouldNormalizePages = currentIsV5Compatible && isImportPagesCollection;
  118. if (shouldNormalizePages) await this.crowi.pageService.normalizeAllPublicPages();
  119. }
  120. /**
  121. * import a collection from json
  122. *
  123. * @memberOf ImportService
  124. * @param {string} collectionName MongoDB collection name
  125. * @param {ImportSettings} importSettings
  126. * @return {insertedIds: Array.<string>, failedIds: Array.<string>}
  127. */
  128. async importCollection(collectionName, importSettings) {
  129. // prepare functions invoked from custom streams
  130. const convertDocuments = this.convertDocuments.bind(this);
  131. const bulkOperate = this.bulkOperate.bind(this);
  132. const execUnorderedBulkOpSafely = this.execUnorderedBulkOpSafely.bind(this);
  133. const emitProgressEvent = this.emitProgressEvent.bind(this);
  134. const collection = mongoose.connection.collection(collectionName);
  135. const { mode, jsonFileName, overwriteParams } = importSettings;
  136. const collectionProgress = this.currentProgressingStatus.progressMap[collectionName];
  137. try {
  138. const jsonFile = this.getFile(jsonFileName);
  139. // validate options
  140. this.validateImportSettings(collectionName, importSettings);
  141. // flush
  142. if (mode === 'flushAndInsert') {
  143. await collection.deleteMany({});
  144. }
  145. // stream 1
  146. const readStream = fs.createReadStream(jsonFile, { encoding: this.growiBridgeService.getEncoding() });
  147. // stream 2
  148. const jsonStream = JSONStream.parse('*');
  149. // stream 3
  150. const convertStream = new Transform({
  151. objectMode: true,
  152. transform(doc, encoding, callback) {
  153. const converted = convertDocuments(collectionName, doc, overwriteParams);
  154. this.push(converted);
  155. callback();
  156. },
  157. });
  158. // stream 4
  159. const batchStream = createBatchStream(BULK_IMPORT_SIZE);
  160. // stream 5
  161. const writeStream = new Writable({
  162. objectMode: true,
  163. async write(batch, encoding, callback) {
  164. const unorderedBulkOp = collection.initializeUnorderedBulkOp();
  165. // documents are not persisted until unorderedBulkOp.execute()
  166. batch.forEach((document) => {
  167. bulkOperate(unorderedBulkOp, collectionName, document, importSettings);
  168. });
  169. // exec
  170. const { insertedCount, modifiedCount, errors } = await execUnorderedBulkOpSafely(unorderedBulkOp);
  171. logger.debug(`Importing ${collectionName}. Inserted: ${insertedCount}. Modified: ${modifiedCount}. Failed: ${errors.length}.`);
  172. const increment = insertedCount + modifiedCount + errors.length;
  173. collectionProgress.currentCount += increment;
  174. collectionProgress.totalCount += increment;
  175. collectionProgress.insertedCount += insertedCount;
  176. collectionProgress.modifiedCount += modifiedCount;
  177. emitProgressEvent(collectionProgress, errors);
  178. try {
  179. // First aid to prevent unexplained memory leaks
  180. logger.info('global.gc() invoked.');
  181. gc();
  182. }
  183. catch (err) {
  184. logger.error('fail garbage collection: ', err);
  185. }
  186. callback();
  187. },
  188. final(callback) {
  189. logger.info(`Importing ${collectionName} has completed.`);
  190. callback();
  191. },
  192. });
  193. readStream
  194. .pipe(jsonStream)
  195. .pipe(convertStream)
  196. .pipe(batchStream)
  197. .pipe(writeStream);
  198. await streamToPromise(writeStream);
  199. // clean up tmp directory
  200. fs.unlinkSync(jsonFile);
  201. }
  202. catch (err) {
  203. throw new ImportingCollectionError(collectionProgress, err);
  204. }
  205. }
  206. /**
  207. *
  208. * @param {string} collectionName
  209. * @param {importSettings} importSettings
  210. */
  211. validateImportSettings(collectionName, importSettings) {
  212. const { mode } = importSettings;
  213. switch (collectionName) {
  214. case 'configs':
  215. if (mode !== 'flushAndInsert') {
  216. throw new Error(`The specified mode '${mode}' is not allowed when importing to 'configs' collection.`);
  217. }
  218. break;
  219. }
  220. }
  221. /**
  222. * process bulk operation
  223. * @param {object} bulk MongoDB Bulk instance
  224. * @param {string} collectionName collection name
  225. * @param {object} document
  226. * @param {ImportSettings} importSettings
  227. */
  228. bulkOperate(bulk, collectionName, document, importSettings) {
  229. // insert
  230. if (importSettings.mode !== 'upsert') {
  231. return bulk.insert(document);
  232. }
  233. // upsert
  234. switch (collectionName) {
  235. case 'pages':
  236. return bulk.find({ path: document.path }).upsert().replaceOne(document);
  237. default:
  238. return bulk.find({ _id: document._id }).upsert().replaceOne(document);
  239. }
  240. }
  241. /**
  242. * emit progress event
  243. * @param {CollectionProgress} collectionProgress
  244. * @param {object} appendedErrors key: collection name, value: array of error object
  245. */
  246. emitProgressEvent(collectionProgress, appendedErrors) {
  247. const { collectionName } = collectionProgress;
  248. // send event (in progress in global)
  249. this.adminEvent.emit('onProgressForImport', { collectionName, collectionProgress, appendedErrors });
  250. }
  251. /**
  252. * emit terminate event
  253. */
  254. emitTerminateEvent() {
  255. this.adminEvent.emit('onTerminateForImport');
  256. }
  257. /**
  258. * extract a zip file
  259. *
  260. * @memberOf ImportService
  261. * @param {string} zipFile absolute path to zip file
  262. * @return {Array.<string>} array of absolute paths to extracted files
  263. */
  264. async unzip(zipFile) {
  265. const readStream = fs.createReadStream(zipFile);
  266. const unzipStreamPipe = readStream.pipe(unzipStream.Parse());
  267. const files = [];
  268. unzipStreamPipe.on('entry', (/** @type {Entry} */ entry) => {
  269. const fileName = entry.path;
  270. // https://regex101.com/r/mD4eZs/6
  271. // prevent from unexpecting attack doing unzip file (path traversal attack)
  272. // FOR EXAMPLE
  273. // ../../src/server/example.html
  274. if (fileName.match(/(\.\.\/|\.\.\\)/)) {
  275. logger.error('File path is not appropriate.', fileName);
  276. return;
  277. }
  278. if (fileName === this.growiBridgeService.getMetaFileName()) {
  279. // skip meta.json
  280. entry.autodrain();
  281. }
  282. else {
  283. const jsonFile = path.join(this.baseDir, fileName);
  284. const writeStream = fs.createWriteStream(jsonFile, { encoding: this.growiBridgeService.getEncoding() });
  285. entry.pipe(writeStream);
  286. files.push(jsonFile);
  287. }
  288. });
  289. await streamToPromise(unzipStreamPipe);
  290. return files;
  291. }
  292. /**
  293. * execute unorderedBulkOp and ignore errors
  294. *
  295. * @memberOf ImportService
  296. * @param {object} unorderedBulkOp result of Model.collection.initializeUnorderedBulkOp()
  297. * @return {object} e.g. { insertedCount: 10, errors: [...] }
  298. */
  299. async execUnorderedBulkOpSafely(unorderedBulkOp) {
  300. let errors = [];
  301. let result = null;
  302. try {
  303. const log = await unorderedBulkOp.execute();
  304. result = log.result;
  305. }
  306. catch (err) {
  307. result = err.result;
  308. errors = err.writeErrors || [err];
  309. errors.map((err) => {
  310. const moreDetailErr = err.err;
  311. return { _id: moreDetailErr.op._id, message: err.errmsg };
  312. });
  313. }
  314. const insertedCount = result.nInserted + result.nUpserted;
  315. const modifiedCount = result.nModified;
  316. return {
  317. insertedCount,
  318. modifiedCount,
  319. errors,
  320. };
  321. }
  322. /**
  323. * execute unorderedBulkOp and ignore errors
  324. *
  325. * @memberOf ImportService
  326. * @param {string} collectionName
  327. * @param {object} document document being imported
  328. * @param {object} overwriteParams overwrite each document with unrelated value. e.g. { creator: req.user }
  329. * @return {object} document to be persisted
  330. */
  331. convertDocuments(collectionName, document, overwriteParams) {
  332. const Model = getModelFromCollectionName(collectionName);
  333. const schema = (Model != null) ? Model.schema : null;
  334. const convertMap = this.convertMap[collectionName];
  335. const _document = {};
  336. // not Mongoose Model
  337. if (convertMap == null) {
  338. // apply keepOriginal to all of properties
  339. Object.entries(document).forEach(([propertyName, value]) => {
  340. _document[propertyName] = keepOriginal(value, { document, propertyName });
  341. });
  342. }
  343. // Mongoose Model
  344. else {
  345. // assign value from documents being imported
  346. Object.entries(convertMap).forEach(([propertyName, convertedValue]) => {
  347. const value = document[propertyName];
  348. // distinguish between null and undefined
  349. if (value === undefined) {
  350. return; // next entry
  351. }
  352. const convertFunc = (typeof convertedValue === 'function') ? convertedValue : null;
  353. _document[propertyName] = (convertFunc != null) ? convertFunc(value, { document, propertyName, schema }) : convertedValue;
  354. });
  355. }
  356. // overwrite documents with custom values
  357. Object.entries(overwriteParams).forEach(([propertyName, overwriteValue]) => {
  358. const value = document[propertyName];
  359. // distinguish between null and undefined
  360. if (value !== undefined) {
  361. const overwriteFunc = (typeof overwriteValue === 'function') ? overwriteValue : null;
  362. _document[propertyName] = (overwriteFunc != null) ? overwriteFunc(value, { document: _document, propertyName, schema }) : overwriteValue;
  363. }
  364. });
  365. return _document;
  366. }
  367. /**
  368. * validate using meta.json
  369. * to pass validation, all the criteria must be met
  370. * - ${version of this GROWI} === ${version of GROWI that exported data}
  371. *
  372. * @memberOf ImportService
  373. * @param {object} meta meta data from meta.json
  374. */
  375. validate(meta) {
  376. if (meta.version !== this.crowi.version) {
  377. throw new Error('The version of this GROWI and the uploaded GROWI data are not the same');
  378. }
  379. // TODO: check if all migrations are completed
  380. // - export: throw err if there are pending migrations
  381. // - import: throw err if there are pending migrations
  382. }
  383. /**
  384. * Delete all uploaded files
  385. */
  386. deleteAllZipFiles() {
  387. fs.readdirSync(this.baseDir)
  388. .filter(file => path.extname(file) === '.zip')
  389. .forEach(file => fs.unlinkSync(path.join(this.baseDir, file)));
  390. }
  391. }