CommandRunner.coffee 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. spawn = require("child_process").spawn
  2. logger = require "logger-sharelatex"
  3. logger.info "using standard command runner"
  4. module.exports = CommandRunner =
  5. run: (project_id, command, directory, image, timeout, environment, callback = (error) ->) ->
  6. command = (arg.replace('$COMPILE_DIR', directory) for arg in command)
  7. logger.log project_id: project_id, command: command, directory: directory, "running command"
  8. logger.warn "timeouts and sandboxing are not enabled with CommandRunner"
  9. # merge environment settings
  10. env = {}
  11. env[key] = value for key, value of process.env
  12. env[key] = value for key, value of environment
  13. # run command as detached process so it has its own process group (which can be killed if needed)
  14. proc = spawn command[0], command.slice(1), stdio: "inherit", cwd: directory, detached: true, env: env
  15. proc.on "error", (err)->
  16. logger.err err:err, project_id:project_id, command: command, directory: directory, "error running command"
  17. callback(err)
  18. proc.on "close", (code, signal) ->
  19. logger.info code:code, signal:signal, project_id:project_id, "command exited"
  20. if signal is 'SIGTERM' # signal from kill method below
  21. err = new Error("terminated")
  22. err.terminated = true
  23. return callback(err)
  24. else if code is 1 # exit status from chktex
  25. err = new Error("exited")
  26. err.code = code
  27. return callback(err)
  28. else
  29. callback()
  30. return proc.pid # return process id to allow job to be killed if necessary
  31. kill: (pid, callback = (error) ->) ->
  32. try
  33. process.kill -pid # kill all processes in group
  34. catch err
  35. return callback(err)
  36. callback()