export.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. const logger = require('@alias/logger')('growi:services:ExportService'); // eslint-disable-line no-unused-vars
  2. const fs = require('fs');
  3. const path = require('path');
  4. const mongoose = require('mongoose');
  5. const { Transform } = require('stream');
  6. const streamToPromise = require('stream-to-promise');
  7. const archiver = require('archiver');
  8. const ConfigLoader = require('../service/config-loader');
  9. const toArrayIfNot = require('../../lib/util/toArrayIfNot');
  10. const CollectionProgressingStatus = require('../models/vo/collection-progressing-status');
  11. class ExportProgressingStatus extends CollectionProgressingStatus {
  12. async init() {
  13. // retrieve total document count from each collections
  14. const promises = this.progressList.map(async(collectionProgress) => {
  15. const collection = mongoose.connection.collection(collectionProgress.collectionName);
  16. collectionProgress.totalCount = await collection.count();
  17. });
  18. await Promise.all(promises);
  19. this.recalculateTotalCount();
  20. }
  21. }
  22. class ExportService {
  23. constructor(crowi) {
  24. this.crowi = crowi;
  25. this.appService = crowi.appService;
  26. this.growiBridgeService = crowi.growiBridgeService;
  27. this.getFile = this.growiBridgeService.getFile.bind(this);
  28. this.baseDir = path.join(crowi.tmpDir, 'downloads');
  29. this.per = 100;
  30. this.zlibLevel = 9; // 0(min) - 9(max)
  31. this.adminEvent = crowi.event('admin');
  32. this.currentProgressingStatus = null;
  33. }
  34. /**
  35. * parse all zip files in downloads dir
  36. *
  37. * @memberOf ExportService
  38. * @return {object} info for zip files and whether currentProgressingStatus exists
  39. */
  40. async getStatus() {
  41. const zipFiles = fs.readdirSync(this.baseDir).filter(file => path.extname(file) === '.zip');
  42. // process serially so as not to waste memory
  43. const zipFileStats = [];
  44. const parseZipFilePromises = zipFiles.map((file) => {
  45. const zipFile = this.getFile(file);
  46. return this.growiBridgeService.parseZipFile(zipFile);
  47. });
  48. for await (const stat of parseZipFilePromises) {
  49. zipFileStats.push(stat);
  50. }
  51. // filter null object (broken zip)
  52. const filtered = zipFileStats.filter(element => element != null);
  53. const isExporting = this.currentProgressingStatus != null;
  54. return {
  55. zipFileStats: filtered,
  56. isExporting,
  57. progressList: isExporting ? this.currentProgressingStatus.progressList : null,
  58. };
  59. }
  60. /**
  61. * create meta.json
  62. *
  63. * @memberOf ExportService
  64. * @return {string} path to meta.json
  65. */
  66. async createMetaJson() {
  67. const metaJson = path.join(this.baseDir, this.growiBridgeService.getMetaFileName());
  68. const writeStream = fs.createWriteStream(metaJson, { encoding: this.growiBridgeService.getEncoding() });
  69. const passwordSeed = this.crowi.env.PASSWORD_SEED || null;
  70. const metaData = {
  71. version: this.crowi.version,
  72. url: this.appService.getSiteUrl(),
  73. passwordSeed,
  74. exportedAt: new Date(),
  75. envVars: ConfigLoader.getEnvVarsForDisplay(),
  76. };
  77. writeStream.write(JSON.stringify(metaData));
  78. writeStream.close();
  79. await streamToPromise(writeStream);
  80. return metaJson;
  81. }
  82. /**
  83. *
  84. * @param {ExportProgress} exportProgress
  85. * @return {Transform}
  86. */
  87. generateLogStream(exportProgress) {
  88. const logProgress = this.logProgress.bind(this);
  89. let count = 0;
  90. return new Transform({
  91. transform(chunk, encoding, callback) {
  92. count++;
  93. logProgress(exportProgress, count);
  94. this.push(chunk);
  95. callback();
  96. },
  97. });
  98. }
  99. /**
  100. * insert beginning/ending brackets and comma separator for Json Array
  101. *
  102. * @memberOf ExportService
  103. * @return {TransformStream}
  104. */
  105. generateTransformStream() {
  106. let isFirst = true;
  107. const transformStream = new Transform({
  108. transform(chunk, encoding, callback) {
  109. // write beginning brace
  110. if (isFirst) {
  111. this.push('[');
  112. isFirst = false;
  113. }
  114. // write separator
  115. else {
  116. this.push(',');
  117. }
  118. this.push(chunk);
  119. callback();
  120. },
  121. final(callback) {
  122. // write beginning brace
  123. if (isFirst) {
  124. this.push('[');
  125. }
  126. // write ending brace
  127. this.push(']');
  128. callback();
  129. },
  130. });
  131. return transformStream;
  132. }
  133. /**
  134. * dump a mongodb collection into json
  135. *
  136. * @memberOf ExportService
  137. * @param {string} collectionName collection name
  138. * @return {string} path to zip file
  139. */
  140. async exportCollectionToJson(collectionName) {
  141. const collection = mongoose.connection.collection(collectionName);
  142. const nativeCursor = collection.find();
  143. const readStream = nativeCursor.stream({ transform: JSON.stringify });
  144. // get TransformStream
  145. const transformStream = this.generateTransformStream();
  146. // log configuration
  147. const exportProgress = this.currentProgressingStatus.progressMap[collectionName];
  148. const logStream = this.generateLogStream(exportProgress);
  149. // create WritableStream
  150. const jsonFileToWrite = path.join(this.baseDir, `${collectionName}.json`);
  151. const writeStream = fs.createWriteStream(jsonFileToWrite, { encoding: this.growiBridgeService.getEncoding() });
  152. readStream
  153. .pipe(logStream)
  154. .pipe(transformStream)
  155. .pipe(writeStream);
  156. await streamToPromise(writeStream);
  157. return writeStream.path;
  158. }
  159. /**
  160. * export multiple Collections into json and Zip
  161. *
  162. * @memberOf ExportService
  163. * @param {Array.<string>} collections array of collection name
  164. * @return {Array.<string>} paths to json files created
  165. */
  166. async exportCollectionsToZippedJson(collections) {
  167. const metaJson = await this.createMetaJson();
  168. // process serially so as not to waste memory
  169. const jsonFiles = [];
  170. const jsonFilesPromises = collections.map(collectionName => this.exportCollectionToJson(collectionName));
  171. for await (const jsonFile of jsonFilesPromises) {
  172. jsonFiles.push(jsonFile);
  173. }
  174. // send terminate event
  175. this.emitStartZippingEvent();
  176. // zip json
  177. const configs = jsonFiles.map((jsonFile) => { return { from: jsonFile, as: path.basename(jsonFile) } });
  178. // add meta.json in zip
  179. configs.push({ from: metaJson, as: path.basename(metaJson) });
  180. // exec zip
  181. const zipFile = await this.zipFiles(configs);
  182. // get stats for the zip file
  183. const addedZipFileStat = await this.growiBridgeService.parseZipFile(zipFile);
  184. // send terminate event
  185. this.emitTerminateEvent(addedZipFileStat);
  186. // TODO: remove broken zip file
  187. }
  188. async export(collections) {
  189. if (this.currentProgressingStatus != null) {
  190. throw new Error('There is an exporting process running.');
  191. }
  192. this.currentProgressingStatus = new ExportProgressingStatus(collections);
  193. await this.currentProgressingStatus.init();
  194. try {
  195. await this.exportCollectionsToZippedJson(collections);
  196. }
  197. finally {
  198. this.currentProgressingStatus = null;
  199. }
  200. }
  201. /**
  202. * log export progress
  203. *
  204. * @memberOf ExportService
  205. *
  206. * @param {CollectionProgress} collectionProgress
  207. * @param {number} currentCount number of items exported
  208. */
  209. logProgress(collectionProgress, currentCount) {
  210. const output = `${collectionProgress.collectionName}: ${currentCount}/${collectionProgress.totalCount} written`;
  211. // update exportProgress.currentCount
  212. collectionProgress.currentCount = currentCount;
  213. // output every this.per items
  214. if (currentCount % this.per === 0) {
  215. logger.debug(output);
  216. this.emitProgressEvent();
  217. }
  218. // output last item
  219. else if (currentCount === collectionProgress.totalCount) {
  220. logger.info(output);
  221. this.emitProgressEvent();
  222. }
  223. }
  224. /**
  225. * emit progress event
  226. */
  227. emitProgressEvent() {
  228. const { currentCount, totalCount, progressList } = this.currentProgressingStatus;
  229. const data = {
  230. currentCount,
  231. totalCount,
  232. progressList,
  233. };
  234. // send event (in progress in global)
  235. this.adminEvent.emit('onProgressForExport', data);
  236. }
  237. /**
  238. * emit start zipping event
  239. */
  240. emitStartZippingEvent() {
  241. this.adminEvent.emit('onStartZippingForExport', {});
  242. }
  243. /**
  244. * emit terminate event
  245. * @param {object} zipFileStat added zip file status data
  246. */
  247. emitTerminateEvent(zipFileStat) {
  248. this.adminEvent.emit('onTerminateForExport', { addedZipFileStat: zipFileStat });
  249. }
  250. /**
  251. * zip files into one zip file
  252. *
  253. * @memberOf ExportService
  254. * @param {object|array<object>} configs object or array of object { from: "path to source file", as: "file name after unzipped" }
  255. * @return {string} absolute path to the zip file
  256. * @see https://www.archiverjs.com/#quick-start
  257. */
  258. async zipFiles(_configs) {
  259. const configs = toArrayIfNot(_configs);
  260. const appTitle = this.appService.getAppTitle();
  261. const timeStamp = (new Date()).getTime();
  262. const zipFile = path.join(this.baseDir, `${appTitle}-${timeStamp}.growi.zip`);
  263. const archive = archiver('zip', {
  264. zlib: { level: this.zlibLevel },
  265. });
  266. // good practice to catch warnings (ie stat failures and other non-blocking errors)
  267. archive.on('warning', (err) => {
  268. if (err.code === 'ENOENT') logger.error(err);
  269. else throw err;
  270. });
  271. // good practice to catch this error explicitly
  272. archive.on('error', (err) => { throw err });
  273. for (const { from, as } of configs) {
  274. const input = fs.createReadStream(from);
  275. // append a file from stream
  276. archive.append(input, { name: as });
  277. }
  278. const output = fs.createWriteStream(zipFile);
  279. // pipe archive data to the file
  280. archive.pipe(output);
  281. // finalize the archive (ie we are done appending files but streams have to finish yet)
  282. // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
  283. archive.finalize();
  284. await streamToPromise(archive);
  285. logger.info(`zipped growi data into ${zipFile} (${archive.pointer()} bytes)`);
  286. // delete json files
  287. for (const { from } of configs) {
  288. fs.unlinkSync(from);
  289. }
  290. return zipFile;
  291. }
  292. getReadStreamFromRevision(revision, format) {
  293. const data = revision.body;
  294. const Readable = require('stream').Readable;
  295. const readable = new Readable();
  296. readable._read = () => {};
  297. readable.push(data);
  298. readable.push(null);
  299. return readable;
  300. }
  301. }
  302. module.exports = ExportService;