TaskLoggerService.php 2.0 KB

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