SafeExec.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const _ = require('underscore')
  2. const childProcess = require('child_process')
  3. const Settings = require('settings-sharelatex')
  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 = _.once(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({
  38. message: 'failed to kill process after timeout',
  39. info: {
  40. command,
  41. options,
  42. pid: child.pid
  43. }
  44. })
  45. )
  46. }
  47. }, options.timeout)
  48. }
  49. child.on('close', function(code, signal) {
  50. if (code || signal) {
  51. return cleanup(
  52. new FailedCommandError(command, code || signal, stdout, stderr)
  53. )
  54. }
  55. cleanup()
  56. })
  57. child.on('error', err => {
  58. cleanup(err)
  59. })
  60. child.stdout.on('data', chunk => {
  61. stdout += chunk
  62. })
  63. child.stderr.on('data', chunk => {
  64. stderr += chunk
  65. })
  66. }
  67. function safeExecPromise(command, options) {
  68. return new Promise((resolve, reject) => {
  69. safeExec(command, options, (err, stdout, stderr) => {
  70. if (err) {
  71. reject(err)
  72. }
  73. resolve({ stdout, stderr })
  74. })
  75. })
  76. }