TaskLoggerService.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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_DIR = '/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. $data = unserialize($msg->getBody());
  21. if (isset($data['id']) && isset($data['cmd'])) {
  22. $taskloggerId = $data['id'];
  23. $cmd = $data['cmd'];
  24. $file_name = $this->createTaskLoggerCmdFile($taskloggerId, $cmd);
  25. $output = $this->runFileProcess($file_name);
  26. return true;
  27. }
  28. return false;
  29. }
  30. /**
  31. * @param string $taskloggerId
  32. * @param string $cmd
  33. *
  34. * @return string
  35. */
  36. public function createTaskLoggerCmdFile($taskloggerId, $cmd)
  37. {
  38. $mode = 0777;
  39. $tasklogger_dir = self::TASKLOGGER_DIR . DIRECTORY_SEPARATOR . $taskloggerId;
  40. if (!file_exists($tasklogger_dir)) {
  41. mkdir($tasklogger_dir, $mode, true);
  42. }
  43. $file_name = $tasklogger_dir . DIRECTORY_SEPARATOR .'cmd.sh';
  44. file_put_contents($file_name, $cmd);
  45. chmod($file_name, $mode);
  46. return $file_name;
  47. }
  48. /**
  49. * @param string $filename
  50. *
  51. * @return string
  52. */
  53. public function runFileProcess($filename)
  54. {
  55. $process = new Process($filename);
  56. $process->run();
  57. return array(
  58. 'output' => $process->getOutput(),
  59. 'error' => $process->getErrorOutput(),
  60. );
  61. }
  62. }