import.js 16 KB

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