解析运行命令，输出更加好看的格式

php start.php start | stop | restart | reload | status
510821
public static function parseCommand()
    {
        // 检查运行命令的参数
        global $argv;
        $startFile = $argv[0];
        if ( ! isset($argv[1]))
        {
            self::printUsage($startFile);
            exit;
        }

        // 命令
        $command = trim($argv[1]);

        // 子命令，目前只支持-d
        $command2 = isset($argv[2]) ? $argv[2] : '';

        // 记录日志
        $mode = '';
        if ($command === 'start')
        {
            if ($command2 === '-d')
            {
                $mode = 'in DAEMON mode';
            }
            else
            {
                $mode = 'in DEBUG mode';
            }
        }

        Base::getLog()->debug(__METHOD__ . ' parse and execute command', [
            'file'    => $startFile,
            'command' => $command,
            'mode'    => $mode,
        ]);

        // 检查主进程是否在运行
        $masterPid = @file_get_contents(self::$pidFile);
        Base::getLog()->debug(__METHOD__ . ' get master pid from pidFile', [
            'file' => self::$pidFile,
            'pid'  => $masterPid,
        ]);

        $masterIsAlive = $masterPid && @posix_kill($masterPid, 0);
        Base::getLog()->debug(__METHOD__ . ' if master is alive', [
            'alive' => $masterIsAlive,
        ]);

        if ($masterIsAlive)
        {
            if ($command === 'start')
            {
                Base::getLog()->debug(__METHOD__ . ' server is running', [
                    'file' => $startFile,
                ]);
            }
        }
        elseif ($command !== 'start' && $command !== 'restart')
        {
            Base::getLog()->debug(__METHOD__ . ' server is not running', [
                'file' => $startFile,
            ]);
        }

        // 根据命令做相应处理
        switch ($command)
        {
            // 启动 workerman
            case 'start':
                if ($command2 === '-d')
                {
                    Worker::$daemonize = true;
                }
                break;
            // 显示 workerman 运行状态
            case 'status':
                // 尝试删除统计文件，避免脏数据
                if (is_file(self::$statusFile))
                {
                    Base::getLog()->debug(__METHOD__ . ' delete old status file', [
                        'file' => self::$statusFile,
                    ]);
                    @unlink(self::$statusFile);
                }
                // 向主进程发送 SIGUSR2 信号 ，然后主进程会向所有子进程发送 SIGUSR2 信号
                // 所有进程收到 SIGUSR2 信号后会向 $statusFile 写入自己的状态
                posix_kill($masterPid, SIGUSR2);
                // 睡眠100毫秒，等待子进程将自己的状态写入 $statusFile 指定的文件
                usleep(100000);
                // 展示状态
                if ( ! is_file(self::$statusFile))
                {
                    exit("Status file is missing.\n");
                }
                readfile(self::$statusFile);
                exit(0);
            // 重启 workerman
            case 'restart':
                // 停止 workeran

            case 'stop':

                Base::getLog()->debug(__METHOD__ . ' stopping all services', [
                    'file' => $startFile,
                ]);

                // 想主进程发送SIGINT信号，主进程会向所有子进程发送SIGINT信号
                $masterPid && posix_kill($masterPid, SIGINT);
                // 如果 $timeout 秒后主进程没有退出则展示失败界面
                $timeout = 5;
                $startTime = time();
                while (1)
                {
                    // 检查主进程是否存活
                    $masterIsAlive = $masterPid && posix_kill($masterPid, 0);
                    if ($masterIsAlive)
                    {
                        // 检查是否超过$timeout时间
                        if (time() - $startTime >= $timeout)
                        {
                            self::log("Workerman[$startFile] stop fail");
                            exit;
                        }
                        usleep(10000);
                        continue;
                    }
                    self::log("Workerman[$startFile] stop success");
                    // 是restart命令
                    if ($command === 'stop')
                    {
                        exit(0);
                    }
                    // -d 说明是以守护进程的方式启动
                    if ($command2 === '-d')
                    {
                        Worker::$daemonize = true;
                    }
                    break;
                }
                break;
            // 平滑重启 workerman
            case 'reload':
                posix_kill($masterPid, SIGUSR1);
                self::log("Workerman[$startFile] reload");
                exit;
            // 未知命令
            default :
                self::printUsage($startFile);
                exit;
        }
    }
1211472
public function startAction() {
        $posts = $this->getImportBatch(-1);

        if($posts['total'] > 0) {
            try {
                $postIDs = [];
                foreach($posts['posts'] as $post) {
                    $postIDs[] = $post['id'];
                }

                BatchManager::instance()->addToBatchAndRun($this->batchIdentifier(), $postIDs);
            } catch (\Exception $ex) {
                json_response(["status"=>"error", "error" => $ex->getMessage()]);
            }
        } else {
            BatchManager::instance()->reset($this->batchIdentifier());
            json_response(['status' => 'finished']);
        }

        $data = [
            'status' => 'running',
            'total' => $posts['total'],
            'first' => $posts['posts'][0]
        ];

        json_response($data);
    }
872021
public static function run()
    {
        if (! session_id()) {
            session_start();
        }

        $complementType = self::getType('strtoupper');

        $path = App::$complementType();

        if ($paths = File::getFilesFromDir($path)) {
            foreach ($paths as $path) {
                if (! $path->isDot() && $path->isDir()) {
                    $_path = Url::addBackSlash($path->getPath());
                    $slug = $path->getBasename();
                    $file = $_path . $slug . '/' . $slug . '.json';
                    if (! File::exists($file)) {
                        continue;
                    }
                    self::load($file);
                }
            }
        }

        self::requestHandler(self::getType('strtolower', false));
    }
182569
function __init()
    {
        #DEBUG
        if (defined('DEBUG') and strtolower(DEBUG) == 'on')
        {
            //记录运行时间和内存占用情况
            $this->env['runtime']['start'] = microtime(true);
            $this->env['runtime']['mem'] = memory_get_usage();
            //使用whoops美化错误页面
            if (class_exists('\\Whoops\\Run'))
            {
                $whoops = new \Whoops\Run;
                if ($this->env['sapi_name'] == 'cli')
                {
                    $whoops->pushHandler(new \Whoops\Handler\PlainTextHandler());
                }
                else
                {
                    $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
                }
                $whoops->register();
            }
        }
        $this->callHook(self::HOOK_INIT);
    }
158610
public function start() {
		if( $this->isRunning() ) {
			return;
		}

		$script = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'server' . DIRECTORY_SEPARATOR . 'server.php';

		$stdout = tempnam(sys_get_temp_dir(), 'mockserv-stdout-');
		$cmd    = "php -S {$this->host}:{$this->port} " . escapeshellarg($script);

		if( !putenv(self::TMP_ENV . '=' . $this->tmpDir) ) {
			throw new Exceptions\RuntimeException('Unable to put environmental variable');
		}
		$fullCmd = sprintf('%s > %s 2>&1 & echo $!',
			escapeshellcmd($cmd),
			escapeshellarg($stdout)
		);

		InternalServer::incrementRequestCounter($this->tmpDir, 0);

		$this->pid = exec(
			$fullCmd,
			$o,
			$ret
		);

		if( !ctype_digit($this->pid) ) {
			throw new Exceptions\ServerException("Error starting server, received '{$this->pid}', expected int PID");
		}

		sleep(1); // just to make sure it's fully started up, maybe not necessary

		if( !$this->isRunning() ) {
			throw new Exceptions\ServerException("Failed to start server. Is something already running on port {$this->port}?");
		}

		$this->started = true;

		register_shutdown_function(function () {
			if( $this->isRunning() ) {
				$this->stop();
			}
		});
	}
55844
static function CodingSwitch($app = "./",$charset='UTF-8',$mode = "FILES",$file_types = array(".html",".php")) {
		self::info("注意: 程序使用的文件编码检测算法可能对某些特殊字符不适用");
		$filearr = self::searchdir($app,$mode,$file_types);
		foreach($filearr as $file)
			self::DetectAndSwitch($file,$charset);
	}
419863
public function stop()
    {
        $httpServer = $this->getHttpServer();

        // 是否已启动
        if (!$httpServer->isRunning()) {
            \output()->writeln('<error>The server is not running! cannot stop</error>', true, true);
        }

        // pid文件
        $serverStatus = $httpServer->getServerSetting();
        $pidFile = $serverStatus['pfile'];

        \output()->writeln(sprintf('<info>Swoft %s is stopping ...</info>', input()->getScript()));

        $result = $httpServer->stop();

        // 停止失败
        if (!$result) {
            \output()->writeln(sprintf('<error>Swoft %s stop fail</error>', input()->getScript()), true, true);
        }
        //删除pid文件
        @unlink($pidFile);

        output()->writeln(sprintf('<success>Swoft %s stop success!</success>', input()->getScript()));
    }
1000142
public function run()
    {
        // Define a custom error handler so we can log PHP errors
        set_error_handler([\Kotori\Core\Handle::class, 'error']);
        set_exception_handler([\Kotori\Core\Handle::class, 'exception']);
        register_shutdown_function([\Kotori\Core\Handle::class, 'end']);

        Container::get('config')->initialize($this->config);
        Middleware::register('before_app');

        ini_set('date.timezone', Container::get('config')->get('time_zone'));

        // Load application's common functions
        Helper::import(Container::get('config')->get('app_full_path') . '/common.php');

        // @codingStandardsIgnoreStart
        if (function_exists('spl_autoload_register')) {
            spl_autoload_register(['\\Kotori\\Core\\Helper', 'autoload']);
        } else {
            function __autoload($className)
            {
                Helper::autoload($className);
            }
        }
        // @codingStandardsIgnoreEnd

        // Init session
        Container::get('request')->sessionInit();

        Middleware::register('after_app');
        // Load route class
        Container::get('route')->dispatch();
    }
749909
public function reload()
    {
        $httpServer = $this->getHttpServer();

        // 是否已启动
        if (!$httpServer->isRunning()) {
            output()->writeln('<error>The server is not running! cannot reload</error>', true, true);
        }

        output()->writeln(sprintf('<info>Server %s is reloading</info>', input()->getScript()));

        // 重载
        $reloadTask = input()->hasOpt('t');
        $httpServer->reload($reloadTask);
        output()->writeln(sprintf('<success>Server %s reload success</success>', input()->getScript()));
    }
888900
function launch(){

        $this->waitAnswer();
        $template = $this->getHomeCard();
        $server = self::$servers[array_rand(self::$servers)];
        $speech = '欢迎使用平台样例演示，请试着说' . $server;
        $reprompt = '没有听懂，可以直接对我想要使用的服务，例如' . $server;
        $hint = new Hint($server);

        return [
            'outputSpeech' => $speech,
            'reprompt' => $reprompt,
            'directives' => [$hint, $template]
        ];
    }
411968
public function flush()
  {
    // God, PHP really has some esoteric ways of doing simple things.
    $host = $this->host_.($this->port_ != 80 ? ':'.$this->port_ : '');

    $headers = array();
    $defaultHeaders = array('Host' => $host,
                            'Accept' => 'application/x-thrift',
                            'User-Agent' => 'PHP/THttpClient',
                            'Content-Type' => 'application/x-thrift',
                            'Content-Length' => TStringFuncFactory::create()->strlen($this->buf_));
    foreach (array_merge($defaultHeaders, $this->headers_) as $key => $value) {
        $headers[] = "$key: $value";
    }

    $options = array('method' => 'POST',
                     'header' => implode("\r\n", $headers),
                     'max_redirects' => 1,
                     'content' => $this->buf_);
    if ($this->timeout_ > 0) {
      $options['timeout'] = $this->timeout_;
    }
    $this->buf_ = '';

    $contextid = stream_context_create(array('http' => $options));
    $this->handle_ = @fopen($this->scheme_.'://'.$host.$this->uri_, 'r', false, $contextid);

    // Connect failed?
    if ($this->handle_ === FALSE) {
      $this->handle_ = null;
      $error = 'THttpClient: Could not connect to '.$host.$this->uri_;
      throw new TTransportException($error, TTransportException::NOT_OPEN);
    }
  }
807092
public function start()
    {
        $data = Utility::get($this->params, "data", array());
        if ($data && count($data)>0) {
            switch($this->dataFormat)
            {
            case "table":
                $columnNames = $data[0];
                $metaData = array("columns"=>array());
                for ($i=0;$i<count($columnNames);$i++) {
                    $metaData["columns"][$columnNames[$i]] = array(
                        "type"=>(isset($data[1]))
                            ?$this->guessType($data[1][$i]):"unknown",
                    );;
                }
                $this->sendMeta($metaData, $this);
                $this->startInput(null);
                $rowNum = count($data);
                for ($i=1;$i<$rowNum;$i++) {
                    $this->next(array_combine($columnNames, $data[$i]), $this);
                }
                break;
            case "associate":
            default:
                $metaData = array("columns"=>array());
                foreach ($data[0] as $key=>$value) {
                    $metaData["columns"][$key]=array(
                        "type"=>$this->guessType($value),
                    );
                }
                $this->sendMeta($metaData, $this);
                $this->startInput(null);
                foreach ($data as $row) {
                    $this->next($row);
                }
                break;
            }
        }
        $this->endInput(null);
    }
1353361
public function run()
    {
        $stime = microtime(true);
        $this->header('Content-Type: text/html; charset=utf-8');
        ?>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
            <title>Server status.</title>
        </head>
        <body>
        <br/>Uptime: <b><?php echo DateTime::diffAsText(Daemon::$startTime, time());
            ?></b>
        <br/><br/><b>State of workers:</b><?php $stat = Daemon::getStateOfWorkers();
        ?>
        <br/>Idle: <?php echo $stat['idle'];
        ?>
        <br/>Busy: <?php echo $stat['busy'];
        ?>
        <br/>Total alive: <?php echo $stat['alive'];
        ?>
        <br/>Shutdown: <?php echo $stat['shutdown'];
        ?>
        <br/>Pre-init: <?php echo $stat['preinit'];
        ?>
        <br/>Wait-init: <?php echo $stat['waitinit'];
        ?>
        <br/>Init: <?php echo $stat['init'];
        ?>
        <br/>
        <br/>Request took: <?php printf('%f', round(microtime(true) - $stime, 6));
        ?>
        </body>
        </html>
        <?php
    }
819850
public function stop()
    {
        $server = $this->createServerManager();

        // 是否已启动
        if (!$server->isRunning()) {
            \output()->writeln('<error>The server is not running! cannot stop</error>', true, true);
        }

        // pid文件
        $serverOpts = $server->getServerSetting();
        $pidFile = $serverOpts['pfile'];

        \output()->writeln(sprintf('<info>Swoft %s is stopping ...</info>', input()->getScript()));

        $result = $server->stop();

        // 停止失败
        if (!$result) {
            \output()->writeln(sprintf('<error>Swoft %s stop fail</error>', input()->getScript()), true, true);
        }
        //删除pid文件
        @unlink($pidFile);

        \output()->writeln(sprintf('<success>Swoft %s stop success!</success>', input()->getScript()));
    }
924691
public function run()
  {
    if ( \count((array)$this->obj) === 0 ){
      header('HTTP/1.0 404 Not Found');
      exit();
    }

    if ( $this->mode === 'cli' ){
      if ( !headers_sent() && !$this->obj->content ){
        exit('No output...');
      }
      if ( $this->obj->content ){
        echo $this->obj->content;
      }
      @ob_end_flush();
      exit();
    }

    if ( isset($this->obj->prescript) ){
      if ( empty($this->obj->prescript) ){
        unset($this->obj->prescript);
      }
      else if ( !BBN_IS_DEV ){
        try{
          $tmp = \JShrink\Minifier::minify($this->obj->prescript);
        }
        catch ( \RuntimeException $e ){
          \bbn\x::log($this->obj->prescript, 'js_shrink');
        }
        if ( $tmp ){
          $this->obj->prescript = $tmp;
        }
      }
    }
    if ( isset($this->obj->script) ){
      if ( empty($this->obj->script) ){
        unset($this->obj->script);
      }
      else if ( !BBN_IS_DEV ){
        try{
          $tmp = \JShrink\Minifier::minify($this->obj->script);
        }
        catch ( \RuntimeException $e ){
          \bbn\x::log($this->obj->script, 'js_shrink');
        }
        if ( $tmp ){
          $this->obj->script = $tmp;
        }

      }
    }
    if ( isset($this->obj->postscript) ){
      if ( empty($this->obj->postscript) ){
        unset($this->obj->postscript);
      }
      else if ( !BBN_IS_DEV ){
        try{
          $tmp = \JShrink\Minifier::minify($this->obj->postscript);
        }
        catch ( \RuntimeException $e ){
          \bbn\x::log($this->obj->postscript, 'js_shrink');
        }
        if ( $tmp ){
          $this->obj->postscript = $tmp;
        }
      }
    }
    if ( empty($this->obj->content) || ( ($this->mode === 'file') || ($this->mode === 'image') ) ){
      if (!empty($this->obj->file)){
        if (\is_string($this->obj->file) && is_file($this->obj->file)){
          $this->obj->file = new bbn\file($this->obj->file);
        }
        if (\is_object($this->obj->file) &&
          method_exists($this->obj->file, 'download') &&
          method_exists($this->obj->file, 'test') &&
          $this->obj->file->test()
        ){
          $this->mode = 'file';
        }
      }
      else if (!empty($this->obj->img)){
        if (\is_string($this->obj->img) && is_file($this->obj->img)){
          $this->obj->img = new bbn\file\image($this->obj->img);
        }
        if (\is_object($this->obj->img) &&
          method_exists($this->obj->img, 'display') &&
          method_exists($this->obj->img, 'test') &&
          $this->obj->img->test()
        ){
          $this->mode = 'image';
        }
      }
    }
    switch ( $this->mode ){
      case 'public':
      case 'json':
      case 'js':
      case 'css':
      case 'doc':
      case 'html':
        if ( !ob_start("ob_gzhandler" ) ){
          ob_start();
        }
        else{
          header('Content-Encoding: gzip');
        }
        break;
      default:
        ob_start();
    }
    if ( (empty($this->obj->content) && empty($this->obj->file) && empty($this->obj->img) && ($this->mode !==
          'public')) ||
      (($this->mode === 'public') && empty($this->obj)) ){
      $this->mode = '';
    }
    else if ( !empty($this->obj->content) && !empty($this->obj->help) ){
      $Parsedown = new \Parsedown();
      $this->obj->help = $Parsedown->text($this->obj->help);
    }
    switch ( $this->mode ){

      case 'public':
        header('Content-type: application/json; charset=utf-8');
        echo json_encode($this->obj);
        break;

      case 'js':
        header('Content-type: application/javascript; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'css':
        header('Content-type: text/css; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'text':
        header('Content-type: text/plain; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'xml':
        header('Content-type: text/xml; charset=utf-8');
        echo $this->obj->content;
        break;

      case 'image':
        if ( isset($this->obj->img) && \is_object($this->obj->img) ){
          $this->obj->img->display();
        }
        else{
          $this->log("Impossible to display the following image: ".$this->obj->img->name);
          header('HTTP/1.0 404 Not Found');

        }
        break;

      case 'file':
        if ( isset($this->obj->file) && \is_object($this->obj->file) && method_exists($this->obj->file, 'download') ){
          $this->obj->file->download();
        }
        else{
          $this->log("Impossible to display the following controller", $this);
          header('HTTP/1.0 404 Not Found');
          exit();
        }
        break;

      default:
        header('Content-type: text/html; charset=utf-8');
        echo isset($this->obj->content) ? $this->obj->content : '';

    }
  }
1223040
synchronized public static void restart() {
		if (null != crontabSetting) {
			//重新读取配置文件
			crontabSetting.load();
		}
		if (scheduler.isStarted()) {
			//关闭并清除已有任务
			scheduler.stop(true);
		}
		
		//重新加载任务
		schedule(crontabSetting);
		//重新启动
		scheduler.start();
	}
1061005
static function run_php($command, $background_mode = false, $ignore_duplicates = true)
    {
        if (!$ignore_duplicates || empty(self::$running_commands[$command])) {
            $config = Config::read('core');
            $php = empty($config['php']) ? 'php' : $config['php'];
            if (substr(php_uname(), 0, 7) == "Windows") {
                pclose(popen('start' . ($background_mode ? ' /B ' : ' ') . $php . ' ' . $command, "r"));
            } else {
                exec($php . ' ' . $command . ($background_mode ? " > /dev/null &" : ''));
            }
        }
        self::$running_commands[$command] = true;
    }