SafeExec.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const lodashOnce = require('lodash.once')
  2. const childProcess = require('child_process')
  3. const Settings = require('@overleaf/settings')
  4. const { ConversionsDisabledError, FailedCommandError } = require('./Errors')
  5. // execute a command in the same way as 'exec' but with a timeout that
  6. // kills all child processes
  7. //
  8. // we spawn the command with 'detached:true' to make a new process
  9. // group, then we can kill everything in that process group.
  10. module.exports = safeExec
  11. module.exports.promises = safeExecPromise
  12. // options are {timeout: number-of-milliseconds, killSignal: signal-name}
  13. function safeExec(command, options, callback) {
  14. if (!Settings.enableConversions) {
  15. return callback(
  16. new ConversionsDisabledError('image conversions are disabled')
  17. )
  18. }
  19. const [cmd, ...args] = command
  20. const child = childProcess.spawn(cmd, args, { detached: true })
  21. let stdout = ''
  22. let stderr = ''
  23. let killTimer
  24. const cleanup = lodashOnce(function (err) {
  25. if (killTimer) {
  26. clearTimeout(killTimer)
  27. }
  28. callback(err, stdout, stderr)
  29. })
  30. if (options.timeout) {
  31. killTimer = setTimeout(function () {
  32. try {
  33. // use negative process id to kill process group
  34. process.kill(-child.pid, options.killSignal || 'SIGTERM')
  35. } catch (error) {
  36. cleanup(
  37. new FailedCommandError('failed to kill process after timeout', {
  38. command,
  39. options,
  40. pid: child.pid,
  41. })
  42. )
  43. }
  44. }, options.timeout)
  45. }
  46. child.on('close', function (code, signal) {
  47. if (code || signal) {
  48. return cleanup(
  49. new FailedCommandError(command, code || signal, stdout, stderr)
  50. )
  51. }
  52. cleanup()
  53. })
  54. child.on('error', err => {
  55. cleanup(err)
  56. })
  57. child.stdout.on('data', chunk => {
  58. stdout += chunk
  59. })
  60. child.stderr.on('data', chunk => {
  61. stderr += chunk
  62. })
  63. }
  64. function safeExecPromise(command, options) {
  65. return new Promise((resolve, reject) => {
  66. safeExec(command, options, (err, stdout, stderr) => {
  67. if (err) {
  68. reject(err)
  69. }
  70. resolve({ stdout, stderr })
  71. })
  72. })
  73. }