import.js 14 KB

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