export.js 10 KB

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