public function testControlledExit() { if (!extension_loaded('pcntl')) { $this->markTestSkipped('PCNTL extension is not loaded.'); } $proc = new Process('exec ' . PHP_BINARY . ' ' . escapeshellarg(__DIR__ . '/console') . ' jms-job-queue:run --worker-name=test --verbose --max-runtime=999999'); $proc->start(); usleep(500000.0); $this->assertTrue($proc->isRunning(), 'Process exited prematurely: ' . $proc->getOutput() . $proc->getErrorOutput()); $this->assertTrueWithin(3, function () use($proc) { return false !== strpos($proc->getOutput(), 'Signal Handlers have been installed'); }, function () use($proc) { $this->fail('Signal handlers were not installed: ' . $proc->getOutput() . $proc->getErrorOutput()); }); $proc->signal(SIGTERM); $this->assertTrueWithin(3, function () use($proc) { return false !== strpos($proc->getOutput(), 'Received SIGTERM'); }, function () use($proc) { $this->fail('Signal was not received by process within 3 seconds: ' . $proc->getOutput() . $proc->getErrorOutput()); }); $this->assertTrueWithin(3, function () use($proc) { return !$proc->isRunning(); }, function () use($proc) { $this->fail('Process did not terminate within 3 seconds: ' . $proc->getOutput() . $proc->getErrorOutput()); }); $this->assertContains('All jobs finished, exiting.', $proc->getOutput()); }
public function testHttpDataDownloadUsingManyWorkers() { $filesystem = new Filesystem(); $targetDirPath = TEMP_DIR . '/' . uniqid('test_http_download'); $filesystem->mkdir($targetDirPath); $workersManager = new Process('php ' . BIN_DIR . '/spider.php worker:start-many -c 3'); $workersManager->start(); $this->assertTrue($workersManager->isRunning(), 'Workers Manager should be working'); $collector = new Process('php ' . BIN_DIR . '/spider.php collector:start --target-folder=' . $targetDirPath); $collector->setIdleTimeout(10); // there should be an output/result at least once every 10 seconds $collector->start(); $this->assertTrue($collector->isRunning(), 'Task Results Collector should be working'); $taskLoader = new Process('php ' . BIN_DIR . '/spider.php tasks:load < ' . FIXTURES_DIR . '/uris.txt'); $taskLoader->setTimeout(120); // 120 seconds is enough to complete the task $taskLoader->start(); $this->assertTrue($taskLoader->isRunning(), 'Task Loader should be working'); while ($taskLoader->isRunning()) { sleep(1); // waiting for process to complete } $taskLoaderOutput = $taskLoader->getOutput() . $taskLoader->getErrorOutput(); $this->assertContains('Total count of Tasks put in the Queue: 10', $taskLoaderOutput, 'Task Loader should have loaded 10 Tasks'); $this->assertContains('Waiting for acknowledgement from Task Result Collector', $taskLoaderOutput, 'Task Loader should have been waiting for Task Result Collector acknowledgement'); $this->assertContains('Informing all workers to stop', $taskLoaderOutput, 'Task Loader should have inform Workers to stop'); $fi = new \FilesystemIterator($targetDirPath, \FilesystemIterator::SKIP_DOTS); $this->assertEquals(10, iterator_count($fi), '10 Task Result Files expected'); }
function getStatus() { if ($this->process->isRunning()) { return TestInterface::STATUS_RUNNING; } elseif ($this->process->getExitCode() > 0) { return TestInterface::STATUS_FAIL; } else { return TestInterface::STATUS_OK; } }
/** * @inheritdoc */ public function heartbeat() { if ($this->stopped) { return false; } if ($this->process->isRunning()) { $this->heartbeatCallback(); return true; } else { $this->stopped = true; return false; } }
/** * @group console */ public function testSleeperCommand() { // init $sleeperCommand = new SleeperCommand(); $sleeperCommandLockFilePath = sprintf('%s/lock_command_%s', $this->getClient()->getKernel()->getCacheDir(), str_replace(':', '_', $sleeperCommand->getName())); $commandline = sprintf('env bin/console --env=%s %s', $this->getClient()->getKernel()->getEnvironment(), $sleeperCommand->getName()); // the first run of this command with the locking mechanism: the lock is created $firstProcess = new Process($commandline); $firstProcess->start(); sleep(SleeperCommand::SLEEPING_TIME / 2); // the second run of this command is invalid $secondProcess = new Process($commandline); $secondProcess->run(); $this->assertSame(2, $secondProcess->getExitCode(), 'Invalid exit code'); $secondProcessOutput = $secondProcess->getOutput(); $this->assertSame(2, substr_count($secondProcessOutput, PHP_EOL), 'There is more than two lines'); $this->assertContains('locking is activated', $secondProcessOutput, 'Incorrect line 1'); $this->assertContains('will not be started', $secondProcessOutput, 'Incorrect line 2'); // check the first process is still running $this->assertTrue($firstProcess->isRunning(), sprintf('The command %s does not work', $firstProcess->getCommandLine())); // after the sleeping, the lock is released sleep(1 + SleeperCommand::SLEEPING_TIME / 2); $this->assertSame(0, $firstProcess->getExitCode()); $firstProcessOutput = $firstProcess->getOutput(); $this->assertSame(3, substr_count($firstProcessOutput, PHP_EOL), 'There is more than three lines'); $this->assertContains('starting', $firstProcessOutput); $this->assertContains('processing', $firstProcessOutput); $this->assertContains('ending', $firstProcessOutput); // the third run of this command, after the sleeping, is valid $thirdProcess = new Process($commandline); $thirdProcess->run(); $this->assertSame(0, $thirdProcess->getExitCode()); }
/** * Run a terminal command * @param [array] $command [description] * @param [path] $directory [description] * @param OutputInterface $output [description] * @return [void] [description] */ private function runProcess($command, $directory, $output, $alias) { $output->writeln(''); if (is_array($command['line'])) { $commandLine = implode(' && ', $command['line']); } else { $commandLine = $command['line']; } $process = new Process($commandLine, $directory); $process->setTimeout(7600); $process->start(); if ($output->isVerbose()) { $process->wait(function ($type, $buffer) { echo $buffer; }); } else { $progress = new ProgressBar($output); $progress->setFormat("<comment>%message%</comment> [%bar%]"); $progress->setMessage($command['title']); $progress->start(); $progress->setRedrawFrequency(10000); while ($process->isRunning()) { $progress->advance(); } $progress->finish(); $progress->clear(); } $output->writeln(''); $output->write('<comment>' . $command['title'] . ' </comment><info>√ done</info>'); }
/** * @override */ protected function execute(InputInterface $input, OutputInterface $output) { $this->output = $output; $this->input = $input; $tmpRouter = tempnam(sys_get_temp_dir(), 'soup-router') . '.php'; file_put_contents($tmpRouter, '<?php $possibleFilePath = "' . BOX_PATH . '/Resources/Assets" . $_SERVER["REQUEST_URI"]; if (file_exists($possibleFilePath) & !is_dir($possibleFilePath)) { $types = array( "css" => "Content-Type: text/css", "js" => "Content-Type: text/javascript" ); $extension = pathinfo($possibleFilePath, PATHINFO_EXTENSION); if (isset($types[$extension])) { header($types[$extension]); } readfile($possibleFilePath); } else { require("' . BOX_PATH . '/src/Bootstrap.php"); } '); $process = new Process('php -S localhost:1716 ' . $tmpRouter); $process->start(); $output->writeln('server running on http://localhost:1716 (ctrl+c to quit)'); while ($process->isRunning()) { // this is just a keep-alive, // if we don't sleep here the cpu process goes crazy without anything // to do, since we have to wait, we can wait forever as well sleep(PHP_INT_MAX); } }
/** * @Route("/", name="write_register", options={"expose"=true}) * @param Request $request * @return JsonResponse */ public function writeAction(Request $request) { if ($request->isXmlHttpRequest()) { $value = $request->get("value"); $register_id = $request->get("register_id"); $registerRepo = $this->getDoctrine()->getRepository('BmsConfigurationBundle:Register'); $register = $registerRepo->find($register_id); $em = $this->getDoctrine()->getManager(); $write = new RegisterWriteData(); $write->setRegister($register)->setGetToProcess(0)->setValue($value)->setSuccessWrite(0)->setTimeOfUpdate(new \DateTime())->setUsername($this->getUser()); $em->persist($write); $em->flush(); $vpn = $this->getParameter('vpn'); $exe = "ssh pi@" . $vpn . " ./bin/addToWrite.sh " . $register_id . " " . $value . " " . $this->getUser(); $process = new Process($exe); $process->start(); while ($process->isRunning()) { // waiting for process to finish } $ret['output'] = $process->getOutput(); return new JsonResponse($ret); } else { throw new AccessDeniedHttpException(); } }
protected function stop() { if ($this->background && $this->process->isRunning()) { $this->process->stop(); $this->printTaskInfo("Stopped {command}", ['command' => $this->getCommand()]); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $this->setGithubToken($output); $packageName = $input->getArgument('package'); $packageNameVersion = PackageNameVersionExtractor::fromString($packageName); $package = new Package($packageNameVersion->name, $packageNameVersion->version); $bowerphp = $this->getBowerphp($output); $url = $bowerphp->getPackageInfo($package); $default = $this->getDefaultBrowser(); $arg = "{$default} \"{$url}\""; if (OutputInterface::VERBOSITY_DEBUG <= $output->getVerbosity()) { $output->writeln($arg); } else { $output->writeln(''); } // @codeCoverageIgnoreStart if (!defined('PHPUNIT_BOWER_TESTSUITE')) { $browser = new Process($arg); $browser->start(); while ($browser->isRunning()) { // do nothing... } } // @codeCoverageIgnoreEnd }
protected function stop() { if ($this->background && $this->process->isRunning()) { $this->process->stop(); $this->printTaskInfo("Stopped <info>" . $this->getCommand() . "</info>"); } }
public function stop() { if ($this->background && $this->process->isRunning()) { $this->process->stop(); $this->printTaskInfo("stopped <info>{$this->command}</info>"); } }
/** * {@inheritdoc} */ public function tick() { if (!$this->process->isRunning() && $this->outputBuffer->isEmpty()) { usleep(1000); if ($this->outputBuffer->isEmpty()) { if ($this->process->isSuccessful()) { $this->deferred->resolve(new MessageEvent($this, $this->process->getOutput())); } else { $this->deferred->reject(new MessageEvent($this, $this->process->getOutput())); } return; } } if (!$this->outputBuffer->isEmpty()) { $this->deferred->notify(new MessageEvent($this, $this->outputBuffer->dequeue()[1])); } }
public function procesaCola() { if ((!$this->excelProcess || !$this->excelProcess->isRunning()) && ($siguentePedido = $this->cola->getFirst())) { try { $this->crearExcel($siguentePedido); $this->cola->limpiarUltimoPedido(); } catch (\Exception $e) { $this->info('|-- Archivo excel bloqueado. Esperando...'); return false; } $this->excelProcess = new Process('excel "' . config("roomsApi.macroInicial") . '"'); $this->excelProcess->start(); $this->info('|- abriendo excel'); return true; } return false; }
public function beforeTest(TestEvent $event) { if (!$this->process->isRunning()) { return; } /** @var \RemoteWebDriver $driver */ $driver = $this->getModule('WebDriver')->webDriver; $this->writeln(["\n", "SauceLabs Connect Info: ", sprintf('SauceOnDemandSessionID=%s job-name=%s', $driver->getSessionID(), $event->getTest()->getName()), ""]); }
/** * {@inheritdoc} */ public function start() { if ($this->phantomJsProc !== null) { return parent::start(); } $cmd = sprintf('exec %s --webdriver=%d', $this->phantomJsBin, $this->wdPort); try { $this->phantomJsProc = new Process($cmd); $this->phantomJsProc->start(); } catch (\Exception $e) { throw new DriverException('Could not start PhantomJs', 0, $e); } if (!$this->phantomJsProc->isRunning()) { throw new DriverException('Could not confirm PhantomJs is running'); } // give PhantomJs a chance to start before creating a session sleep(1); parent::start(); }
/** * {@inheritdoc} */ public function run(JobReportInterface $report) { try { $this->process->start(); $this->savePid($this->process->getPid(), $report); while ($this->process->isRunning()) { // waiting for process to finish } if ($this->process->isSuccessful()) { $report->setOutput(trim($this->process->getOutput())); return JobState::STATE_FINISHED; } $report->setErrorOutput(trim($this->process->getErrorOutput())); } catch (LogicException $e) { $report->setErrorOutput($e->getMessage()); } catch (RuntimeException $e) { $report->setErrorOutput($e->getMessage()); } return JobState::STATE_FAILED; }
/** * {@inheritdoc} */ public function restore(Filesystem $source, Filesystem $destination, ReadonlyDatabase $database, array $parameter) { $tempFile = $this->temporaryFileSystem->createTemporaryFile('mysql'); file_put_contents($tempFile, $source->read('dump.sql')); $process = new Process($this->getImportCommand($parameter['username'], $parameter['password'], $parameter['database'], $tempFile)); $process->run(); while ($process->isRunning()) { // waiting for process to finish } $this->output->writeln(sprintf(' * <comment>%s</comment>', $this->getImportCommand($parameter['username'], $parameter['password'], $parameter['database'], 'dump.sql', true))); }
public function testRunCommandSimple() { $process = new Process($this->getCmd('kitpages:semaphore:aquire', 12)); $process->start(); while ($process->isRunning()) { sleep(1); } $output = $process->getOutput(); $this->assertEquals('12', $output); $process = new Process($this->getCmd('kitpages:semaphore:release')); $process->run(); }
/** * Start Process Background * * @param string $cmd String Cmd * * @return bool */ public function start($cmd) { $this->init(); $process = new Process($cmd . ' >> ' . $this->log . ' 2>&1'); $process->disableOutput(); $process->start(); if ($process->isRunning()) { sleep(1); $this->pid = $this->pid($cmd); } return true; }
/** * {@inheritdoc} */ public function wait(Process $process) { $start = microtime(true); $end = $start + $this->timeout / 1000; while (!$process->isTerminated() && microtime(true) < $end) { usleep(self::TICK * 1000); } if ($process->isRunning()) { $callback = $this->callback; $callback(); } $process->wait(); }
/** * Run child process. * * @param Daemonize $daemon * * @return mixed */ public function runChildProcess(Daemonize $daemon) { $this->output->setEnableAnsi(false); $this->output->setStdOut($this->log); $this->output->setStdErr($this->log); $this->process->start(); if (!$this->process->isRunning()) { throw new RuntimeException('Unable to start server process.'); } $this->processControl->setPid($this->process->getPid()); $this->process->wait(function ($type, $buffer) { $this->output->writeln($buffer); }); }
/** * Checks whether server connection and server process are still available * and running * * @throws \RuntimeException */ protected function checkAvailability() { if (null === $this->connection) { if (null === $this->process) { throw new \RuntimeException('No connection available. Did you start the server?'); } if ($this->process->isRunning()) { $this->stop(); throw new \RuntimeException(sprintf('Server did not respond in time: (%s) [Stopped]', $this->process->getExitCode())); } } if (!$this->process->isRunning()) { throw new \RuntimeException(sprintf('Server process has been terminated: (%s) [%s]', $this->process->getExitCode(), $this->process->getErrorOutput())); } }
/** * Execute the console command. * * @return mixed */ public function handle() { $date = Carbon::now()->format('Y-m-d_h-i'); $user = env('DB_USERNAME'); $password = env('DB_PASSWORD'); $database = env('DB_DATABASE'); $command = "mysqldump --user={$user} -p{$password} {$database} > {$date}.sql"; $process = new Process($command); $process->start(); while ($process->isRunning()) { $s3 = Storage::disk('s3'); $s3->put('gallery-app-db/' . $date . ".sql", file_get_contents("{$date}.sql")); unlink("{$date}.sql"); } }
/** * Fire and forget a command. It will be executed asynchronously, but you can get its output via the $callback. * * @param string $cmd Command to be fired. * @param callable $callback [optional] Callback function that will be called periodically during command's execution * and will take two arguments: 1st is a string buffer output and 2nd is bool error. * You can return (bool) false from the callback to stop the running command. */ public function fire($cmd, $callback = null) { $process = new SymfonyProcess($cmd); $process->start(); // if callback is defined then call it periodically if (is_callable($callback)) { while ($process->isRunning()) { // call the callback $continue = call_user_func_array($callback, array($process->getIncrementalOutput())); // if callback returned false then stop the process if ($continue === false) { $process->stop(3, SIGINT); } } } }
/** * Starts a process in the background - waits for 1 second to check that the process did not die prematurely * (it is supposed to be a long-running task) * @param string $command * * @return int the pid of the created process * @throws \Symfony\Component\Process\Exception\RuntimeException when process could not start / terminated immediately */ public function startProcess($command) { $process = new Process($command); $process->start(); // give the OS some time to abort invalid commands sleep(1); if (!$process->isRunning()) { throw new RuntimeException("Process terminated immediately"); } // while at it, emit a message if ($this->dispatcher) { $event = new ProcessStartedEvent($process->getPid(), $command); $this->dispatcher->dispatch(EventsList::PROCESS_STARTED, $event); } return $process->getPid(); }
public function processCommand() { $this->watch = $this->getRoute()->getMatchedParam('watch', false); $this->fileSystem = new Filesystem(); $this->setUpServer(); $command = sprintf('php -S %s:%d -t %s %s', 'localhost', '8000', $this->getPath() . '/' . $this->getPHPoole()->getOption('output.dir'), sprintf('%s/.phpoole/router.php', $this->getPath())); $this->wlAnnonce(sprintf('Starting server (http://%s:%d)...', 'localhost', '8000')); $process = new Process($command); if (!$process->isStarted()) { // write changes cache if ($this->watch) { $finder = new Finder(); $finder->files()->name('*.md')->name('*.html')->in([$this->getPath() . '/' . $this->getPHPoole()->getOption('content.dir'), $this->getPath() . '/' . $this->getPHPoole()->getOption('layouts.dir')]); if (is_dir($this->getPath() . '/' . $this->getPHPoole()->getOption('themes.dir'))) { $finder->in($this->getPath() . '/' . $this->getPHPoole()->getOption('themes.dir')); } $resourceCache = new ResourceCacheMemory(); $resourceWatcher = new ResourceWatcher($resourceCache); $resourceWatcher->setFinder($finder); $this->fileSystem->dumpFile($this->getPath() . '/.phpoole/watch.flag', ''); } // start server try { $process->start(); Plateform::openBrowser('http://localhost:8000'); while ($process->isRunning()) { // watch changes? if ($this->watch) { $resourceWatcher->findChanges(); if ($resourceWatcher->hasChanges()) { $this->fileSystem->dumpFile($this->getPath() . '/.phpoole/changes.flag', ''); // re-generate $this->wlAlert('Changes detected!'); $callable = new Build(); call_user_func($callable, $this->getRoute(), $this->getConsole()); } } usleep(1000000); // 1 s } } catch (ProcessFailedException $e) { $this->tearDownServer(); echo $e->getMessage(); exit(2); } } }
/** * Execute the console command. * * @return mixed */ public function handle() { $username = env('DB_USERNAME'); $password = env('DB_PASSWORD'); $dbName = env('DB_DATABASE'); $extention = storage_path('app/dbBackups/'); $fileName = $extention . 'ebooktemp-' . Carbon::now()->format('d-m-Y'); $command = "mysqldump -e -f -u {$username} -p{$password} {$dbName} > {$fileName}.sql"; $process = new Process($command); $process->start(); while ($process->isRunning()) { $this->info('backup is running now ..'); } if ($process->isSuccessful()) { $this->info('backup is done'); } else { $this->error('error occured !!' . $process->getErrorOutput()); } }
/** * Tells the child to not pick up any more work and go to bed * * @return void */ public function getReadyForBed() { $busyStatusses = array(ChildProcessContainer::STATUS_SLEEPY, ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY); if (in_array($this->status, $busyStatusses)) { //ready for bed return; } if ($this->status == ChildProcessContainer::STATUS_DEAD) { // do nothing } else { if ($this->status == ChildProcessContainer::STATUS_BUSY) { $this->status = ChildProcessContainer::STATUS_BUSY_BUT_SLEEPY; } else { $this->status = ChildProcessContainer::STATUS_SLEEPY; } } if ($this->process->isRunning()) { $this->sendTERMSignal(); } }
/** * @param Command $command * * @return Command */ public function runCommand(Command $command) { // Build process $process = new Process($command->sanitized, $this->configuration->get('paths.app')); // Run process $output = ''; if (!$this->pretend) { $process->run(function ($type, $buffer) use(&$output) { $output .= $buffer; }); } // Wait for process while ($process->isRunning()) { // ... } // Update command $command->output = trim($output, PHP_EOL) . PHP_EOL; $command->status = $process->getExitCode() === 0 || $this->pretend; $command->done = true; return $command; }