SafeExec.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* eslint-disable
  2. camelcase,
  3. handle-callback-err,
  4. no-return-assign,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS101: Remove unnecessary use of Array.from
  11. * DS102: Remove unnecessary code created because of implicit returns
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. const _ = require('underscore')
  16. const logger = require('logger-sharelatex')
  17. const child_process = require('child_process')
  18. const Settings = require('settings-sharelatex')
  19. // execute a command in the same way as 'exec' but with a timeout that
  20. // kills all child processes
  21. //
  22. // we spawn the command with 'detached:true' to make a new process
  23. // group, then we can kill everything in that process group.
  24. module.exports = function(command, options, callback) {
  25. if (callback == null) {
  26. callback = function(err, stdout, stderr) {}
  27. }
  28. if (!Settings.enableConversions) {
  29. const error = new Error('Image conversions are disabled')
  30. return callback(error)
  31. }
  32. // options are {timeout: number-of-milliseconds, killSignal: signal-name}
  33. const [cmd, ...args] = Array.from(command)
  34. const child = child_process.spawn(cmd, args, { detached: true })
  35. let stdout = ''
  36. let stderr = ''
  37. const cleanup = _.once(function(err) {
  38. if (killTimer != null) {
  39. clearTimeout(killTimer)
  40. }
  41. return callback(err, stdout, stderr)
  42. })
  43. if (options.timeout != null) {
  44. var killTimer = setTimeout(function() {
  45. try {
  46. // use negative process id to kill process group
  47. return process.kill(-child.pid, options.killSignal || 'SIGTERM')
  48. } catch (error) {
  49. return logger.log(
  50. { process: child.pid, kill_error: error },
  51. 'error killing process'
  52. )
  53. }
  54. }, options.timeout)
  55. }
  56. child.on('close', function(code, signal) {
  57. const err = code ? new Error(`exit status ${code}`) : signal
  58. return cleanup(err)
  59. })
  60. child.on('error', err => cleanup(err))
  61. child.stdout.on('data', chunk => (stdout += chunk))
  62. return child.stderr.on('data', chunk => (stderr += chunk))
  63. }