/**
  * Listen for exit command and terminate
  * the event loop
  *
  * @param string $data
  * @return void
  */
 public function write($data)
 {
     if (trim($data) === self::EXIT_CMD) {
         $this->loop->stop();
         $this->close();
     }
 }
Exemple #2
0
 /**
  * Stops shell
  */
 public function stop()
 {
     if (!$this->running) {
         return;
     }
     $this->loop->stop();
     $this->running = false;
 }
 /**
  * {@inheritdoc}
  */
 public function stop()
 {
     if (null !== $this->loop) {
         $this->loop->stop();
         $this->httpServer->removeAllListeners();
         $this->httpServer = null;
         $this->socketServer->shutdown();
         $this->socketServer = null;
         $this->loop = null;
     }
 }
 /**
  * Create a queue with fanout exchange.
  *
  * @param string $exchange
  * @param string $queue
  *
  * @return PromiseInterface
  */
 public function fanout($exchange, $queue)
 {
     if (!isset($this->queues[$queue])) {
         $this->queues[$queue] = $this->connect()->then(function (Channel $channel) use($exchange, $queue) {
             return \React\Promise\all([$channel, $channel->queueDeclare($queue), $channel->exchangeDeclare($exchange, 'fanout'), $channel->queueBind($queue, $exchange)]);
         }, function (Exception $exception) {
             $this->loop->stop();
             throw new AsyncMessagingException(sprintf('Could not create channel and exchange: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()), 0, $exception);
         });
     }
     return $this->queues[$queue];
 }
Exemple #5
0
 public function terminate()
 {
     $this->loop->stop();
     $this->daemon->terminate();
     // @codeCoverageIgnoreStart
     if (!defined('PHPUNIT_TEST')) {
         define('PHPUNIT_TEST', false);
     }
     // @codeCoverageIgnoreEnd
     if (!PHPUNIT_TEST) {
         die;
     }
 }
 /**
  * @param callable $callback
  *
  * @return void
  */
 protected function consumeMessage(callable $callback)
 {
     $this->channelFactory->fanout($this->exchange, $this->channel)->then(function ($r) use($callback) {
         /** @var Channel $channel */
         $channel = $r[0];
         return $channel->consume(function (Message $message) use($callback) {
             $data = json_decode($message->content, true);
             $callback($this->serializer->deserialize(null, $data));
         }, $this->channel, '', false, true);
     }, function (Exception $exception) {
         $this->loop->stop();
         throw new AsyncMessagingException(sprintf('Could not consume message: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()), 0, $exception);
     });
 }
Exemple #7
0
 public function stop()
 {
     $this->peersInbound->close();
     $this->peersOutbound->close();
     $this->loop->stop();
     $this->db->stop();
 }
Exemple #8
0
 /**
  * Action time for master! Send tasks `to-do` for workers and go to sleep.
  * Also decide when to stop server/loop.
  */
 public function sendTasks()
 {
     if (!$this->wait) {
         if (count($this->tasks) > 0) {
             // Get task name to do.
             $task = current($this->tasks);
             $taskName = $task->getName();
             array_shift($this->tasks);
             $this->informer->startTask($taskName);
             if ($task->isOnce()) {
                 $task->run(new Context(null, null, $this->input, $this->output));
                 $this->informer->endTask();
             } else {
                 $this->tasksToDo = [];
                 foreach ($this->servers as $serverName => $server) {
                     if ($task->runOnServer($serverName)) {
                         $env = isset($this->environments[$serverName]) ? $this->environments[$serverName] : ($this->environments[$serverName] = new Environment());
                         if (count($task->getOnlyForStage()) > 0 && (!$env->has('stages') || !$task->runForStages($env->get('stages')))) {
                             continue;
                         }
                         $this->informer->onServer($serverName);
                         $this->tasksToDo[$serverName] = $taskName;
                     }
                 }
                 // Inform all workers what tasks they need to do.
                 $taskToDoStorage = new ArrayStorage();
                 $taskToDoStorage->push($this->tasksToDo);
                 $this->pure->setStorage('tasks_to_do', $taskToDoStorage);
                 $this->wait = true;
             }
         } else {
             $this->loop->stop();
         }
     }
 }
Exemple #9
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     $app = new Container();
     $app->instance('config', new Repository());
     (new EventServiceProvider($app))->register();
     (new AmiServiceProvider($app))->register();
     $this->loop = $app[LoopInterface::class];
     $this->loop->nextTick(function () {
         if (!$this->running) {
             $this->loop->stop();
         }
     });
     $this->stream = $app[Stream::class];
     $this->events = $app['events'];
     $this->app = $app;
 }
Exemple #10
0
 /**
  * Action time for master! Send tasks `to-do` for workers and go to sleep.
  * Also decide when to stop server/loop.
  */
 public function sendTasks()
 {
     if (!$this->wait) {
         if (count($this->tasks) > 0) {
             // Get task name to do.
             $task = current($this->tasks);
             $taskName = $task->getName();
             array_shift($this->tasks);
             $this->informer->startTask($taskName);
             if ($task->isOnce()) {
                 $task->run(new Context($this->localhost, $this->localEnv, $this->input, $this->output));
                 $this->informer->endTask();
             } else {
                 $this->tasksToDo = [];
                 foreach ($this->servers as $serverName => $server) {
                     if ($task->isOnServer($serverName)) {
                         if (!isset($this->environments[$serverName])) {
                             $this->environments[$serverName] = new Environment();
                         }
                         // Start task on $serverName.
                         $this->tasksToDo[$serverName] = $taskName;
                     }
                 }
                 // Inform all workers what tasks they need to do.
                 $taskToDoStorage = new ArrayStorage();
                 $taskToDoStorage->push($this->tasksToDo);
                 $this->pure->setStorage('tasks_to_do', $taskToDoStorage);
                 $this->wait = true;
             }
         } else {
             $this->loop->stop();
         }
     }
 }
Exemple #11
0
 /**
  * Disconnect and stop the event loop
  */
 public function stop()
 {
     $this->wsClient->close();
     $this->ariClient->onClose(function () {
         $this->eventLoop->stop();
     });
 }
Exemple #12
0
 public function consume($topic, $channel, $payload)
 {
     if (!count($this->messages)) {
         return;
     }
     try {
         if (!$this->exception) {
             $this->checkMessage($topic, $channel, $payload);
         }
     } catch (\PHPUnit_Framework_AssertionFailedError $e) {
         $this->exception = $e;
     }
     if (count($this->messages) == 0) {
         $this->loop->stop();
     }
 }
 /**
  * @param QueueMessage $message
  *
  * @return void
  */
 protected function publishMessage(QueueMessage $message)
 {
     $this->channelFactory->fanout($this->exchange, $this->channel)->then(function ($r) use($message) {
         /** @var Channel $channel */
         $channel = $r[0];
         return \React\Promise\all([$channel->publish(json_encode($this->serializer->serialize($message)), [], $this->exchange)]);
     }, function (Exception $exception) {
         $this->loop->stop();
         throw new AsyncMessagingException(sprintf('Could not publish message: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()), 0, $exception);
     })->then(function () {
         $this->loop->stop();
     }, function (Exception $exception) {
         $this->loop->stop();
         var_dump(sprintf('Could not publish message: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()));
     });
     $this->loop->run();
 }
Exemple #14
0
 /**
  * Calls {@link eventLoop}'s stop() method.
  */
 public function stop()
 {
     if ($this->stopTimer) {
         $this->stopTimer->cancel();
         $this->stopTimer = null;
     }
     $this->eventLoop->stop();
 }
Exemple #15
0
 /**
  * Checks if the SIGTERM is presente in the server.
  */
 protected function checkSigterm()
 {
     if ($this->sigterm) {
         $this->loop->stop();
         $this->socket->shutdown();
         $this->output->writeln('The Foreman Processor has been stopped.');
     }
 }
 public function testStopShouldPreventRunFromBlocking($timeLimit = 0.005)
 {
     $this->loop->addTimer(1, function () {
         $this->fail('Timer was executed.');
     });
     $this->loop->nextTick(function () {
         $this->loop->stop();
     });
     $this->assertRunFasterThan($timeLimit);
 }
 /**
  * @param LoopInterface $loop
  * @param Messenger $messenger
  * @return Process
  */
 public static function create(LoopInterface $loop, Messenger $messenger)
 {
     try {
         return new Process($loop, $messenger);
     } catch (\Exception $exeption) {
         $messenger->error(MessagesFactory::error(['message' => $exeption->getMessage(), 'code' => $exeption->getCode(), 'line' => $exeption->getLine(), 'file' => $exeption->getFile()]));
         $loop->addTimer(1, function () use($loop) {
             $loop->stop();
         });
     }
 }
/**
 * block waiting for the given $promise to resolve
 *
 * @param PromiseInterface $promise
 * @param LoopInterface    $loop
 * @return mixed returns whatever the promise resolves to
 * @throws Exception when the promise is rejected
 */
function await(PromiseInterface $promise, LoopInterface $loop)
{
    $wait = true;
    $resolved = null;
    $exception = null;
    $promise->then(function ($c) use(&$resolved, &$wait, $loop) {
        $resolved = $c;
        $wait = false;
        $loop->stop();
    }, function ($error) use(&$exception, &$wait, $loop) {
        $exception = $error;
        $wait = false;
        $loop->stop();
    });
    while ($wait) {
        $loop->run();
    }
    if ($exception !== null) {
        throw $exception;
    }
    return $resolved;
}
 /**
  * Waits until the controller's promise resolves.
  *
  * @param GetResponseForControllerResultEvent $event
  *
  * @return mixed
  *
  * @throws \Exception
  */
 private function awaitControllerResult(GetResponseForControllerResultEvent $event)
 {
     $wait = true;
     $resolved = null;
     $exception = null;
     Promise\resolve($event->getControllerResult())->then(function ($result) use(&$resolved, &$wait) {
         $resolved = $result;
         $wait = false;
     }, function ($result) use(&$exception, &$wait) {
         $exception = $result;
         $wait = false;
     })->always(function () {
         $this->loop->stop();
     });
     while ($wait) {
         $this->loop->run();
     }
     if ($exception instanceof \Throwable || $exception instanceof \Exception) {
         throw $exception;
     }
     return $resolved;
 }
Exemple #20
0
 public function __construct(LoopInterface $loop, EventEmitterInterface $emitter, $token)
 {
     $self = $this;
     $this->emitter = $emitter;
     $connector = new ClientFactory($loop);
     $endpoint = $this->getEndpoint($token);
     $consumer = new Consumer($emitter);
     $connector($endpoint)->then(function (WebSocket $conn) use($self, $emitter) {
         $emitter->emit('log', ['Connected!']);
         $conn->on('message', function ($msg) use($self, $emitter) {
             $emitter->emit('log', ['Received a message: ' . $msg, OutputInterface::VERBOSITY_DEBUG]);
             $msgData = json_decode($msg);
             if (property_exists($msgData, 'user') && $msgData->user === $self->selfId) {
                 return;
             }
             if (property_exists($msgData, 'channel') && substr($msgData->channel, 0, 1) === 'D' && property_exists($msgData, 'text')) {
                 if (strpos($msgData->text, 'start') !== false) {
                     $self->log('Received a start request: ' . json_encode($msg));
                     $emitter->emit('session.start', [$msgData]);
                 } elseif (strpos($msgData->text, 'stop') !== false) {
                     $self->log('Received a stop request: ' . json_encode($msg));
                     $emitter->emit('session.stop', [$msgData]);
                 } elseif (strpos($msgData->text, 'est') !== false) {
                     $self->log('Received an estimate request: ' . json_encode($msg));
                     $emitter->emit('session.estimate', [$msgData]);
                 } elseif (strpos($msgData->text, 'rate') !== false) {
                     $emitter->emit('session.rate', [$msgData]);
                 } elseif (strpos($msgData->text, 'status') !== false) {
                     $self->log('Received an estimate request: ' . json_encode($msg));
                     $emitter->emit('session.status', [$msgData]);
                 } elseif (strpos($msgData->text, 'hello') !== false) {
                     $emitter->emit('hello', [$msgData]);
                 } else {
                     $emitter->emit('unknown', [$msgData]);
                 }
             }
         });
         // $emitter->on('send', function($msg) use ($conn, $self) {
         //     $self->increase();
         //     $msg['id'] = $self->msgCounter;
         //     $self->log('Sending message: '.json_encode($msg));
         //     $conn->send(json_encode($msg));
         //     $self->increase();
         // });
     }, function ($e) use($loop, $emitter) {
         $emitter->emit('error.fatal', "Could not connect: {$e->getMessage()}\n");
         $loop->stop();
     });
 }
 public function initialize(Messenger $server, Messenger $client, LoopInterface $loop)
 {
     foreach ($this->messages as $message) {
         $client->on($message->event, function ($arg) use($message, $loop) {
             $this->assertEquals($arg, $message->arguments);
             $message->called = true;
             $this->totalCalled++;
             if ($this->totalCalled === count($this->messages)) {
                 $loop->stop();
             }
         });
         $loop->addTimer(0.001, function () use($server, $message) {
             $server->send($message->event, $message->arguments);
         });
     }
     $loop->addTimer(3, function () use($loop) {
         $loop->stop();
         throw new \RuntimeException('Timeout reached, server has not accomplished all messages.');
     });
     $loop->run();
     foreach ($this->messages as $message) {
         $this->assertTrue($message->called);
     }
 }
 /**
  * @param Server        $server
  * @param LoopInterface $loop
  */
 protected function closure(Server $server, LoopInterface $loop)
 {
     $this->logger->notice('Stopping server ...');
     foreach ($this->serverPushHandlerRegistry->getPushers() as $handler) {
         $handler->close();
         $this->logger->info(sprintf('Stop %s push handler', $handler->getName()));
     }
     $server->emit('end');
     $server->shutdown();
     foreach ($this->periodicRegistry->getPeriodics() as $periodic) {
         if ($periodic instanceof TimerInterface && $loop->isTimerActive($periodic)) {
             $loop->cancelTimer($periodic);
         }
     }
     $loop->stop();
     $this->logger->notice('Server stopped !');
 }
 /**
  * Instruct a running event loop to stop.
  */
 public function stop()
 {
     $this->emit('stopStart');
     $this->loop->stop();
     $this->emit('stopDone');
 }
 private function limitedLoop($timeout = 5)
 {
     $this->loop->addTimer($timeout, function () {
         $this->loop->stop();
     });
 }
Exemple #25
0
 /**
  * @return void
  */
 public function disconnect()
 {
     $this->logger->info('Stopping');
     $this->loop->stop();
 }
Exemple #26
0
 /**
  * Stop loop
  */
 private function stopLoop()
 {
     $this->client->disconnect();
     $this->loop->stop();
 }
Exemple #27
0
 /**
  * Disconnect and stop the event loop
  */
 public function stop()
 {
     $this->wsClient->close();
     $this->eventLoop->stop();
 }
Exemple #28
0
 /**
  * @param NodeInterface $node
  * @param array $params
  * @return array
  */
 public function execute(NodeInterface $node, array $params)
 {
     $this->loop->stop();
     $node->stop();
     return ['message' => 'Shutting down'];
 }
Exemple #29
0
 /**
  * Stop subscribe event loop
  */
 public function stop()
 {
     $this->loop->stop();
 }
Exemple #30
0
 public function shutdown()
 {
     $this->loop->stop();
 }