Create Pid file for process
@param string $appName
@param string $path
438324
public function createPidfile($appName, $path='/var/run'){
		if(!$this->control){
			$this->createControl();
		}
		return new Pidfile($this->control, strtolower($appName), $path);
	}
903311
public function exportActivity(string $appname):Renderer
    {
        $appconfig = null;
        $file = JL::open(FEnv::get("framework.config.core.apps.file"));
        foreach ($file as $one => $val) {
            if ($val->name == $appname) {
                $appconfig = $val;
                break;
            }
        }
        if ($appconfig == null) {
            throw new Server500(new \ArrayObject(array("The application $appname does not exist.",
                "Please check your app configuration")));
        }
        unset($appconfig->enabled);

        try {
            $date = new \DateTime();
            $datefull = $date;
            $date = $date->format('YmdHi');
            $dirbase = FEnv::get("framework.bin").'exports/';
            $dirapp = $dirbase.($appname).'/';
            $dirappexp  = $dirapp.($appname)."_".$date.'/';
            Server::create($dirbase, 'directory');
            Server::create($dirapp, 'directory');
            Server::create($dirappexp, 'directory');
            JL::put($dirappexp."register.json", json_encode($appconfig, JSON_PRETTY_PRINT));
            $zip = new ZipEngine($dirapp.($appname)."_".$date.".zip");
            $zip->setSource(FEnv::get("framework.apps").$appname);
            $zip->addFile($dirappexp."register.json", "register.json");
            $zip->setArchiveComment("$appname - Export date :".$datefull->format('g:ia \o\n l jS F Y'));
            $zip->recursiveCompress();
            if ($zip->close()) {
                Server::delete($dirappexp, 'directory');
                return ((new Renderer())->jsonRenderer(array("code" => 200, "msg" => "OK")));
            } else {
                return ((new Renderer())->jsonRenderer(array("code" => 500,
                    "msg" => "Error on archive creation process")));
            }
        } catch (\Exception $e) {
            return ((new Renderer())->jsonRenderer(array("code" => 500,
                "msg" => "Error on archive creation process : ".$e->getMessage())));
        }
    }
44016
public VDirectory createApplication(String appName) {
        Tenant tenant = new Tenant(TenantService.instance().getDefaultTenantDef());
        return createApplication(tenant, appName);
	}
1186920
public function createFile($attribute, $path, $name)
    {
        $handlerCreateFile = $this->fileOption($attribute, 'createFile');
        $file = $handlerCreateFile($path, $name);
        if ($file) {
            $storage = $this->fileStorage($attribute);
            $contents = file_get_contents($path);
            $handlerTemplatePath = $this->fileOption($attribute, 'templatePath');
            if ($storage->write($handlerTemplatePath($file), $contents)) {
                $this->setState($attribute, $file);
                $this->owner->{$attribute} = $file->id;
                return $file;
            }
        } // @codeCoverageIgnore
        return false; // @codeCoverageIgnore
    }
173133
public static function appSign_once($path, $bucketName)
    {
        $appId = Conf::getAppId();
        $secretId = Conf::getSecretId();
        $secretKey = Conf::getSecretKey();

        if (preg_match('/^\//', $path) == 0) {
            $path = '/'.$path;
        }
        $fileId = '/'.$appId.'/'.$bucketName.$path;

        if (empty($secretId) || empty($secretKey) || empty($appId)) {
            return self::AUTH_SECRET_ID_KEY_ERROR;
        }

        return self::appSignBase($appId, $secretId, $secretKey, 0, $fileId, $bucketName);
    }
1359849
public function commit($appName, $tableName) {
        $json = json_encode($this->docs);
        $this->docs = array();
        return $this->push($json, $appName, $tableName);
    }
748810
public function copy(bool $symlink, string $appname, string $env = null)
    {
        if ($appname == '#none' && $env == null) {
            $dirs = scandir(FEnvFcm::get("framework.root")."/apps/");

            foreach ($dirs as $dir) {
                if ($dir == ".") {
                    continue;
                }
                if ($dir == "..") {
                    continue;
                }
                if (!is_dir(FEnvFcm::get("framework.root")."/apps/".$dir)) {
                    continue;
                }
                if (file_exists(FEnvFcm::get("framework.root")."/apps/".$dir."/Front/Resources/")) {
                    Server::copy(
                        FEnvFcm::get("framework.root") . "/apps/" . $dir . "/Front/Resources/",
                        FEnvFcm::get("framework.root") . "/public/components/apps/dev/" . strtolower($dir),
                        'directory',
                        $symlink
                    );
                    Server::copy(
                        FEnvFcm::get("framework.root") . "/apps/" . $dir . "/Front/Resources/",
                        FEnvFcm::get("framework.root") . "/public/components/apps/prod/" . strtolower($dir),
                        'directory',
                        $symlink
                    );
                }
            }
        } elseif ($appname == '#none' && in_array($env, array("dev", "prod", "all"))) {
            if ($env == "all") {
                $dirs = scandir(FEnvFcm::get("framework.root")."/apps/");

                foreach ($dirs as $dir) {
                    if ($dir == ".") {
                        continue;
                    }
                    if ($dir == "..") {
                        continue;
                    }
                    if (!is_dir(FEnvFcm::get("framework.root")."/apps/".$dir)) {
                        continue;
                    }
                    if (file_exists(FEnvFcm::get("framework.root")."/apps/".$dir."/Front/Resources/")) {
                        Server::copy(
                            FEnvFcm::get("framework.root") . "/apps/" . $dir . "/Front/Resources/",
                            FEnvFcm::get("framework.root") . "/public/components/apps/dev/" .
                            strtolower($dir),
                            'directory',
                            $symlink
                        );
                        Server::copy(
                            FEnvFcm::get("framework.root") . "/apps/" . $dir . "/Front/Resources/",
                            FEnvFcm::get("framework.root") . "/public/components/apps/prod/" .
                            strtolower($dir),
                            'directory',
                            $symlink
                        );
                    }
                }
            } else {
                $dirs = scandir(FEnvFcm::get("framework.root")."/apps/");

                foreach ($dirs as $dir) {
                    if ($dir == ".") {
                        continue;
                    }
                    if ($dir == "..") {
                        continue;
                    }
                    if (!is_dir(FEnvFcm::get("framework.root")."/apps/".$dir)) {
                        continue;
                    }
                    if (file_exists(FEnvFcm::get("framework.root")."/apps/".$dir."/Front/Resources/")) {
                        Server::copy(
                            FEnvFcm::get("framework.root") . "/apps/" . $dir . "/Front/Resources/",
                            FEnvFcm::get("framework.root") . "/public/components/apps/" .
                            strtolower($env) . "/" . strtolower($dir),
                            'directory',
                            $symlink
                        );
                    }
                }
            }
        } elseif ($appname !== '#none' && in_array($env, array("dev", "prod", "all"))) {
            if ($env == "all") {
                if (!is_dir(FEnvFcm::get("framework.root")."/apps/".$appname."/Front/Resources/")) {
                    Output::displayAsRed("The resources folder for $appname doesn't exist.");
                }
                if (file_exists(FEnvFcm::get("framework.root") . "/apps/" . $appname .
                    "/Front/Resources/")) {
                    Server::copy(
                        FEnvFcm::get("framework.root") . "/apps/" . $appname . "/Front/Resources/",
                        FEnvFcm::get("framework.root") . "/public/components/apps/dev/" .
                        strtolower($appname),
                        'directory',
                        $symlink
                    );
                    Server::copy(
                        FEnvFcm::get("framework.root") . "/apps/" . $appname . "/Front/Resources/",
                        FEnvFcm::get("framework.root") . "/public/components/apps/prod/" .
                        strtolower($appname),
                        'directory',
                        $symlink
                    );
                }
            } else {
                if (file_exists(FEnvFcm::get("framework.root") .
                    "/apps/" . $appname . "/Front/Resources/")) {
                    Server::copy(
                        FEnvFcm::get("framework.root") . "/apps/" . $appname . "/Front/Resources/",
                        FEnvFcm::get("framework.root") . "/public/components/apps/" . strtolower($env) .
                        "/" . strtolower($appname),
                        'directory',
                        $symlink
                    );
                }
            }
        } elseif ($appname !== '#none' && $env == null) {
            if (!is_dir(FEnvFcm::get("framework.root")."/apps/".$appname."/Front/Resources/")) {
                Output::displayAsRed("The resources folder for $appname doesn't exist.");
            }
            if (file_exists(FEnvFcm::get("framework.root") . "/apps/" .
                $appname . "/Front/Resources/")) {
                Server::copy(
                    FEnvFcm::get("framework.root") . "/apps/" . $appname . "/Front/Resources/",
                    FEnvFcm::get("framework.root") . "/public/components/apps/dev/" . strtolower($appname),
                    'directory',
                    $symlink
                );
                Server::copy(
                    FEnvFcm::get("framework.root") . "/apps/" . $appname . "/Front/Resources/",
                    FEnvFcm::get("framework.root") . "/public/components/apps/prod/" . strtolower($appname),
                    'directory',
                    $symlink
                );
            }
        } else {
            Output::displayAsRed("App name or env name does not exist. Referer to help command\n");
        }
    }
321466
public function setStdoutFile(string $path, bool $append = false): Process
    {
        $this->setOutputFile(self::STDOUT, $path, $append);
        return $this;
    }
368004
public function injectApp($app, $path = '')
    {
        if (!defined('WEBROOT')) {
            throw new Exception('入口文件必须定义一个WEBROOT的变量到根目录');
        }
        $path = $path ? rtrim($path) . '/' : dirname(WEBROOT) . '/';
        $this->loader->addNamespace('\\' . $app, $path . $app);
        $this->setInitApps($app, $path);
        return $this;
    }
1349363
protected function createProject($projectName = 'myProj') {
        $this->showHeader();
        Console::stdout("Creating $projectName \n");

        Utils::getInstance()->createDirectory("./apps/" . $projectName, ['src', 'routes', 'config', 'public', 'doc', 'templates']);
        echo "\n";
        foreach (self::FILES_APP as $pathname => $contents) {
            Utils::getInstance()->createFile("./apps/" . $projectName . "/" . $pathname, $contents);
        }
        echo "\n Don't forget to run 'composer update' in your root project folder (apps/" . $projectName . ") before start to use! \n";
    }
1150686
public function appAction() {
        $name = ucfirst($this->getFirstParamOrAsk('Enter application\'s name'));;
        FSService::makeWritable(DC::getEnvironment()->getApplicationRoot() . $name);
        $this->createCV(array(
            'name' => 'Index',
            'app'  => $name,
        ));
        $appPath = DC::getEnvironment()->getApplicationRoot() . $name . '/';
        $this->safeCreateFromTemplate($appPath . 'Views/_layout.slot', '_view_layout', array('app'=>$name));
        $this->safeCreateFromTemplate($appPath . 'config.yml', '_app_config', array('app'=>$name));
        $config = DC::getProjectConfig();
        if (!$config->has('applications/'.strtolower($name))) {
            $config->set('applications/'.strtolower($name), strtolower($name));
            $this->notify('added information to project.yml', '+ config');
            $config->save();
        }
    }
966324
function runApp (appDir, appName) {
    var binPath = path.join(appDir, 'Contents', 'MacOS', appName);
    events.emit('log', 'Starting: ' + binPath);
    return spawn(binPath);
}
563157
private function executeInstall($app_name = null)
    {
        if ($app_name == null) {
            $app_name = $this->getAppName();
        }
        $apache = new ApacheProcess();
        $apache->a2enconf($app_name);
        return $apache->reload();
    }
1006383
function (path, callback) {
    var mkdir = child_process.spawn('mkdir', ['-p', path]);
    mkdir.on('error', function (err) {
        callback(err);
        callback = function(){};
    });
    mkdir.on('exit', function (code) {
        if (code === 0) callback();
        else callback(new Error('mkdir exited with code: ' + code));
    });
}
442514
protected function generatePhpIni($appId, $bucketId, $filePath)
    {
        if (file_exists($filePath)) {
            $overwrite = $this->myCommand->confirm(
                'Overwrite the existing "php.ini" file?', false
            );

            if (! $overwrite) {
                return;
            }
        }

        $storageBucket = "{$appId}.appspot.com";
        if ($bucketId !== null) {
            $storageBucket = $bucketId;
        }

        $contents =
<<<EOT
; enable function that are disabled by default in the App Engine PHP runtime
google_app_engine.enable_functions = "php_sapi_name, php_uname, getmypid"
google_app_engine.allow_include_gs_buckets = "{$storageBucket}"
allow_url_include = 1
EOT;
        file_put_contents($filePath, $contents);

        $this->myCommand->info('Generated the "php.ini" file.');
    }
521757
protected function createNewProcess(string $connectionDelegatePath): SymfonyProcess
    {
        $realConnectionDelegatePath = realpath($connectionDelegatePath);

        if ($realConnectionDelegatePath === false) {
            throw new RuntimeException("Cannot find file or directory '$connectionDelegatePath'.");
        }

        // Remove useless options for the process
        $processOptions = array_diff_key($this->options, array_flip(self::USELESS_OPTIONS_FOR_PROCESS));

        return new SymfonyProcess(array_merge(
            [$this->options['executable_path']],
            $this->options['debug'] ? ['--inspect'] : [],
            [$this->getProcessScriptPath()],
            [$realConnectionDelegatePath],
            [json_encode((object) $processOptions)]
        ));
    }
948760
public function attach(array $arguments = null): int {

        if (!$this->has('appname')) {
            throw new Exception("Must set appname in order to run daemon.", 500);
        }

        if (!$this->has('appdir')) {
            throw new Exception("Must set appdir in order to run daemon.", 500);
        }

        $appName = $this->get('appname');

        $appID = strtolower($appName);
        $runFile = $this->get('pidfile') ?? paths('/var/run', "{$appID}.pid");

        $this->lock = new Lock($runFile);

        // Basic configuration

        $appName = $this->get('appname');
        $appDescription = $this->get('appdescription');

        // Set up app

        // Prepare global CLI

        $this->log(LogLevel::INFO, "{app} v{version}", [
            'app'       => APP,
            'version'   => APP_VERSION
        ]);

        $this->cli
            ->description($appDescription)
            ->meta('filename', $appName)

            ->command('start')
                ->description('Start the application.')
                ->opt('watchdog:w', "Don't announce failures to start", false, 'boolean')

            ->command('stop')
                ->description('Stop the application.')

            ->command('restart')
                ->description('Stop the application, then start it again.')

            ->command('status')
                ->description('Check application running status');

        // Allow payload application to influence CLI
        $this->payloadExec('preflight');

        // Parse CLI
        $this->args = $this->cli->parse($arguments, true);
        $this->di->setInstance(Args::class, $this->args);
        $this->set('args', $this->args);

        $command = $this->args->getCommand();
        $sysDaemonize = $this->get('daemonize', true);
        if (!$sysDaemonize) {
            $command = 'start';
        }

        $exitCode = null;
        switch ($command) {

            // Checking running status
            case 'status':
                // Check if pid file is currently running
                $isRunning = $this->lock->isLocked();

                if ($isRunning) {
                    $this->log(LogLevel::NOTICE, 'running');
                    return 0;
                } else {
                    $this->log(LogLevel::NOTICE, 'not running');
                    return 1;
                }
                break;

            // Stop or restart daemon
            case 'stop':
            case 'restart':

                // Check if pid file is currently running
                $runPid = $this->lock->getRunningPID();
                $isRunning = $this->lock->isLocked();

                // Log desired action
                $this->getLogger()->enableLogger('persist');

                if ($command == 'restart') {
                    $this->log(LogLevel::WARNING, 'restarting...');
                } else {
                    $this->log(LogLevel::NOTICE, 'stopping...');
                    if (!$isRunning) {
                        $this->log(LogLevel::WARNING, 'not running!');
                    }
                }

                if ($isRunning) {

                    // Stop it
                    posix_kill($runPid, SIGTERM);
                    sleep(1);

                    // Check if it's still running
                    if ($this->lock->isProcessRunning($runPid)) {

                        // Kill it harder
                        posix_kill($runPid, SIGKILL);
                        sleep(1);

                        // Check if it's still running
                        if ($this->lock->isProcessRunning($runPid)) {
                            $this->log(LogLevel::WARNING, 'unable to stop daemon');
                            return 1;
                        }
                    }
                }

                // Remove PID file
                if (!$isRunning) {
                    $this->lock->unlock();
                }

                if ($command == 'stop') {
                    if (!$isRunning) {
                        return 1;
                    }
                    return 0;
                }

                // 'restart' flows through to 'start'

            // Start daemon
            case 'start':

                // Check for currently running instance
                $runConcurrent = $this->get('concurrent', false);
                if (!$runConcurrent) {

                    // Check locks
                    $runPid = $this->lock->getRunningPID();
                    $isRunning = $this->lock->isLocked();

                    if ($isRunning) {
                        $watchdog = $this->args->getOpt('watchdog');
                        $code = $watchdog ? 0 : 1;

                        $this->log(LogLevel::INFO, 'already running');
                        return $code;
                    }
                }

                // Running user
                $uid = posix_geteuid();
                $user = posix_getpwuid($uid);
                $this->set('user', $user);

                $this->log(LogLevel::DEBUG, "running as {user} (uid {uid})", [
                    'uid'   => $uid,
                    'user'  => $user['name']
                ]);

                // Make sure we can do our things
                $sysUser = $this->get('runasuser', null);
                $sysGroup = $this->get('runasgroup', null);
                if ($sysUser || $sysGroup) {
                    if ($user['uid'] != 0) {
                        $this->log(LogLevel::ERROR, 'must be running as root to setegid() or seteuid()');
                        return 1;
                    }
                }

                // Daemonize
                if ($sysDaemonize) {

                    $realm = $this->fork('daemon', null, true);
                    $this->realm = $realm;

                    // Console returns 0
                    if ($realm == 'console') {
                        $this->log(LogLevel::DEBUG, "[{pid}]   console detached, parent exiting");
                        return 0;
                    }

                } else {

                    $this->log(LogLevel::DEBUG, "[{pid}] Will not go into background");
                    $this->realm = 'daemon';

                }

                /*
                 * Initialize after daemonizing
                 *
                 * Daemon needs to attach signal handlers and set the tick rate.
                 * Also a good place to any other tasks that need to happen as
                 * soon as we know we're actually starting up.
                 */
                $this->initializeDaemon();

                // Daemon returns execution to the main file
                $this->daemonPid = posix_getpid();

                // Invoking user
                $iusername = trim(shell_exec('logname'));
                $iuser = posix_getpwnam($iusername);
                $this->set('iuser', $iuser);

                // Current terminal name
                $terminal = posix_ttyname(STDOUT);
                $terminal = str_replace('/dev/', '', $terminal);
                $this->set('itty', $terminal);

                /*
                 * Initialize payload
                 *
                 * Payload process needs to know that things are running. This
                 * gives it a chance to adjust logging, inspect command line
                 * arguments, etc.
                 */
                $this->payloadExec('initialize');

                $this->attachPayloadErrorHandler();

                $this->log(LogLevel::NOTICE, "Running");

                /*
                 * Run the payload
                 *
                 * Depending on daemon mode, run the payload application as a
                 * single background process, or as a worker fleet.
                 */
                $sysMode = $this->get('mode', self::MODE_SINGLE);
                switch ($sysMode) {
                    case self::MODE_SINGLE:

                        // Run app
                        $this->runModeSingle();

                        break;

                    case self::MODE_FLEET:

                        // Launch and maintain fleet
                        $this->runModeFleet();

                        break;
                }

                // Dismiss payload
                $this->payloadExec('dismiss');

                // Pipe exit code to wrapper file
                $exitCode = $this->exit;

                break;

            default:
                $exitHandled = null;

                // Hand off control to app
                $exitHandled = $this->payloadExec('cli', [$this->args]);

                // Command not handled by app
                if (is_null($exitHandled)) {
                    throw new Exception("Unhandled command", 400);
                }

                $exitCode = (int)$exitHandled;
                break;
        }

        return $exitCode;
    }