TaskLoggerService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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\DependencyInjection\ContainerInterface;
  7. class TaskLoggerService implements ConsumerInterface
  8. {
  9. /**
  10. * Directorio donde se guardan los script
  11. */
  12. const TASKLOGGER_PATH = '/tmp/tasklogger';
  13. /**
  14. * @var ContainerInterface
  15. */
  16. protected $serviceContainer;
  17. /**
  18. * @param ContainerInterface $serviceContainer
  19. */
  20. public function __construct(ContainerInterface $serviceContainer)
  21. {
  22. $this->serviceContainer = $serviceContainer;
  23. }
  24. /**
  25. * $msg will be an instance of `PhpAmqpLib\Message\AMQPMessage`
  26. * with the $msg->body being the data sent over RabbitMQ.
  27. *
  28. * @param AMQPMessage $msg
  29. */
  30. public function execute(AMQPMessage $msg)
  31. {
  32. $msgBody = unserialize($msg->getBody());
  33. if (isset($msgBody['id']) && isset($msgBody['content'])) {
  34. $taskloggerId = $msgBody['id'];
  35. $content = $msgBody['content'];
  36. $filename = $this->createTaskLoggerCmdFile($taskloggerId, $content);
  37. $output = $this->runProcess($filename);
  38. $output["process"] = $filename;
  39. $monologLoggerId = 'monolog.logger.devicelog';
  40. if ($this->serviceContainer->has($monologLoggerId)) {
  41. $this->serviceContainer->get($monologLoggerId)->info($output['output'], [
  42. 'deviceType' => $msgBody['entityClass'],
  43. 'deviceId' => $msgBody['entityId'],
  44. ]);
  45. }
  46. var_export($output);
  47. return true;
  48. }
  49. return false;
  50. }
  51. /**
  52. * @param string $taskloggerId
  53. * @param string $data
  54. *
  55. * @return string
  56. */
  57. public function createTaskLoggerCmdFile($taskloggerId, $data)
  58. {
  59. $mode = 0777;
  60. $tasklogger_dir = self::TASKLOGGER_PATH . DIRECTORY_SEPARATOR . $taskloggerId;
  61. if (!file_exists($tasklogger_dir)) {
  62. mkdir($tasklogger_dir, $mode, true);
  63. }
  64. $filename = $tasklogger_dir . DIRECTORY_SEPARATOR . 'cmd.sh';
  65. file_put_contents($filename, $data);
  66. chmod($filename, $mode);
  67. return $filename;
  68. }
  69. /**
  70. * @param string $filename
  71. *
  72. * @return array
  73. */
  74. public function runProcess($filename)
  75. {
  76. $predir = getcwd();
  77. chdir(dirname($filename));
  78. $process = new Process($filename);
  79. $process->run();
  80. chdir($predir);
  81. return array(
  82. 'output' => $process->getOutput(),
  83. 'error' => $process->getErrorOutput(),
  84. 'exit_code' => $process->getExitCode(),
  85. );
  86. }
  87. }