import.js 16 KB

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