| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164 |
- <?php
- Lib::loadClass('Request');
- /**
- * @usage: Core_AsyncJobsServer::startAsyncJob(execPath, name, [ 'out.log', 'error.log', 'cwd', 'args' ])
- * @usage: Core_AsyncJobsServer::isInstalled()
- */
- class Core_AsyncJobsServer {
- static function path_nodeJS() { return "/usr/local/bin/node"; }
- // npm_path="/usr/local/bin/npm"
- static function path_pm2() { return "/usr/local/bin/pm2"; }
- static function path_pm2UserWww() { return "/Library/WebServer/.pm2/"; }
- static function startAsyncJob($execPath, $name, $props = [], &$out) {
- if (!$execPath) throw new Exception("Missing job exec path");
- if (!$name) throw new Exception("Missing job name");
- $pathLog = V::get('out.log', '', $props);
- $pathError = V::get('error.log', '', $props);
- // for Ant:
- // index.php?_route=UrlAction_Ant&_task=ant&path=default_db.in7_dziennik_koresp/etykieta&typeName=default_db:IN7_DZIENNIK_KORESP&primaryKey=66263&primaryKeyField=ID
- // index.php?_route=UrlAction_Ant
- // & _task=ant
- // & path=default_db.in7_dziennik_koresp/test-bash
- // & typeName=default_db:IN7_DZIENNIK_KORESP
- // & primaryKey=66263
- // & primaryKeyField=ID
- // index.php?_route=UrlAction_Ant
- // & _task=ant
- // & path=default_db.in7_dziennik_koresp/test-bash
- // & template=test-loop
- // & typeName=default_db:IN7_DZIENNIK_KORESP
- // & primaryKey=66263
- // & primaryKeyField=ID
- // ant=default_db:IN7_DZIENNIK_KORESP/test-bash & task=test-loop & ns=default_db:IN7_DZIENNIK_KORESP & pk=66263
- if (empty($pathLog)) throw new Exception("Missing job log path");
- if (empty($pathError)) throw new Exception("Missing job error path");
- $execArg = V::get('args', '', $props); // execArg for script
- $cmd = implode(" ", [
- "pm2 start '{$execPath}'",
- (!empty($props['cwd'])) ? "--cwd=\"{$props['cwd']}\"" : "",
- "--name '{$name}'",
- "--no-autorestart",
- "--output '{$pathLog}'",
- "--error '{$pathError}'",
- "--time", // prefix time to log entry
- (!empty(trim($execArg))) ? "-- {$execArg}" : "",
- ]);
- // return V::shell_exec($cmd);
- V::exec($cmd . " 2>&1", $out, $ret);
- // echo "cmd: <code>{$cmd}</code><br>RETURN CODE: '{$ret}'<br><pre>OUTPUT:\n" . implode("\n", $out). "</pre>";
- if (0 !== $ret) {
- // [PM2][ERROR] Script already launched, add -f option to force re-execution
- $firstLine = reset($out);
- if (0 === strpos($firstLine, '[PM2][ERROR] Script already launched')) {
- $out = [ "[PM2][ERROR] Script already launched" ];
- }
- // throw new Exception("Nie uruchomiono zadania. " . implode(" ", $out));
- } else {
- // [PM2] Applying action restartProcessId on app [biall-backup-db](ids: [ 0 ])
- // [PM2] [biall-backup-db](0) ✓
- // [PM2] Process successfully started
- $line0 = reset($out);
- $line1 = next($out);
- $line2 = next($out);
- if (0 === strpos($line0, '[PM2] Applying action')
- && 0 === strpos($line1, '[PM2] [')
- && 0 === strpos($line2, '[PM2] Process successfully started')
- ) {
- $out = [ "[PM2] Process successfully started" ];
- return 0;
- }
- // [PM2] Starting /opt/local/pl.procesy5/async_jobs/2020-02-26/3/start.sh in fork_mode (1 instance) [PM2] Done.
- if (0 === strpos($line0, '[PM2] Starting ')
- && 0 === strpos($line1, '[PM2] Done')
- ) {
- $out = [ "[PM2] Process successfully started" ];
- return 0;
- }
- // throw new AlertInfoException("Uruchomiono zadanie. " . implode(" ", $out));
- }
- return $ret;
- }
- static function runPm2Script($props, &$out) { // TODO: mv to AsyncJobs / @return bool $ret from exec
- if (empty($props['jobName'])) throw new Exception("Missing jobName");
- if (empty($props['path'])) throw new Exception("Missing path");
- // cwd (string) “/var/www/” the directory from which your app will be launched
- $jobName = $props['jobName'];
- $outLogPath = "/tmp/p5-async-jobs--{$jobName}--out.log";
- $errLogPath = "/tmp/p5-async-jobs--{$jobName}--err.log";
- $path = $props['path'];
- $args = trim(V::get('args', '', $props));
- $cmd = implode(" ", [
- "pm2 start '{$path}'",
- (!empty($props['cwd'])) ? "--cwd=\"{$props['cwd']}\"" : "",
- "--name '{$jobName}'",
- "--no-autorestart",
- "--output '{$outLogPath}'",
- "--error '{$errLogPath}'",
- "--time", // prefix time to log entry
- (!empty($args)) ? "-- {$args}" : "",
- ]);
- V::exec($cmd . " 2>&1", $out, $ret);
- // echo "cmd: <code>{$cmd}</code><br>RETURN CODE: '{$ret}'<br><pre>OUTPUT:\n" . implode("\n", $out). "</pre>";
- if (0 !== $ret) {
- // [PM2][ERROR] Script already launched, add -f option to force re-execution
- $firstLine = reset($out);
- if (0 === strpos($firstLine, '[PM2][ERROR] Script already launched')) {
- $out = [ "[PM2][ERROR] Script already launched" ];
- }
- // throw new Exception("Nie uruchomiono backupu. " . implode(" ", $out));
- } else {
- // [PM2] Applying action restartProcessId on app [biall-backup-db](ids: [ 0 ])
- // [PM2] [biall-backup-db](0) ✓
- // [PM2] Process successfully started
- $line0 = reset($out);
- $line1 = next($out);
- $line2 = next($out);
- if (0 === strpos($line0, '[PM2] Applying action')
- && 0 === strpos($line1, '[PM2] [')
- && 0 === strpos($line2, '[PM2] Process successfully started')
- ) {
- $out = [ "[PM2] Process successfully started" ];
- }
- // throw new AlertInfoException("Uruchomiono backup. " . implode(" ", $out));
- }
- return $ret;
- }
- static function isInstalled() {
- // V::exec("/usr/local/bin/pm2 --version 2>&1", $out, $ret);
- V::exec("/usr/local/bin/pm2 ping 2>&1", $out, $ret); // expected "{ msg: 'pong' }"
- // echo UI::h('pre', [], "ret({$ret}):\n" . implode("\n", $out));
- if ($ret === 0) {
- // [PM2] Spawning PM2 daemon with pm2_home=/Library/WebServer/.pm2
- // [PM2] PM2 Successfully daemonized
- // { msg: 'pong' }
- }
- if ($ret !== 0) {
- if (!file_exists(self::path_nodeJS())) throw new Exception("pm2 not installed");
- // if [ ! -f "$node_path" ]; then
- // echo "$node_path not exists"
- // wget https://nodejs.org/dist/v12.15.0/node-v12.15.0.pkg
- // sudo installer -verbose -pkg node-v12.15.0.pkg -target /
- // fi
- // # node -v # expected v12.15.0
- if (!file_exists(self::path_pm2())) throw new Exception("pm2 not installed");
- // npm install -g pm2
- // sudo npm install -g pm2
- // pm2 -version # expected 4.2.3
- if (!file_exists(self::path_pm2UserWww())) throw new Exception("pm2 user folder not exists");
- // FIX for Mac OS:
- // $ sudo mkdir /Library/WebServer/.pm2/
- // $ sudo chown _www /Library/WebServer/.pm2/
- throw new Exception("Error pm2"); // unknown error
- }
- }
- }
|