TaskLoggerService.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace WorkflowBundle\Services;
  3. use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
  4. use PhpAmqpLib\Message\AMQPMessage;
  5. use Symfony\Component\Process\Process;
  6. use Symfony\Component\Process\Exception\ProcessFailedException;
  7. class TaskLoggerService implements ConsumerInterface
  8. {
  9. /**
  10. * $msg will be an instance of `PhpAmqpLib\Message\AMQPMessage`
  11. * with the $msg->body being the data sent over RabbitMQ.
  12. *
  13. * @param AMQPMessage $msg
  14. */
  15. public function execute(AMQPMessage $msg)
  16. {
  17. $data = unserialize($msg->getBody());
  18. if (isset($data['id']) && isset($data['cmd'])) {
  19. $taskloggerId = $data['id'];
  20. $cmd = $data['cmd'];
  21. $file_name = $this->createTaskLoggerCmdFile($taskloggerId, $cmd);
  22. $output = $this->runFileProcess($file_name);
  23. return true;
  24. }
  25. return false;
  26. }
  27. /**
  28. * @param string $taskloggerId
  29. *
  30. * @return string
  31. */
  32. public function createTaskLoggerCmdFile($taskloggerId, $cmd)
  33. {
  34. $mode = 0777;
  35. $tasklogger_dir = "/tmp/tasklogger/{$taskloggerId}/";
  36. if (!file_exists($tasklogger_dir)) {
  37. mkdir($tasklogger_dir, $mode, true);
  38. }
  39. $file_name = $tasklogger_dir.'cmd.sh';
  40. file_put_contents($file_name, $cmd);
  41. chmod($file_name, $mode);
  42. return $file_name;
  43. }
  44. /**
  45. * @param string $filename
  46. *
  47. * @return string
  48. */
  49. public function runFileProcess($filename)
  50. {
  51. $process = new Process($filename);
  52. $output = null;
  53. try {
  54. $process->mustRun();
  55. $output = $process->getOutput();
  56. } catch (ProcessFailedException $e) {
  57. $output = $e->getMessage();
  58. }
  59. return $output;
  60. }
  61. }