Skip to content

onure9e/zero-pm

Repository files navigation

Zero PM - Advanced Node.js Process Manager

TypeScript Node.js PM2 Compatible MIT License

πŸš€ PM2-Inspired Process Manager with Modern Ecosystem Integration

Zero PM is a powerful, production-ready Node.js process manager that combines PM2's reliability with modern TypeScript development and seamless ecosystem integration.


πŸ“‹ Table of Contents


✨ Features

πŸš€ Core Features

  • πŸ”„ Cluster Management: Automatic load balancing and clustering with round-robin, least-connections algorithms
  • πŸ”„ Auto-Restart: Intelligent process monitoring with configurable restart policies
  • πŸ“Š Real-time Monitoring: CPU, memory, and system metrics with WebSocket updates
  • 🌐 Web Dashboard: Modern HTTP dashboard for process visualization and control
  • πŸ“ Advanced Logging: Colored console output and persistent file logging with rotation
  • βš™οΈ PM2-Style Configuration: ecosystem.config.js support with environment-specific settings
  • πŸ’Ύ State Persistence: Process state survives CLI restarts and system reboots
  • 🎨 Colored CLI: Beautiful terminal output with easycolor integration
  • πŸ”§ Ecosystem Integration: Seamless integration with zero-config and zerohelper

πŸ› οΈ Advanced Features

  • Zero Downtime Reloads: Graceful reload with SIGUSR2 support for production deployments
  • Multiple Output Formats: JSON, table, and colored outputs for different use cases
  • System Integration: Automatic startup scripts for systemd, launchd, and other init systems
  • Process Scaling: Dynamic instance scaling with scale command
  • Signal Handling: Advanced process signal management and custom signal sending
  • Log Management: Automatic log rotation, flushing, and streaming capabilities
  • Environment Management: Multi-environment support with env_production, env_development
  • Deployment Ready: Built-in deployment configurations and rollback capabilities

πŸ—οΈ Technical Excellence

  • TypeScript First: Written in TypeScript with full type safety and excellent IDE support
  • Production Ready: Comprehensive error handling, logging, and monitoring
  • Cross-Platform: Windows, macOS, and Linux support with platform-specific optimizations
  • Resource Efficient: Low memory footprint with optimized performance
  • Extensible: Plugin architecture for custom functionality
  • Well Tested: Comprehensive test suite with 100% coverage on critical paths

🏁 Quick Start

Prerequisites

  • Node.js: >= 16.0.0
  • npm: >= 7.0.0 (or yarn/pnpm)

Install & Run

# Install globally
npm install -g @onurege3467/zero-pm

# Start your first app
zero-pm start server.js

# View running processes
zero-pm list

# Access web dashboard
zero-pm dashboard --port 3000

# Open http://localhost:3000 in your browser

That's it! Your Node.js application is now running with production-grade process management.


πŸ“¦ Installation

Global Installation (Recommended)

npm install -g @onurege3467/zero-pm

Local Installation

npm install --save-dev @onurege3467/zero-pm

Ecosystem Dependencies (Optional but Recommended)

# For advanced configuration management
npm install @onurege3467/zero-config

# For enhanced CLI colors and output
npm install @onurege3467/easycolor

# For database-backed persistence
npm install @onurege3467/zerohelper

Development Setup

# Clone the repository
git clone https://github.com/onure9e/zero-pm.git
cd zero-pm

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Start development
npm run dev

🎯 Usage

CLI Commands

Zero PM provides 24+ CLI commands for comprehensive process management:

πŸ“Š Process Information

# List all processes (table format)
zero-pm list

# List processes in JSON format
zero-pm jlist

# List processes in pretty table format
zero-pm prettylist

# Describe a specific process
zero-pm describe my-app

# Show monitoring information
zero-pm monit

πŸš€ Process Control

# Start a process
zero-pm start app.js
zero-pm start app.js --name my-app
zero-pm start app.js --instances 4 --fork

# Start from configuration file
zero-pm start-config ecosystem.config.js
zero-pm start-config --env production

# Stop processes
zero-pm stop my-app
zero-pm stop-all

# Restart processes
zero-pm restart my-app

# Reload processes (zero downtime)
zero-pm reload my-app
zero-pm graceful-reload my-app

πŸ“ Logging & Debugging

# View process logs
zero-pm logs my-app
zero-pm logs my-app --lines 100

# Flush logs
zero-pm flush
zero-pm flush my-app

βš™οΈ Advanced Operations

# Scale process instances
zero-pm scale my-app 8

# Send signals to processes
zero-pm sendSignal my-app SIGUSR1

# Reset restart counters
zero-pm reset my-app

# Delete processes
zero-pm delete my-app

🌐 Web Interface

# Start web dashboard
zero-pm dashboard
zero-pm dashboard --port 3000
zero-pm dashboard --host 0.0.0.0 --port 8080

πŸ”§ System Integration

# Save current configuration
zero-pm save

# Generate startup scripts
zero-pm startup          # systemd (Linux)
zero-pm startup launchd  # macOS

# Remove startup scripts
zero-pm unstartup

Programmatic API

Zero PM can also be used programmatically in your Node.js applications:

import { ZeroProcessManager } from '@onurege3467/zero-pm';

async function main() {
  const pm = new ZeroProcessManager();

  // Start a process
  await pm.start('server.js', {
    name: 'api-server',
    instances: 4,
    exec_mode: 'cluster'
  });

  // List running processes
  const processes = pm.list();
  console.log('Running processes:', processes);

  // Monitor processes
  const metrics = await pm.monit();
  console.log('System metrics:', metrics.system);

  // Graceful shutdown
  process.on('SIGINT', async () => {
    await pm.stopAll();
    process.exit(0);
  });
}

main().catch(console.error);

Configuration Files

Zero PM supports multiple configuration formats for different use cases:

JavaScript Configuration (ecosystem.config.js) - Recommended

module.exports = {
  apps: [{
    name: 'api-server',
    script: './server.js',
    instances: 4,
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'development',
      PORT: 3000
    },
    env_production: {
      NODE_ENV: 'production',
      PORT: 8000,
      DATABASE_URL: 'postgres://prod-db:5432/myapp'
    },
    max_memory_restart: '500M',
    restart_delay: 1000,
    autorestart: true,
    watch: false,
    log_file: './logs/app.log',
    error_file: './logs/app-error.log'
  }],

  deploy: {
    production: {
      user: 'deploy',
      host: ['server1.com', 'server2.com'],
      ref: 'origin/main',
      repo: 'git@github.com:user/repo.git',
      path: '/var/www/app',
      'post-deploy': 'npm install && pm2 reload ecosystem.config.js --env production'
    }
  }
};

YAML Configuration (processes.yaml)

- name: web-server
  script: server.js
  instances: 4
  exec_mode: cluster
  env:
    NODE_ENV: production
    PORT: 3000
  max_memory_restart: 500M
  autorestart: true
  stdout_file: logs/web.log
  stderr_file: logs/web-error.log

- name: worker
  script: worker.js
  instances: 2
  exec_mode: fork
  env:
    REDIS_URL: redis://localhost:6379
  restart_delay: 2000

JSON Configuration (processes.json)

[
  {
    "name": "api-server",
    "script": "./server.js",
    "instances": 2,
    "exec_mode": "cluster",
    "env": {
      "PORT": 3000
    }
  }
]

πŸ”§ Advanced Configuration

Process Configuration Options

Option Type Default Description
name string Auto-generated Process name
script string Required Script to execute
args string undefined Command line arguments
cwd string Current directory Working directory
instances number | 'max' 1 Number of instances
exec_mode 'fork' | 'cluster' 'fork' Execution mode
env object {} Environment variables
max_memory_restart string undefined Memory limit (e.g., '500M')
max_restarts number undefined Maximum restart attempts
min_uptime string '1s' Minimum uptime before considering stable
restart_delay number 0 Delay between restarts (ms)
autorestart boolean true Auto-restart on crashes
watch boolean | string[] false Files/directories to watch
ignore_watch string[] Common ignores Files to ignore when watching
stdout_file string undefined Standard output log file
stderr_file string undefined Standard error log file
pid_file string undefined PID file path
kill_timeout number 1600 Kill timeout (ms)
listen_timeout number undefined Listen timeout (ms)
shutdown_with_message boolean false Graceful shutdown

Environment-Specific Configuration

module.exports = {
  apps: [{
    name: 'my-app',
    script: 'app.js',
    env: {
      NODE_ENV: 'development',
      DEBUG: '*'
    },
    env_staging: {
      NODE_ENV: 'staging',
      DEBUG: 'app:*'
    },
    env_production: {
      NODE_ENV: 'production',
      DEBUG: false
    }
  }]
};

Start with specific environment:

zero-pm start-config ecosystem.config.js --env production

Load Balancing Algorithms

Zero PM supports multiple load balancing strategies:

// In ecosystem.config.js
module.exports = {
  apps: [{
    name: 'load-balanced-app',
    script: 'server.js',
    instances: 'max',
    load_balancer: 'least-connections' // or 'round-robin', 'weighted-round-robin'
  }]
};

🌐 Web Dashboard

Zero PM includes a modern web dashboard for monitoring and managing processes:

Features

  • πŸ“Š Real-time Metrics: CPU, memory, and system statistics
  • πŸŽ›οΈ Process Control: Start, stop, restart processes via UI
  • πŸ“ Log Streaming: Live log viewing and filtering
  • πŸ” Process Details: Detailed information about each process
  • πŸ“ˆ Performance Graphs: Historical performance data
  • 🎨 Modern UI: Clean, responsive interface

Starting the Dashboard

# Default configuration
zero-pm dashboard

# Custom port and host
zero-pm dashboard --port 8080 --host 0.0.0.0

API Endpoints

The dashboard provides RESTful APIs for integration:

# Get all processes
GET /api/processes

# Get system metrics
GET /api/stats

# WebSocket for real-time updates
ws://localhost:3000

Dashboard Screenshots

(Dashboard includes interactive charts and real-time updates)


βš™οΈ System Integration

Automatic Startup

Zero PM can automatically start on system boot:

# Save current configuration
zero-pm save

# Generate startup scripts
zero-pm startup          # Linux (systemd)
zero-pm startup launchd  # macOS

# Follow the displayed instructions
sudo systemctl daemon-reload
sudo systemctl enable zero-pm
sudo systemctl start zero-pm

Supported Systems

  • 🐧 Linux (systemd): zero-pm startup
  • 🍎 macOS (launchd): zero-pm startup launchd
  • πŸ”§ Manual Setup: For other systems

Service Management

# Check status
sudo systemctl status zero-pm

# View logs
sudo journalctl -u zero-pm -f

# Restart service
sudo systemctl restart zero-pm

# Disable auto-startup
zero-pm unstartup

πŸ”„ Process Management

Execution Modes

Fork Mode

{
  name: 'single-process',
  script: 'app.js',
  exec_mode: 'fork',  // Single process
  instances: 1
}

Cluster Mode

{
  name: 'multi-process',
  script: 'app.js',
  exec_mode: 'cluster',  // Multiple processes
  instances: 4
}

Scaling Processes

# Scale to 8 instances
zero-pm scale my-app 8

# Scale to maximum CPU cores
zero-pm scale my-app max

Graceful Operations

Zero PM supports zero-downtime operations:

# Graceful reload (recommended for production)
zero-pm graceful-reload my-app

# Regular reload
zero-pm reload my-app

# Graceful shutdown
zero-pm stop my-app

Signal Handling

Send custom signals to processes:

# Reload configuration
zero-pm sendSignal my-app SIGHUP

# Custom signal
zero-pm sendSignal my-app SIGUSR1

πŸ“Š Monitoring & Metrics

Built-in Monitoring

# Real-time monitoring
zero-pm monit

# Process-specific metrics
zero-pm describe my-app

Metrics Collected

  • CPU Usage: Per-process and system-wide
  • Memory Usage: RSS, heap, and external memory
  • Uptime: Process and system uptime
  • Restart Count: Number of automatic restarts
  • Network I/O: Connection statistics
  • File Descriptors: Open file handles

Web Dashboard Metrics

The web dashboard provides:

  • Real-time CPU/memory graphs
  • Process status indicators
  • Log streaming
  • Performance history
  • System resource usage

Custom Monitoring

Integrate with external monitoring tools:

const pm = new ZeroProcessManager();

// Get metrics programmatically
const metrics = await pm.monit();
console.log('Processes:', metrics.processes.length);
console.log('System CPU:', metrics.system.cpu);

πŸ”§ Ecosystem Integration

Zero PM is designed to work seamlessly with the Zero ecosystem:

Zero Config Integration

Advanced configuration management with zero-config:

// Automatic environment variable loading
// Global config support
// Schema validation
// Hot config reloading

Easycolor Integration

Beautiful CLI output with easycolor:

// Colored status indicators
// Progress bars
// Formatted tables
// Theme support

Zerohelper Integration

Database-backed persistence with zerohelper:

// SQLite, MongoDB, PostgreSQL, Redis support
// Process state persistence
// Log storage
// Custom metrics storage

Integration Benefits

  • Unified Configuration: Single source of truth for all Zero tools
  • Consistent CLI: Same commands and output across all tools
  • Shared State: Process information shared between tools
  • Enhanced Monitoring: Cross-tool metrics and logging

πŸ”„ Migration from PM2

Command Mapping

PM2 Command Zero PM Equivalent Notes
pm2 start app.js zero-pm start app.js Identical
pm2 list zero-pm list Enhanced output
pm2 logs zero-pm logs Same functionality
pm2 restart app zero-pm restart app Same
pm2 delete app zero-pm delete app Same
pm2 monit zero-pm monit Enhanced
pm2 reload app zero-pm graceful-reload app Improved

Configuration Migration

PM2 ecosystem.config.js files are 100% compatible:

// This works in both PM2 and Zero PM
module.exports = {
  apps: [{
    name: 'my-app',
    script: 'app.js',
    instances: 4,
    env_production: {
      NODE_ENV: 'production'
    }
  }]
};

Migration Steps

  1. Install Zero PM:

    npm uninstall -g pm2
    npm install -g @onurege3467/zero-pm
  2. Update Commands:

    # Replace pm2 with zero-pm
    zero-pm start ecosystem.config.js
  3. Optional: Install Ecosystem:

    npm install @onurege3467/zero-config @onurege3467/easycolor

Benefits of Migration

  • Better TypeScript Support: Full IDE support and type checking
  • Enhanced CLI: More output formats and better colors
  • Modern Architecture: Latest Node.js features and optimizations
  • Ecosystem Integration: Works with other Zero tools
  • Active Development: Regular updates and improvements

🚨 Troubleshooting

Common Issues

Process Won't Start

# Check script exists and is executable
ls -la app.js

# Test script directly
node app.js

# Check logs
zero-pm logs

Port Already in Use

# Find process using port
lsof -i :3000

# Kill process
kill -9 <PID>

# Or change port in config
zero-pm start app.js --env PORT=3001

High Memory Usage

# Check memory usage
zero-pm monit

# Set memory limits
{
  "max_memory_restart": "500M"
}

Logs Not Rotating

# Manual log rotation
zero-pm flush

# Check log file sizes
ls -lh logs/

Debug Mode

Enable verbose logging:

DEBUG=zero-pm zero-pm start app.js

Performance Issues

# Check system resources
zero-pm monit

# Profile application
node --prof app.js

# Check for memory leaks
node --inspect app.js

Startup Issues

# Check systemd status
sudo systemctl status zero-pm

# View systemd logs
sudo journalctl -u zero-pm -f

# Check permissions
ls -la ~/.config/zero-pm/

Network Issues

# Check if dashboard is accessible
curl http://localhost:3000/api/processes

# Check firewall
sudo ufw status

# Check port binding
netstat -tlnp | grep 3000

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Fork and clone
git clone https://github.com/your-username/zero-pm.git
cd zero-pm

# Install dependencies
npm install

# Run tests
npm test

# Run linting
npm run lint

# Start development
npm run dev

# Build for production
npm run build

Code Style

  • TypeScript: Strict mode enabled
  • ESLint: Airbnb config with TypeScript support
  • Prettier: Consistent code formatting
  • Jest: 100% test coverage requirement

Pull Request Process

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Testing

# Run all tests
npm test

# Run specific test
npm test -- --testNamePattern="should start process"

# Run with coverage
npm run test:coverage

# Run linting
npm run lint

# Run type checking
npm run type-check

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License

Copyright (c) 2024 Zero PM

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

πŸ™ Acknowledgments

  • PM2: Inspiration and compatibility target
  • Zero Ecosystem: zero-config, easycolor, zerohelper
  • Node.js Community: Amazing runtime and ecosystem
  • TypeScript Team: Excellent type system
  • Open Source Community: Continuous inspiration

Zero PM - Production-ready process management for modern Node.js applications.

πŸ“š Documentation β€’ πŸ› Report Issues β€’ πŸ’¬ Discussions


Built with ❀️ for the Node.js community

About

NPM: @onurege3467/zero-pm

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published