import.js 14 KB

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