import.js 14 KB

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