TaskLoggerService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. * @param string $cmd
  30. *
  31. * @return string
  32. */
  33. public function createTaskLoggerCmdFile($taskloggerId, $cmd)
  34. {
  35. $mode = 0777;
  36. $tasklogger_dir = "/tmp/tasklogger/{$taskloggerId}/";
  37. if (!file_exists($tasklogger_dir)) {
  38. mkdir($tasklogger_dir, $mode, true);
  39. }
  40. $file_name = $tasklogger_dir.'cmd.sh';
  41. file_put_contents($file_name, $cmd);
  42. chmod($file_name, $mode);
  43. return $file_name;
  44. }
  45. /**
  46. * @param string $filename
  47. *
  48. * @return string
  49. */
  50. public function runFileProcess($filename)
  51. {
  52. $process = new Process($filename);
  53. $output = null;
  54. try {
  55. $process->mustRun();
  56. $output = $process->getOutput();
  57. } catch (ProcessFailedException $e) {
  58. $output = $e->getMessage();
  59. }
  60. return $output;
  61. }
  62. }