import.js 16 KB

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