TaskLoggerService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. var_export($output);
  27. return true;
  28. }
  29. return false;
  30. }
  31. /**
  32. * @param string $taskloggerId
  33. * @param string $data
  34. *
  35. * @return string
  36. */
  37. public function createTaskLoggerCmdFile($taskloggerId, $data)
  38. {
  39. $mode = 0777;
  40. $tasklogger_dir = self::TASKLOGGER_PATH . DIRECTORY_SEPARATOR . $taskloggerId;
  41. if (!file_exists($tasklogger_dir)) {
  42. mkdir($tasklogger_dir, $mode, true);
  43. }
  44. $filename = $tasklogger_dir . DIRECTORY_SEPARATOR . 'cmd.sh';
  45. file_put_contents($filename, $data);
  46. chmod($filename, $mode);
  47. return $filename;
  48. }
  49. /**
  50. * @param string $filename
  51. *
  52. * @return array
  53. */
  54. public function runProcess($filename)
  55. {
  56. $process = new Process($filename);
  57. $process->run();
  58. return array(
  59. 'output' => $process->getOutput(),
  60. 'error' => $process->getErrorOutput(),
  61. 'exit_code' => $process->getExitCode(),
  62. );
  63. }
  64. }