import.js 15 KB

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