export.js 10 KB

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