import.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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. const zipFileStats = await Promise.all(zipFiles.map((file) => {
  103. const zipFile = this.getFile(file);
  104. return this.growiBridgeService.parseZipFile(zipFile);
  105. }));
  106. // filter null object (broken zip)
  107. const filtered = zipFileStats
  108. .filter(zipFileStat => zipFileStat != null);
  109. // sort with ctime("Change Time" - Time when file status was last changed (inode data modification).)
  110. filtered.sort((a, b) => { return a.fileStat.ctime - b.fileStat.ctime });
  111. const isImporting = this.currentProgressingStatus != null;
  112. return {
  113. zipFileStat: filtered.pop(),
  114. isImporting,
  115. progressList: isImporting ? this.currentProgressingStatus.progressList : null,
  116. };
  117. }
  118. /**
  119. * import collections from json
  120. *
  121. * @param {string} collections MongoDB collection name
  122. * @param {array} importSettingsMap key: collection name, value: ImportSettings instance
  123. */
  124. async import(collections, importSettingsMap) {
  125. // init status object
  126. this.currentProgressingStatus = new CollectionProgressingStatus(collections);
  127. try {
  128. const promises = collections.map((collectionName) => {
  129. const importSettings = importSettingsMap[collectionName];
  130. return this.importCollection(collectionName, importSettings);
  131. });
  132. await Promise.all(promises);
  133. }
  134. // catch ImportingCollectionError
  135. catch (err) {
  136. const { collectionProgress } = err;
  137. logger.error(`failed to import to ${collectionProgress.collectionName}`, err);
  138. this.emitProgressEvent(collectionProgress, { message: err.message });
  139. }
  140. finally {
  141. this.currentProgressingStatus = null;
  142. this.emitTerminateEvent();
  143. }
  144. }
  145. /**
  146. * import a collection from json
  147. *
  148. * @memberOf ImportService
  149. * @param {string} collectionName MongoDB collection name
  150. * @param {ImportSettings} importSettings
  151. * @return {insertedIds: Array.<string>, failedIds: Array.<string>}
  152. */
  153. async importCollection(collectionName, importSettings) {
  154. // prepare functions invoked from custom streams
  155. const convertDocuments = this.convertDocuments.bind(this);
  156. const bulkOperate = this.bulkOperate.bind(this);
  157. const execUnorderedBulkOpSafely = this.execUnorderedBulkOpSafely.bind(this);
  158. const emitProgressEvent = this.emitProgressEvent.bind(this);
  159. const collection = mongoose.connection.collection(collectionName);
  160. const { mode, jsonFileName, overwriteParams } = importSettings;
  161. const collectionProgress = this.currentProgressingStatus.progressMap[collectionName];
  162. try {
  163. const jsonFile = this.getFile(jsonFileName);
  164. // validate options
  165. this.validateImportSettings(collectionName, importSettings);
  166. // flush
  167. if (mode === 'flushAndInsert') {
  168. await collection.deleteMany({});
  169. }
  170. // stream 1
  171. const readStream = fs.createReadStream(jsonFile, { encoding: this.growiBridgeService.getEncoding() });
  172. // stream 2
  173. const jsonStream = JSONStream.parse('*');
  174. // stream 3
  175. const convertStream = new Transform({
  176. objectMode: true,
  177. transform(doc, encoding, callback) {
  178. const converted = convertDocuments(collectionName, doc, overwriteParams);
  179. this.push(converted);
  180. callback();
  181. },
  182. });
  183. // stream 4
  184. const batchStream = createBatchStream(BULK_IMPORT_SIZE);
  185. // stream 5
  186. const writeStream = new Writable({
  187. objectMode: true,
  188. async write(batch, encoding, callback) {
  189. const unorderedBulkOp = collection.initializeUnorderedBulkOp();
  190. // documents are not persisted until unorderedBulkOp.execute()
  191. batch.forEach((document) => {
  192. bulkOperate(unorderedBulkOp, collectionName, document, importSettings);
  193. });
  194. // exec
  195. const { insertedCount, modifiedCount, errors } = await execUnorderedBulkOpSafely(unorderedBulkOp);
  196. logger.debug(`Importing ${collectionName}. Inserted: ${insertedCount}. Modified: ${modifiedCount}. Failed: ${errors.length}.`);
  197. const increment = insertedCount + modifiedCount + errors.length;
  198. collectionProgress.currentCount += increment;
  199. collectionProgress.totalCount += increment;
  200. collectionProgress.insertedCount += insertedCount;
  201. collectionProgress.modifiedCount += modifiedCount;
  202. emitProgressEvent(collectionProgress, errors);
  203. callback();
  204. },
  205. final(callback) {
  206. logger.info(`Importing ${collectionName} has terminated.`);
  207. callback();
  208. },
  209. });
  210. readStream
  211. .pipe(jsonStream)
  212. .pipe(convertStream)
  213. .pipe(batchStream)
  214. .pipe(writeStream);
  215. await streamToPromise(writeStream);
  216. // clean up tmp directory
  217. fs.unlinkSync(jsonFile);
  218. }
  219. catch (err) {
  220. throw new ImportingCollectionError(collectionProgress, err);
  221. }
  222. }
  223. /**
  224. *
  225. * @param {string} collectionName
  226. * @param {importSettings} importSettings
  227. */
  228. validateImportSettings(collectionName, importSettings) {
  229. const { mode } = importSettings;
  230. switch (collectionName) {
  231. case 'configs':
  232. if (mode !== 'flushAndInsert') {
  233. throw new Error(`The specified mode '${mode}' is not allowed when importing to 'configs' collection.`);
  234. }
  235. break;
  236. }
  237. }
  238. /**
  239. * process bulk operation
  240. * @param {object} bulk MongoDB Bulk instance
  241. * @param {string} collectionName collection name
  242. * @param {object} document
  243. * @param {ImportSettings} importSettings
  244. */
  245. bulkOperate(bulk, collectionName, document, importSettings) {
  246. // insert
  247. if (importSettings.mode !== 'upsert') {
  248. return bulk.insert(document);
  249. }
  250. // upsert
  251. switch (collectionName) {
  252. default:
  253. return bulk.find({ _id: document._id }).upsert().replaceOne(document);
  254. }
  255. }
  256. /**
  257. * emit progress event
  258. * @param {CollectionProgress} collectionProgress
  259. * @param {object} appendedErrors key: collection name, value: array of error object
  260. */
  261. emitProgressEvent(collectionProgress, appendedErrors) {
  262. const { collectionName } = collectionProgress;
  263. // send event (in progress in global)
  264. this.adminEvent.emit('onProgressForImport', { collectionName, collectionProgress, appendedErrors });
  265. }
  266. /**
  267. * emit terminate event
  268. */
  269. emitTerminateEvent() {
  270. this.adminEvent.emit('onTerminateForImport');
  271. }
  272. /**
  273. * extract a zip file
  274. *
  275. * @memberOf ImportService
  276. * @param {string} zipFile absolute path to zip file
  277. * @return {Array.<string>} array of absolute paths to extracted files
  278. */
  279. async unzip(zipFile) {
  280. const readStream = fs.createReadStream(zipFile);
  281. const unzipStream = readStream.pipe(unzipper.Parse());
  282. const files = [];
  283. unzipStream.on('entry', (entry) => {
  284. const fileName = entry.path;
  285. if (fileName === this.growiBridgeService.getMetaFileName()) {
  286. // skip meta.json
  287. entry.autodrain();
  288. }
  289. else {
  290. const jsonFile = path.join(this.baseDir, fileName);
  291. const writeStream = fs.createWriteStream(jsonFile, { encoding: this.growiBridgeService.getEncoding() });
  292. entry.pipe(writeStream);
  293. files.push(jsonFile);
  294. }
  295. });
  296. await streamToPromise(unzipStream);
  297. return files;
  298. }
  299. /**
  300. * execute unorderedBulkOp and ignore errors
  301. *
  302. * @memberOf ImportService
  303. * @param {object} unorderedBulkOp result of Model.collection.initializeUnorderedBulkOp()
  304. * @return {object} e.g. { insertedCount: 10, errors: [...] }
  305. */
  306. async execUnorderedBulkOpSafely(unorderedBulkOp) {
  307. let errors = [];
  308. let result = null;
  309. try {
  310. const log = await unorderedBulkOp.execute();
  311. result = log.result;
  312. }
  313. catch (err) {
  314. result = err.result;
  315. errors = err.writeErrors || [err];
  316. errors.map((err) => {
  317. const moreDetailErr = err.err;
  318. return { _id: moreDetailErr.op._id, message: err.errmsg };
  319. });
  320. }
  321. const insertedCount = result.nInserted + result.nUpserted;
  322. const modifiedCount = result.nModified;
  323. return {
  324. insertedCount,
  325. modifiedCount,
  326. errors,
  327. };
  328. }
  329. /**
  330. * execute unorderedBulkOp and ignore errors
  331. *
  332. * @memberOf ImportService
  333. * @param {string} collectionName
  334. * @param {object} document document being imported
  335. * @param {object} overwriteParams overwrite each document with unrelated value. e.g. { creator: req.user }
  336. * @return {object} document to be persisted
  337. */
  338. convertDocuments(collectionName, document, overwriteParams) {
  339. const Model = this.growiBridgeService.getModelFromCollectionName(collectionName);
  340. const schema = (Model != null) ? Model.schema : null;
  341. const convertMap = this.convertMap[collectionName];
  342. const _document = {};
  343. // not Mongoose Model
  344. if (convertMap == null) {
  345. // apply keepOriginal to all of properties
  346. Object.entries(document).forEach(([propertyName, value]) => {
  347. _document[propertyName] = this.keepOriginal(value, { document, propertyName });
  348. });
  349. }
  350. // Mongoose Model
  351. else {
  352. // assign value from documents being imported
  353. Object.entries(convertMap).forEach(([propertyName, convertedValue]) => {
  354. const value = document[propertyName];
  355. // distinguish between null and undefined
  356. if (value === undefined) {
  357. return; // next entry
  358. }
  359. const convertFunc = (typeof convertedValue === 'function') ? convertedValue : null;
  360. _document[propertyName] = (convertFunc != null) ? convertFunc(value, { document, propertyName, schema }) : convertedValue;
  361. });
  362. }
  363. // overwrite documents with custom values
  364. Object.entries(overwriteParams).forEach(([propertyName, overwriteValue]) => {
  365. const value = document[propertyName];
  366. // distinguish between null and undefined
  367. if (value !== undefined) {
  368. const overwriteFunc = (typeof overwriteValue === 'function') ? overwriteValue : null;
  369. _document[propertyName] = (overwriteFunc != null) ? overwriteFunc(value, { document: _document, propertyName, schema }) : overwriteValue;
  370. }
  371. });
  372. return _document;
  373. }
  374. /**
  375. * validate using meta.json
  376. * to pass validation, all the criteria must be met
  377. * - ${version of this growi} === ${version of growi that exported data}
  378. *
  379. * @memberOf ImportService
  380. * @param {object} meta meta data from meta.json
  381. */
  382. validate(meta) {
  383. if (meta.version !== this.crowi.version) {
  384. throw new Error('the version of this growi and the growi that exported the data are not met');
  385. }
  386. // TODO: check if all migrations are completed
  387. // - export: throw err if there are pending migrations
  388. // - import: throw err if there are pending migrations
  389. }
  390. /**
  391. * Delete all uploaded files
  392. */
  393. deleteAllZipFiles() {
  394. fs.readdirSync(this.baseDir)
  395. .filter(file => path.extname(file) === '.zip')
  396. .forEach(file => fs.unlinkSync(path.join(this.baseDir, file)));
  397. }
  398. }
  399. module.exports = ImportService;