TaskLoggerService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. $monologLoggerId = 'monolog.logger.devicelog';
  39. if ($this->serviceContainer->has($monologLoggerId)) {
  40. $this->serviceContainer->get($monologLoggerId)->info($output['output'], [
  41. 'deviceType' => $msgBody['entityClass'],
  42. 'deviceId' => $msgBody['entityId'],
  43. ]);
  44. }
  45. var_export($output);
  46. return true;
  47. }
  48. return false;
  49. }
  50. /**
  51. * @param string $taskloggerId
  52. * @param string $data
  53. *
  54. * @return string
  55. */
  56. public function createTaskLoggerCmdFile($taskloggerId, $data)
  57. {
  58. $mode = 0777;
  59. $tasklogger_dir = self::TASKLOGGER_PATH . DIRECTORY_SEPARATOR . $taskloggerId;
  60. if (!file_exists($tasklogger_dir)) {
  61. mkdir($tasklogger_dir, $mode, true);
  62. }
  63. $filename = $tasklogger_dir . DIRECTORY_SEPARATOR . 'cmd.sh';
  64. file_put_contents($filename, $data);
  65. chmod($filename, $mode);
  66. return $filename;
  67. }
  68. /**
  69. * @param string $filename
  70. *
  71. * @return array
  72. */
  73. public function runProcess($filename)
  74. {
  75. $process = new Process($filename);
  76. $process->run();
  77. return array(
  78. 'output' => $process->getOutput(),
  79. 'error' => $process->getErrorOutput(),
  80. 'exit_code' => $process->getExitCode(),
  81. );
  82. }
  83. }