import.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. return {
  118. zipFileStat: filtered.pop(),
  119. isImporting,
  120. progressList: isImporting ? this.currentProgressingStatus.progressList : null,
  121. };
  122. }
  123. /**
  124. * import collections from json
  125. *
  126. * @param {string} collections MongoDB collection name
  127. * @param {array} importSettingsMap key: collection name, value: ImportSettings instance
  128. */
  129. async import(collections, importSettingsMap) {
  130. // init status object
  131. this.currentProgressingStatus = new CollectionProgressingStatus(collections);
  132. // process serially so as not to waste memory
  133. const promises = collections.map((collectionName) => {
  134. const importSettings = importSettingsMap[collectionName];
  135. return this.importCollection(collectionName, importSettings);
  136. });
  137. for await (const promise of promises) {
  138. try {
  139. await promise;
  140. }
  141. // catch ImportingCollectionError
  142. catch (err) {
  143. const { collectionProgress } = err;
  144. logger.error(`failed to import to ${collectionProgress.collectionName}`, err);
  145. this.emitProgressEvent(collectionProgress, { message: err.message });
  146. }
  147. }
  148. this.currentProgressingStatus = null;
  149. this.emitTerminateEvent();
  150. }
  151. /**
  152. * import a collection from json
  153. *
  154. * @memberOf ImportService
  155. * @param {string} collectionName MongoDB collection name
  156. * @param {ImportSettings} importSettings
  157. * @return {insertedIds: Array.<string>, failedIds: Array.<string>}
  158. */
  159. async importCollection(collectionName, importSettings) {
  160. // prepare functions invoked from custom streams
  161. const convertDocuments = this.convertDocuments.bind(this);
  162. const bulkOperate = this.bulkOperate.bind(this);
  163. const execUnorderedBulkOpSafely = this.execUnorderedBulkOpSafely.bind(this);
  164. const emitProgressEvent = this.emitProgressEvent.bind(this);
  165. const collection = mongoose.connection.collection(collectionName);
  166. const { mode, jsonFileName, overwriteParams } = importSettings;
  167. const collectionProgress = this.currentProgressingStatus.progressMap[collectionName];
  168. try {
  169. const jsonFile = this.getFile(jsonFileName);
  170. // validate options
  171. this.validateImportSettings(collectionName, importSettings);
  172. // flush
  173. if (mode === 'flushAndInsert') {
  174. await collection.deleteMany({});
  175. }
  176. // stream 1
  177. const readStream = fs.createReadStream(jsonFile, { encoding: this.growiBridgeService.getEncoding() });
  178. // stream 2
  179. const jsonStream = JSONStream.parse('*');
  180. // stream 3
  181. const convertStream = new Transform({
  182. objectMode: true,
  183. transform(doc, encoding, callback) {
  184. const converted = convertDocuments(collectionName, doc, overwriteParams);
  185. this.push(converted);
  186. callback();
  187. },
  188. });
  189. // stream 4
  190. const batchStream = createBatchStream(BULK_IMPORT_SIZE);
  191. // stream 5
  192. const writeStream = new Writable({
  193. objectMode: true,
  194. async write(batch, encoding, callback) {
  195. const unorderedBulkOp = collection.initializeUnorderedBulkOp();
  196. // documents are not persisted until unorderedBulkOp.execute()
  197. batch.forEach((document) => {
  198. bulkOperate(unorderedBulkOp, collectionName, document, importSettings);
  199. });
  200. // exec
  201. const { insertedCount, modifiedCount, errors } = await execUnorderedBulkOpSafely(unorderedBulkOp);
  202. logger.debug(`Importing ${collectionName}. Inserted: ${insertedCount}. Modified: ${modifiedCount}. Failed: ${errors.length}.`);
  203. const increment = insertedCount + modifiedCount + errors.length;
  204. collectionProgress.currentCount += increment;
  205. collectionProgress.totalCount += increment;
  206. collectionProgress.insertedCount += insertedCount;
  207. collectionProgress.modifiedCount += modifiedCount;
  208. emitProgressEvent(collectionProgress, errors);
  209. callback();
  210. },
  211. final(callback) {
  212. logger.info(`Importing ${collectionName} has completed.`);
  213. callback();
  214. },
  215. });
  216. readStream
  217. .pipe(jsonStream)
  218. .pipe(convertStream)
  219. .pipe(batchStream)
  220. .pipe(writeStream);
  221. await streamToPromise(writeStream);
  222. // clean up tmp directory
  223. fs.unlinkSync(jsonFile);
  224. }
  225. catch (err) {
  226. throw new ImportingCollectionError(collectionProgress, err);
  227. }
  228. }
  229. /**
  230. *
  231. * @param {string} collectionName
  232. * @param {importSettings} importSettings
  233. */
  234. validateImportSettings(collectionName, importSettings) {
  235. const { mode } = importSettings;
  236. switch (collectionName) {
  237. case 'configs':
  238. if (mode !== 'flushAndInsert') {
  239. throw new Error(`The specified mode '${mode}' is not allowed when importing to 'configs' collection.`);
  240. }
  241. break;
  242. }
  243. }
  244. /**
  245. * process bulk operation
  246. * @param {object} bulk MongoDB Bulk instance
  247. * @param {string} collectionName collection name
  248. * @param {object} document
  249. * @param {ImportSettings} importSettings
  250. */
  251. bulkOperate(bulk, collectionName, document, importSettings) {
  252. // insert
  253. if (importSettings.mode !== 'upsert') {
  254. return bulk.insert(document);
  255. }
  256. // upsert
  257. switch (collectionName) {
  258. default:
  259. return bulk.find({ _id: document._id }).upsert().replaceOne(document);
  260. }
  261. }
  262. /**
  263. * emit progress event
  264. * @param {CollectionProgress} collectionProgress
  265. * @param {object} appendedErrors key: collection name, value: array of error object
  266. */
  267. emitProgressEvent(collectionProgress, appendedErrors) {
  268. const { collectionName } = collectionProgress;
  269. // send event (in progress in global)
  270. this.adminEvent.emit('onProgressForImport', { collectionName, collectionProgress, appendedErrors });
  271. }
  272. /**
  273. * emit terminate event
  274. */
  275. emitTerminateEvent() {
  276. this.adminEvent.emit('onTerminateForImport');
  277. }
  278. /**
  279. * extract a zip file
  280. *
  281. * @memberOf ImportService
  282. * @param {string} zipFile absolute path to zip file
  283. * @return {Array.<string>} array of absolute paths to extracted files
  284. */
  285. async unzip(zipFile) {
  286. const readStream = fs.createReadStream(zipFile);
  287. const unzipStream = readStream.pipe(unzipper.Parse());
  288. const files = [];
  289. unzipStream.on('entry', (entry) => {
  290. const fileName = entry.path;
  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(unzipStream);
  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] = this.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 growi that exported the data are not met');
  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. }
  405. module.exports = ImportService;