import.js 15 KB

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