log( "allocate_ports: $nodeapp_folder" ); $parse = explode( '/', $nodeapp_folder ); $user = $parse[2]; $domain = $parse[4]; // Ensure ports directory exists for this user; root owned like Pluginable's allocate_port, // which makes each .ports file readable only by its user $ports_dir = "/usr/local/hestia/data/hcpp/ports/$user"; if ( ! is_dir( $ports_dir ) ) { $hcpp->log( "allocate_ports: creating ports dir $ports_dir" ); @mkdir( $ports_dir, 0755, true ); } // Wipe the existing ports for this domain if ( file_exists( "/usr/local/hestia/data/hcpp/ports/$user/$domain.ports" ) ) { unlink( "/usr/local/hestia/data/hcpp/ports/$user/$domain.ports" ); } // Allocate a port for each .config.js file found if ( ! is_dir( $nodeapp_folder ) ) { $hcpp->log( "allocate_ports: $nodeapp_folder is not a directory" ); return; } $files = $this->get_config_files( $nodeapp_folder ); foreach($files as $file) { // Get the name of the app from the filename if ( ! preg_match( '/\.config\.js$/', $file ) ) continue; $file = explode( '/', $file ); $file = end( $file ); $name = str_replace( '.config.js', '', $file ); $name = preg_replace( "/[^a-zA-Z0-9-_]+/", "", $name ) . "_port"; // Allocate a port for the app $hcpp->allocate_port( $name, $user, $domain ); } // Throw a nodeapp event to allow other plugins to allocate ports $args = [ 'user' => $user, 'domain' => $domain, 'nodeapp_folder' => $nodeapp_folder ]; $hcpp->do_action( 'nodeapp_ports_allocated', $args ); } /** * Constructor, listen for the priv_change_web_domain_proxy_tpl event */ public function __construct() { global $hcpp; $hcpp->add_action( 'v_change_web_domain_proxy_tpl', [ $this, 'v_change_web_domain_proxy_tpl'] ); $hcpp->add_action( 'v_delete_web_domain_backend', [ $this, 'v_delete_web_domain_backend' ] ); $hcpp->add_action( 'v_delete_web_domain', [ $this, 'v_delete_web_domain_backend' ] ); $hcpp->add_action( 'v_rebuild_web_domain', [ $this, 'v_rebuild_web_domain' ] ); $hcpp->add_action( 'v_suspend_web_domain', [ $this, 'v_suspend_web_domain' ] ); $hcpp->add_action( 'v_unsuspend_web_domain', [ $this, 'v_unsuspend_domain' ] ); // Bulk unsuspend domains only throws this event $hcpp->add_action( 'v_unsuspend_domain', [ $this, 'v_unsuspend_domain' ] ); // Individually unsuspend domain only throws this event $hcpp->add_action( 'v_update_sys_queue', [ $this, 'v_update_sys_queue' ] ); $hcpp->add_action( 'hcpp_invoke_plugin', [ $this, 'hcpp_invoke_plugin' ] ); $hcpp->add_action( 'hcpp_list_web_xpath', [ $this, 'hcpp_list_web_xpath' ] ); $hcpp->add_action( 'hcpp_list_updates_xpath', [ $this, 'hcpp_list_updates_xpath' ] ); $hcpp->add_action( 'hcpp_add_webapp_xpath', [ $this, 'hcpp_add_webapp_xpath' ] ); $hcpp->add_action( 'hcpp_rebooted', [ $this, 'hcpp_rebooted' ] ); $hcpp->add_action( 'hcpp_runuser', [ $this, 'hcpp_runuser' ] ); $hcpp->add_action( 'v_restart_proxy', [ $this, 'v_restart_proxy'] ); // Rewrite config files on ssl related events $hcpp->add_action( 'v_add_web_domain_ssl', [ $this, 'update_nginx_files'] ); $hcpp->add_action( 'v_delete_web_domain_ssl', [ $this, 'update_nginx_files'] ); $hcpp->add_action( 'v_add_web_domain_ssl_force', [ $this, 'update_nginx_files'] ); $hcpp->add_action( 'v_delete_web_domain_ssl_force', [ $this, 'update_nginx_files'] ); $hcpp->add_custom_page( 'nodeapp', __DIR__ . '/pages/nodeapp.php' ); $hcpp->add_custom_page( 'nodeapplog', __DIR__ . '/pages/nodeapplog.php' ); } /** * Do maintenance will shutdown all running apps, across all users that are * using the specified major version of NodeJS and invoke the given callback. * Lastly, after the callback has returned, the apps will be restarted. * * @param callable $cb_maintenance The callback to invoke after all apps have been shutdown, a [user=>apps] array will be passed of stopped apps. * @param array $majors The list of major nodejs versions to perform maintenance on; leave empty to shutdown apps from all versions. * @param array $apps The list of apps to perform maintenance on; leave empty to shutdown all apps. */ public function do_maintenance( $cb_maintenance = null, $majors = [], $apps = [] ) { // Check if majors array is empty and get all majors as default global $hcpp; $hcpp->log( 'nodeapp do_maintenance' ); $hcpp->log( $majors ); if ( count( $majors ) == 0 ) { $versions = $this->get_versions(); foreach( $versions as $v ) { $majors[] = $hcpp->getLeftMost( $v['installed'], '.' ); } } // Get user list of PM2 (bash) capable users $all = $hcpp->run( 'v-list-users json' ); $users = []; foreach( $all as $user => $details ) { if ( $details['SHELL'] == 'bash' ) { $users[] = $user; } } // Find any running apps using the major version across all users $pm2_list = []; $pm2_configs = []; // config.js paths; PM2 ids may change if the daemon is refreshed foreach( $users as $user) { $pm2 = $this->get_pm2_list( $user ); if ( is_null( $pm2 ) ) continue; foreach( $pm2 as $p ) { if ( $p['pm2_env']['status'] == 'online' ) { $version = $p['pm2_env']['exec_interpreter']; $version = $hcpp->getRightMost( $version, '/v' ); $version = $hcpp->getLeftMost( $version, '/' ); $major = $hcpp->getLeftMost( $version, '.' ); if ( in_array( $major, $majors ) ) { // Filter by app name i.e. 'ghost' in 'ghost | test1.dev.pw' $name = $hcpp->getLeftMost( $p['name'], ' | ' ); if ( count( $apps ) == 0 || in_array( $name, $apps ) ) { $pm2_list[$user][] = $p['pm_id']; $pm2_configs[$user][] = $p['pm2_env']['cwd'] . '/' . $name . '.config.js'; } } } } } // Shutdown all apps by id for each user foreach( $pm2_list as $user => $app_ids ) { if ( count( $app_ids ) > 0 ) { $this->stop_pm2_ids( $app_ids, $user ); } } // Invoke the maintenance callback if ( is_callable( $cb_maintenance ) ) { $cb_maintenance( $pm2_list ); } // Restart the stopped apps by config file for each user foreach( $pm2_configs as $user => $configs ) { if ( count( $configs ) > 0 ) { $this->restart_pm2_configs( $configs, $user ); } } } /** * Throw the nodeapp_nginx_modified event to allow other plugins to modify the nginx config files */ public function do_nginx_modified( $restart = false ) { global $hcpp; $hcpp->log( "do_nginx_modified with restart: $restart" ); // Take the queue atomically so entries appended while processing aren't lost $queue = self::NGINX_MODIFIED . '.processing'; if ( ! file_exists( self::NGINX_MODIFIED ) || ! rename( self::NGINX_MODIFIED, $queue ) ) { return; } $fp = fopen( $queue, 'r' ); flock( $fp, LOCK_EX ); // Wait for any append already holding the lock $lines = file( $queue, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ); unlink( $queue ); fclose( $fp ); // Remove any duplicate lines $lines = array_unique( $lines ); $conf_folders = []; foreach( $lines as $line ) { $line = explode( ' ', $line ); $user = $line[0]; $domain = $line[1]; $conf_folders[] = trim( "/home/$user/conf/web/$domain" ); } $conf_folders = $hcpp->do_action( "nodeapp_nginx_confs_written", $conf_folders ); if ( $restart ) { $hcpp->run( "v-restart-proxy" ); } } /** * Delete the PM2 apps for the given user by ids. * * @param array $pm2_ids The list of PM2 process ids to delete */ public function delete_pm2_ids( $pm2_ids ) { $username = $_SESSION["user"]; if ($_SESSION["look"] != "") { $username = $_SESSION["look"]; } global $hcpp; $pm2_ids = escapeshellarg( json_encode( $pm2_ids ) ); $list = json_decode( $hcpp->run("v-invoke-plugin nodeapp_delete_pm2_ids " . $username . ' ' . $pm2_ids ), true ); } /** * Gather a list of all valid PM2 configuration files that allocate ports from the given folder */ public function get_config_files( $dir ) { global $hcpp; $configFiles = array(); $files = scandir( $dir ); foreach ( $files as $file ) { if ( $file == '.' || $file == '..' ) continue; $path = $dir . '/' . $file; if ( is_dir( $path ) && $file != "node_modules" ) { $configFiles = array_merge( $configFiles, $this->get_config_files( $path ) ); } else if ( preg_match('/\.config\.js$/', $file ) ) { // Sanitize the name of the app to prevent Nginx injection if ( ! preg_match( '/\.config\.js$/', $file ) ) continue; $file = explode( '/', $file ); $file = end( $file ); $name = str_replace( '.config.js', '', $file ); $name = preg_replace( "/[^a-zA-Z0-9-_]+/", "", $name ); if ( $path == $dir . '/' . $name . '.config.js' ) { // Check for hestia pm2 port allocating validity if ( file_exists( $path ) && strpos( file_get_contents( $path ), '/usr/local/hestia') !== false ) { $configFiles[] = $path; } } } } return $configFiles; } /** * Generate Nginx proxy settings for each .config.js file found in subfolders * and map the subfolder to a matching reverse proxy url of the same path */ public function generate_nginx_files( $nodeapp_folder, $inc_root = true ) { global $hcpp; $parse = explode( '/', $nodeapp_folder ); $user = $parse[2]; $domain = $parse[4]; $files = $this->get_config_files( $nodeapp_folder ); // Remove prior nginx config files if ( file_exists( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp" ) ) { unlink( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp" ); } if ( file_exists( "/home/$user/conf/web/$domain/nginx.conf_nodeapp" ) ) { unlink( "/home/$user/conf/web/$domain/nginx.conf_nodeapp" ); } // Write port variables in nginx.hsts.conf_ports and nginx.forcessl.conf_ports $file = "/usr/local/hestia/data/hcpp/ports/$user/$domain.ports"; if ( file_exists( $file ) ) { $content = "include /usr/local/hestia/data/hcpp/ports/$user/$domain.ports;"; file_put_contents( "/home/$user/conf/web/$domain/nginx.forcessl.conf_ports", $content ); file_put_contents( "/home/$user/conf/web/$domain/nginx.hsts.conf_ports", $content ); }else{ if ( file_exists( "/home/$user/conf/web/$domain/nginx.forcessl.conf_ports" ) ) { unlink( "/home/$user/conf/web/$domain/nginx.forcessl.conf_ports" ); } if ( file_exists( "/home/$user/conf/web/$domain/nginx.hsts.conf_ports" ) ) { unlink( "/home/$user/conf/web/$domain/nginx.hsts.conf_ports" ); } } // Generate new nodeapp nginx config files $nginx = ''; foreach($files as $file) { $subfolder = str_replace( "$nodeapp_folder/", '', $file ); if ( strpos( $subfolder, '/' ) === false ) { $subfolder = '/'; }else{ $subfolder = '/' . $hcpp->delRightMost($subfolder, '/') . '/'; } if ( $inc_root == false && $subfolder == '/' ) continue; // Skip root $app = $hcpp->getRightMost( $file, '/' ); $app = str_replace( '.config.js', '', $app ); $nginx .= 'location ' . $subfolder . ' { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; proxy_pass http://127.0.0.1:$' . $app . '_port; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }' . "\n"; } // Write the nginx config nodeapp subfolder file to the user's conf folder if ($nginx != '') { $args = [ 'user' => $user, 'domain' => $domain, 'nginx' => $nginx ]; // Allow other plugins to modify nginx conf_nodeapp files $args = $hcpp->do_action( 'nodeapp_write_conf_nodeapp', $args ); $nginx = $args['nginx']; file_put_contents( "/home/$user/conf/web/$domain/nginx.conf_nodeapp", $nginx ); // Overrite the proxy_hide_header in the SSL config file $nginx .= "# Override prev. proxy_hide_header Upgrade\nadd_header Upgrade \$http_upgrade always;"; $args['nginx'] = $nginx; $args = $hcpp->do_action( 'nodeapp_write_ssl_conf_nodeapp', $args ); $nginx = $args['nginx']; file_put_contents( "/home/$user/conf/web/$domain/nginx.ssl.conf_nodeapp", $nginx ); } // Queue for single nginx files modified event; append $user $domain if not already queued $queued = file_exists( self::NGINX_MODIFIED ) ? file( self::NGINX_MODIFIED, FILE_IGNORE_NEW_LINES ) : []; if ( ! in_array( "$user $domain", $queued ) ) { file_put_contents( self::NGINX_MODIFIED, "$user $domain\n", FILE_APPEND | LOCK_EX ); } } /** * Get the list of PM2 processes for the given user * * @param string $user The username to get the PM2 process list for or the current HestiaCP user if not provided * @return array The list of PM2 processes for the given user */ public function get_pm2_list( $user = '""' ) { if ( $user == '""' && isset( $_SESSION ) ) { $user = $_SESSION['user']; if ( $_SESSION['look'] != '' ) { $user = $_SESSION['look']; } } global $hcpp; $list = $hcpp->run("v-invoke-plugin nodeapp_pm2_jlist " . $user); $list = '[' . $hcpp->delLeftMost( $list, '[' ); $list = json_decode( $list, true ); return $list; } /** * Get the log for the given PM2 process under the given user */ public function get_pm2_log( $pm2_id ) { $username = $_SESSION["user"]; if ($_SESSION["look"] != "") { $username = $_SESSION["look"]; } global $hcpp; $log = $hcpp->run("v-invoke-plugin nodeapp_pm2_log " . $username . ' ' . $pm2_id ); return $log; } /** * Get the installed and latest versions of nvm managed NodeJS installs. */ public function get_versions() { global $hcpp; // Find the latest available version of each major from a single remote listing $latest = []; $remote = $hcpp->runuser( '', "nvm ls-remote --no-colors" ); preg_match_all( '/v(\d+)\.(\d+)\.(\d+)/', $remote, $matches, PREG_SET_ORDER ); foreach( $matches as $m ) { $version = "$m[1].$m[2].$m[3]"; if ( ! isset( $latest[$m[1]] ) || version_compare( $version, $latest[$m[1]], '>' ) ) { $latest[$m[1]] = $version; } } // Read installed versions from disk; if the remote listing failed, report as up-to-date $versions = []; foreach( glob( '/opt/nvm/versions/node/v*', GLOB_ONLYDIR ) as $dir ) { $installed = ltrim( basename( $dir ), 'v' ); $major = $hcpp->getLeftMost( $installed, '.' ); $versions[] = [ 'installed' => $installed, 'latest' => $latest[$major] ?? $installed ]; } usort( $versions, function( $a, $b ) { return version_compare( $a['installed'], $b['installed'] ); }); return $versions; } /** * Restart proxy on modified nginx config files */ public function hcpp_add_webapp_xpath( $xpath ) { global $hcpp; if ( file_exists( self::NGINX_MODIFIED ) ) { $hcpp->run( "v-invoke-plugin nodeapp_nginx_modified" ); } return $xpath; } /** * Process the PM2 list command request */ public function hcpp_invoke_plugin( $args ) { global $hcpp; if ( isset( $args[1] ) ) { $username = preg_replace( "/[^a-zA-Z0-9-_]+/", "", $args[1] ); // Sanitized username } switch ( $args[0] ) { case 'nodeapp_get_versions': $hcpp->log( 'nodeapp_get_versions' ); echo json_encode( $this->get_versions() ); break; case 'nodeapp_pm2_jlist': echo $hcpp->runuser( $username, 'pm2 jlist' ); break; case 'nodeapp_delete_pm2_ids': try { $pm2_ids = json_decode( $args[2], true ); }catch( Exception $e ) { $pm2_ids = []; } $cmd = ''; foreach( $pm2_ids as $id ) { $cmd .= 'pm2 delete ' . $id . '; '; } $cmd .= 'pm2 save --force'; $hcpp->runuser( $username, $cmd ); break; case 'nodeapp_stop_pm2_ids': try { $pm2_ids = json_decode( $args[2], true ); }catch( Exception $e ) { $pm2_ids = []; } $cmd = ''; foreach( $pm2_ids as $id ) { $cmd .= 'pm2 stop ' . $id . '; pm2 reset ' . $id . '; '; } $cmd .= 'pm2 save --force'; $hcpp->runuser( $username, $cmd ); // Force remove the PM2 logs $error_log_path = $hcpp->runuser( $username, 'pm2 info ' . $id . ' | grep "error log path"' ); $error_log_path = '/' . $hcpp->delLeftMost( $error_log_path, '/' ); $error_log_path = $hcpp->delRightMost( $error_log_path, '.log' ) . '.log'; $out_log_path = str_replace( '-error.log', '-out.log', $error_log_path ); $cmd = 'rm -f ' . $error_log_path . '; ' . 'rm -f ' . $out_log_path; $hcpp->runuser( $username, $cmd ); break; case 'nodeapp_restart_pm2_ids': try { $pm2_ids = json_decode( $args[2], true ); }catch( Exception $e ) { $pm2_ids = []; } // Restart via config.js filename; find by pm2_id $list = $hcpp->runuser( $username, 'pm2 jlist' ); $list = '[' . $hcpp->delLeftMost( $list, '[' ); $list = json_decode( $list, true ); $cmd = ''; foreach( $pm2_ids as $id ) { foreach( $list as $app ) { if ( $app['pm_id'] == $id ) { // Get the config.js file based on the script file $config = $hcpp->getLeftMost( $app['name'], ' | ' ); $config = $app['pm2_env']['cwd'] . '/' . $config . '.config.js'; if ( $config != '' ) { $cmd .= 'pm2 restart ' . $config . '; '; } } } } $cmd .= 'pm2 save --force'; $hcpp->runuser( $username, $cmd ); break; case 'nodeapp_restart_pm2_configs': $configs = json_decode( $args[2] ?? '[]', true ); if ( ! is_array( $configs ) ) $configs = []; $cmd = ''; foreach( $configs as $config ) { // Only allow existing *.config.js files within the user's web folder $real = realpath( $config ); if ( $real === false || strpos( $real, "/home/$username/web/" ) !== 0 ) continue; if ( substr( $real, -10 ) != '.config.js' ) continue; $cmd .= 'pm2 restart ' . escapeshellarg( $real ) . '; '; } $cmd .= 'pm2 save --force'; $hcpp->runuser( $username, $cmd ); break; case 'nodeapp_pm2_log': $pm2_id = $args[2]; $pm2_id = filter_var( $pm2_id, FILTER_SANITIZE_NUMBER_INT ); echo $hcpp->runuser( $username, 'pm2 logs --lines 4096 --nostream --raw --no-color ' . $pm2_id . ' 2>&1' ); break; case 'nodeapp_nginx_modified': // Debounce allows use to queue and delay under higher loads $cmd = "nohup " . __DIR__ . "/nodeapp_debounce.sh > /dev/null 2>&1 &"; $hcpp->log( $cmd ); $hcpp->log( shell_exec( $cmd ) ); break; case 'nodeapp_debounce': if ( file_exists( self::NGINX_MODIFIED ) ) { $this->do_nginx_modified( true ); } break; } return $args; } public function hcpp_list_updates_xpath( $xpath ) { global $hcpp; $query = '//div[contains(@class, "units-table-row") and .//div[contains(@class, "units-table-cell") and contains(normalize-space(.), "hcpp-nodeapp")]]'; // Add the CSS to the head of the document $css = 'div.units-table-cell .sub-unit {float:left;margin:-3px 5px 0px 15px;}'; $head = $xpath->query('//head')->item(0); $style = $xpath->document->createElement('style', $css); $head->appendChild($style); // Inject list of NodeJS versions below hcpp-nodeapp in the updates list $nodes = $xpath->query($query); if ($nodes->length > 0) { // Get the list of NodeJS versions from the cache $versions = $hcpp->run( 'v-invoke-plugin nodeapp_get_versions json' ); $firstNode = $nodes->item(0); $arch = php_uname('m') == 'x86_64' ? 'amd64' : (php_uname('m') == 'aarch64' ? 'arm64' : 'unknown'); $html = ''; foreach ( $versions as $v ) { $installed = $v['installed']; $latest = $v['latest']; $major = $hcpp->getLeftMost( $installed, '.' ); if ( $installed != $latest ) { $icon = ''; $disabled = 'disabled '; $notice = '(update ' . $latest . ' available)'; }else{ $icon = ''; $disabled = ''; $notice = ''; } $html .= '