SafeExec.js 2.1 KB

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