TaskLoggerService.php 2.5 KB

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