LocalCommandRunner.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * decaffeinate suggestions:
  3. * DS101: Remove unnecessary use of Array.from
  4. * DS102: Remove unnecessary code created because of implicit returns
  5. * DS207: Consider shorter variations of null checks
  6. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  7. */
  8. let CommandRunner;
  9. const { spawn } = require("child_process");
  10. const logger = require("logger-sharelatex");
  11. logger.info("using standard command runner");
  12. module.exports = (CommandRunner = {
  13. run(project_id, command, directory, image, timeout, environment, callback) {
  14. let key, value;
  15. if (callback == null) { callback = function(error) {}; }
  16. command = (Array.from(command).map((arg) => arg.toString().replace('$COMPILE_DIR', directory)));
  17. logger.log({project_id, command, directory}, "running command");
  18. logger.warn("timeouts and sandboxing are not enabled with CommandRunner");
  19. // merge environment settings
  20. const env = {};
  21. for (key in process.env) { value = process.env[key]; env[key] = value; }
  22. for (key in environment) { value = environment[key]; env[key] = value; }
  23. // run command as detached process so it has its own process group (which can be killed if needed)
  24. const proc = spawn(command[0], command.slice(1), {cwd: directory, env});
  25. let stdout = "";
  26. proc.stdout.on("data", data=> stdout += data);
  27. proc.on("error", function(err){
  28. logger.err({err, project_id, command, directory}, "error running command");
  29. return callback(err);
  30. });
  31. proc.on("close", function(code, signal) {
  32. let err;
  33. logger.info({code, signal, project_id}, "command exited");
  34. if (signal === 'SIGTERM') { // signal from kill method below
  35. err = new Error("terminated");
  36. err.terminated = true;
  37. return callback(err);
  38. } else if (code === 1) { // exit status from chktex
  39. err = new Error("exited");
  40. err.code = code;
  41. return callback(err);
  42. } else {
  43. return callback(null, {"stdout": stdout});
  44. }
  45. });
  46. return proc.pid;
  47. }, // return process id to allow job to be killed if necessary
  48. kill(pid, callback) {
  49. if (callback == null) { callback = function(error) {}; }
  50. try {
  51. process.kill(-pid); // kill all processes in group
  52. } catch (err) {
  53. return callback(err);
  54. }
  55. return callback();
  56. }
  57. });