Restart the daemon

@return TaskDaemon
436718
public function restart()
    {
        if (count($this->tasks) == 0)
            throw new \Exception("There are no tasks defined - can not restart");

        $this->stop();

        do {
            sleep(1);
        } while ($this->getPid() !== false);

        $this->start();
    }
234522
public function startTaskServer()
    {
        $bind = "udp://{$this->config['server']}";
        $socket = stream_socket_server($bind, $errNo, $errStr, STREAM_SERVER_BIND);

        if (!$socket) {
            $this->log("$errStr ($errNo)", ProcessLogger::ERROR);
            $this->stopWork();

            return -50;
        }

        stream_set_blocking($socket, 1);

        $this->log("start server by stream_socket_server(), bind=$bind");

        while (!$this->stopWork) {
            $this->dispatchSignals();

            $peer = '';
            $pkt = stream_socket_recvfrom($socket, $this->config['bufferSize'], 0, $peer);

            if ($pkt === false) {
                $this->log('udp error', ProcessLogger::ERROR);
                continue;
            }

            $ret = $this->handleCommand($pkt);

            stream_socket_sendto($socket, "{$ret}\n.\n", 0, $peer);
            usleep(10000);
        }

        return 0;
    }
859464
public function start()
    {
        $this->logger->info("crontab start");

        $loop = Factory::create();

        // add periodic timer
        $crontab_timer = $loop->addPeriodicTimer(60, array($this, 'crontabCallback'));

        // recover the sub processes
        $loop->addPeriodicTimer(60, array($this, 'processRecoverCallback'));

        $server = new \Jenner\Crontab\HTTP\Server($loop, $this, $crontab_timer);
        $server->start($this->port);

        $loop->run();
    }
700239
function restart() {
	logger.log('Restarting', clc.green(script));
	notifyWebSocket('restart');
	if (!kill(true)) {
		// The process wasn't running, start it now.
		start(true);
	} /*else {
		// The process will restart when its 'exit' event is emitted.
	}*/
}
897057
protected function run()
    {
        $this->lambdaCache = new CappedStorageHits;
        $this->lambdaCache->setMaxCacheSize(Daemon::$config->lambdacachemaxsize->value);
        $this->lambdaCache->setCapWindow(Daemon::$config->lambdacachecapwindow->value);

        if (Daemon::$process instanceof Master) {
            Daemon::$process->unregisterSignals();
        }

        EventLoop::init();

        Daemon::$process = $this;
        if (Daemon::$logpointerAsync) {
            Daemon::$logpointerAsync->fd = null;
            Daemon::$logpointerAsync = null;
        }
        class_exists('Timer');
        $this->autoReloadLast = time();
        $this->reloadDelay = Daemon::$config->mpmdelay->value + 2;
        $this->setState(Daemon::WSTATE_PREINIT);

        if (Daemon::$config->autogc->value > 0) {
            gc_enable();
            gc_collect_cycles();
        } else {
            gc_disable();
        }

        if (Daemon::$runworkerMode) {
            if (!Daemon::$config->verbosetty->value) {
                fclose(STDIN);
                fclose(STDOUT);
                fclose(STDERR);
            }

            Daemon::$appResolver->preload(true);
        }

        $this->prepareSystemEnv();
        $this->overrideNativeFuncs();

        $this->setState(Daemon::WSTATE_INIT);
        $this->registerEventSignals();

        FileSystem::init();
        FileSystem::initEvent();
        Daemon::openLogs();

        $this->IPCManager = Daemon::$appResolver->getInstanceByAppName('\PHPDaemon\IPCManager\IPCManager');
        if (!$this->IPCManager) {
            $this->log('cannot instantiate IPCManager');
        }

        Daemon::$appResolver->preload();

        foreach (Daemon::$appInstances as $app) {
            foreach ($app as $appInstance) {
                if (!$appInstance->ready) {
                    $appInstance->ready = true;
                    $appInstance->onReady();
                }
            }
        }

        $this->setState(Daemon::WSTATE_IDLE);

        Timer::add(function ($event) {

            if (!Daemon::$runworkerMode) {
                if ($this->IPCManager) {
                    $this->IPCManager->ensureConnection();
                }
            }

            $this->breakMainLoopCheck();
            if (Daemon::checkAutoGC()) {
                EventLoop::$instance->interrupt(function () {
                    gc_collect_cycles();
                });
            }

            $event->timeout();
        }, 1e6 * 1, 'breakMainLoopCheck');
        if (Daemon::$config->autoreload->value > 0) {
            Timer::add(function ($event) {
                static $n = 0;
                $list = get_included_files();
                $s = sizeof($list);
                if ($s > $n) {
                    $slice = array_map('realpath', array_slice($list, $n));
                    Daemon::$process->IPCManager->sendPacket(['op' => 'addIncludedFiles', 'files' => $slice]);
                    $n = $s;
                }
                $event->timeout();
            }, 1e6 * Daemon::$config->autoreload->value, 'watchIncludedFiles');
        }
        EventLoop::$instance->run();
        $this->shutdown();
    }
442052
public function start()
    {
        declare (ticks = 1);
        register_shutdown_function(array($this, "shutdown"));
        pcntl_signal(SIGTERM, array($this, "signalHandler"));
        pcntl_signal(SIGINT, array($this, "signalHandler"));

        $this->output->writeln("<info>Starting <comment>".$this->config->getName()."</comment>.</info>");

        $this->dispatcher->dispatch(WorkerEvents::STARTED, new WorkerStartedEvent($this));

        // A dummy timer to keep a process on a system.
        $this->eventLoop->addPeriodicTimer(10, function () {});

        $this->output->writeln('<info>Successfully booted. Quit working with CONTROL-C.</info>');

        // Start event loop.
        $this->eventLoop->run();
    }
793082
public function start()
    {
        if (!$this->hasStarted()) {
            $this->setStarted();
            $this->dispatch(RunEvent::STARTED, new RunEvent($this));
            try {
                try {
                    $output = call_user_func($this->callback);
                    $this->handleOutput($output);
                    $this->setFinished();
                    $this->successful = true;
                    $this->dispatch(RunEvent::SUCCESSFUL, new RunEvent($this));
                } catch (Exception $e) {
                    $this->setFinished();
                    $this->successful = false;
                    $this->exception = $e;
                    $this->dispatch(RunEvent::FAILED, new RunEvent($this));
                } catch (Throwable $e) {
                    $this->setFinished();
                    $this->successful = false;
                    $this->exception = $e;
                    $this->dispatch(RunEvent::FAILED, new RunEvent($this));
                }
            } finally {
                $this->dispatch(RunEvent::COMPLETED, new RunEvent($this));
            }
        }

        return $this;
    }
72203
public function restart()
    {
        curl_close($this->curl);

        $this->cookies = array();
        $this->curl = $this->createCurlHandle();
    }
159370
protected function run()
    {
        if (stripos(PHP_OS, 'win') === 0) {
           throw new \Exception('The WorkerManagerRunner only works on linux');
        }

        /** @var WorkerProcessManager $workerManager */
        $workerManager = $this->getServiceLocator()->get(WorkerProcessManager::SERVICE_ID);
        $workerManager->setLimitOfCpu($this->getOption('limitOfCpu'));
        $workerManager->setLimitOfMemory($this->getOption('limitOfMemory'));

        /** @var TaskSerializerService $taskSerializer */
        $taskSerializer = $this->getServiceLocator()->get(TaskSerializerService::SERVICE_ID);
        $queueService   = $this->getQueueService();
        $loop           = Factory::create();

        $interval = $this->getOption('interval');
        $loop->addPeriodicTimer($interval, function () use ($loop, $queueService, $taskSerializer, $workerManager) {
            if ($workerManager->canRun()) {
                $task = $queueService->dequeue();
                if ($task !== null) {
                    $cmd = $workerManager->getCommand();
                    $taskJson = base64_encode($taskSerializer->serialize($task));
                    $cmd = 'cd '.ROOT_PATH.' && '.$cmd.' -t '.$taskJson;

                    $process = new \React\ChildProcess\Process($cmd);
                    $process->start($loop);
                    $workerManager->addProcess($process);
                }

                unset($task);
            }
        });

        $loop->run();
    }
1222915
def restart(self, timeout=None, task=None, block_callbacks=False, role=None):
        
        self.set_state('restarting')
        if not block_callbacks:
            self.__cb_pending = ACTION_ON_RESTART
        ret = self.stop(block_callbacks=True) and self.start(timeout, task, True, role)
        if not ret and not self.is_starting():
            self.set_state('restart failed ({0})'.format(self.state))
        return ret
940043
protected function reset()
    {
        $this->status = null;
        $this->results = [];
        $this->currentDriver = null;
        $this->time['started_at'] = 0;
        $this->time['finished_at'] = 0;

        return $this;
    }
460951
protected function daemonize()
	{
		// Is there already an active daemon running?
		if ($this->isActive())
		{
			$this->getLogger()->emergency($this->name . ' daemon is still running. Exiting the application.');

			return false;
		}

		// Reset Process Information
		$this->safeMode = !!@ ini_get('safe_mode');
		$this->processId = 0;
		$this->running = false;

		// Detach process!
		try
		{
			// Check if we should run in the foreground.
			if (!$this->input->get('f'))
			{
				// Detach from the terminal.
				$this->detach();
			}
			else
			{
				// Setup running values.
				$this->exiting = false;
				$this->running = true;

				// Set the process id.
				$this->processId = (int) posix_getpid();
				$this->parentId = $this->processId;
			}
		}
		catch (\RuntimeException $e)
		{
			$this->getLogger()->emergency('Unable to fork.');

			return false;
		}

		// Verify the process id is valid.
		if ($this->processId < 1)
		{
			$this->getLogger()->emergency('The process id is invalid; the fork failed.');

			return false;
		}

		// Clear the umask.
		@ umask(0);

		// Write out the process id file for concurrency management.
		if (!$this->writeProcessIdFile())
		{
			$this->getLogger()->emergency('Unable to write the pid file at: ' . $this->config->get('application_pid_file'));

			return false;
		}

		// Attempt to change the identity of user running the process.
		if (!$this->changeIdentity())
		{
			// If the identity change was required then we need to return false.
			if ($this->config->get('application_require_identity'))
			{
				$this->getLogger()->critical('Unable to change process owner.');

				return false;
			}
			else
			{
				$this->getLogger()->warning('Unable to change process owner.');
			}
		}

		// Setup the signal handlers for the daemon.
		if (!$this->setupSignalHandlers())
		{
			return false;
		}

		// Change the current working directory to the application working directory.
		@ chdir($this->config->get('application_directory'));

		return true;
	}
274551
def restart(ctx, **kwargs):
    
    update_context(ctx, kwargs)

    daemon = mk_daemon(ctx)
    daemon.stop()
    daemon.start()
1265507
public static function start() {
		if (self::is_running()) {
			throw new \Exception('Transaction daemon is already running');
		}
		$pid = pcntl_fork();
		if ($pid == -1) {
			throw new \Exception('Error while forking');
		} elseif ($pid) {
			file_put_contents(Config::$pid_file, $pid);
			return $pid;
		} else {
			// Child
			$daemon = new self();
			$daemon->run();
		}
	}
1072749
public function actionStart()
    {
        if ($this->clearLogs) {
            if (file_exists(static::$logFile)) {
                unlink(static::$logFile);
            }
            if (file_exists(static::$errorLogFile)) {
                unlink(static::$errorLogFile);
            }
        }

        $message = 'Starting Yii 2 Daemon ' . $this->version . '... ';

        if ($this->_getPid() === false) {
            $this->_getWorkers();
            if (!static::$_workersData) {
                $message .= 'No tasks found. Stopping!';
                echo $message . PHP_EOL;
                $this->_log($message);
                return static::EXIT_CODE_ERROR;
            }
            if ($this->_meetRequerements) {
                pcntl_signal(SIGTERM, ['inpassor\daemon\Controller', 'signalHandler']);
                pcntl_signal(SIGINT, ['inpassor\daemon\Controller', 'signalHandler']);
                pcntl_signal(SIGCHLD, ['inpassor\daemon\Controller', 'signalHandler']);
            }
        } else {
            $message .= 'Service is already running!';
            echo $message . PHP_EOL;
            $this->_log($message);
            return static::EXIT_CODE_NORMAL;
        }

        $this->_pid = $this->_meetRequerements ? pcntl_fork() : 0;
        if ($this->_pid == -1) {
            $message .= 'Could not start service!';
            echo $message . PHP_EOL;
            $this->_log($message);
            return static::EXIT_CODE_ERROR;
        } elseif ($this->_pid) {
            file_put_contents($this->_pidFile, $this->_pid);
            return static::EXIT_CODE_NORMAL;
        }
        if ($this->_meetRequerements) {
            posix_setsid();
        }

        $message .= 'OK.';
        echo $message . PHP_EOL;
        $this->_log($message);

        if ($this->_meetRequerements) {
            declare(ticks=1);
        };

        $previousSec = null;

        while (!static::$_stop) {
            $currentSec = date('s');
            $tickPlus = $currentSec === $previousSec ? 0 : 1;
            if ($tickPlus) {
                foreach (static::$_workersData as $workerUid => $workerData) {
                    if ($workerData['tick'] >= $workerData['delay']) {
                        static::$_workersData[$workerUid]['tick'] = 0;
                        $pid = 0;
                        if ($this->_meetRequerements) {
                            if (!isset(static::$workersPids[$workerUid])) {
                                static::$workersPids[$workerUid] = [];
                            }
                            $pid = (count(static::$workersPids[$workerUid]) < $workerData['maxProcesses']) ? pcntl_fork() : -2;
                        }
                        if ($pid == -1) {
                            $this->_log('Could not launch worker "' . $workerUid . '"');
                        } elseif ($pid == -2) {
                            $this->_log('Max processes exceed for launch worker "' . $workerUid . '"');
                        } elseif ($pid) {
                            static::$workersPids[$workerUid][] = $pid;
                        } else {

                            $config = ArrayHelper::merge(static::$_workersConfig[$workerUid] ?? [], [
                                'uid' => $workerUid
                            ]);

                            /** @var \inpassor\daemon\Worker $worker */
                            $worker = \Yii::createObject($config);
                            $worker->run();

                            if ($this->_meetRequerements) {
                                return static::EXIT_CODE_NORMAL;
                            }
                        }
                    }
                    static::$_workersData[$workerUid]['tick'] += $tickPlus;
                }
            }
            usleep(500000);
            $previousSec = $currentSec;
        }
        return static::EXIT_CODE_NORMAL;
    }
662106
public function start()
    {
        if (extension_loaded('pcntl')) {
            pcntl_signal(SIGINT, function ($sig) {
                $this->stop();
            });
        }

        if (false === file_put_contents($this->myPidFile, getmypid())) {
            throw new \RuntimeException('Cannot save the pid in pid file.');
        }
        if (!$this->server->isConnected()) {
            throw new \Exception('Cannot start: not connected');
        }
        $this->server->onFound($this->onConnectPeer());
        register_shutdown_function(function () {
            $this->stop();
        });
//        $this->server->block();
        $this->work();
    }
482959
public function daemon($workCommand, $connectionName, $queue, WorkerOptions $options)
    {
        if ($this->supportsAsyncSignals()) {
            $this->listenForSignals();
        }

        $lastRestart = $this->getTimestampOfLastQueueRestart();

        while (true) {
            // Before reserving any jobs, we will make sure this queue is not paused and
            // if it is we will just pause this worker for a given amount of time and
            // make sure we do not need to kill this worker process off completely.
            if (!$this->daemonShouldRun($options, $connectionName, $queue)) {
                $this->pauseWorker($options, $lastRestart);

                continue;
            }

            // First, we will attempt to get the next job off of the queue. We will also
            // register the timeout handler and reset the alarm for this job so it is
            // not stuck in a frozen state forever. Then, we can fire off this job.
            $job = $this->getNextJob(
                $this->manager->connection($connectionName), $queue
            );

            if ($this->supportsAsyncSignals()) {
                $this->registerTimeoutHandler($job, $options);
            }

            // If the daemon should run (not in maintenance mode, etc.), then we can run
            // fire off this job for processing. Otherwise, we will need to sleep the
            // worker so no more jobs are processed until they should be processed.
            if ($job) {
                $this->runJob($workCommand, $job, $connectionName, $options);
            } else {
                $this->sleep($options->sleep);
            }

            // Finally, we will check to see if we have exceeded our memory limits or if
            // the queue should restart based on other indications. If so, we'll stop
            // this worker and let whatever is "monitoring" it restart the process.
            $this->stopIfNecessary($options, $lastRestart, $job);
        }
    }