mirror of
https://github.com/ByLegenS/ntg-service-manager.git
synced 2026-04-27 04:45:50 +03:00
No description
| bin | ||
| cmd | ||
| internal | ||
| tests | ||
| .dockerignore | ||
| .gitignore | ||
| build-test.bat | ||
| build-test.sh | ||
| config.docker.yaml | ||
| config.template.yaml | ||
| docker-build.ps1 | ||
| docker-build.sh | ||
| docker-compose.yml | ||
| DOCKER.md | ||
| Dockerfile | ||
| go.mod | ||
| go.sum | ||
| Makefile | ||
| README.md | ||
NTG Service Manager
Cross-platform Multi-Process Manager ve IPC Server
NTG Service Manager, birden fazla servisi (Apache, PHP, MariaDB, Nginx, PostgreSQL vb.) tek bir Windows Service veya systemd daemon olarak yönetmenizi sağlayan, Go ile yazılmış gelişmiş bir process manager'dır.
📋 İçindekiler
- Özellikler
- Mimari
- Kurulum
- Docker Deployment
- Kullanım
- IPC Komutları
- Konfigürasyon
- Örnekler
- Testler
- Geliştirme
- Lisans
🎯 Özellikler
Multi-Process Management
- ✅ Aynı anda birden fazla process yönetimi (Apache@8.2, Apache@8.3, MariaDB@11.0, PHP@8.3 vb.)
- ✅ Process isimlendirme - Her process benzersiz isimle yönetilir
- ✅ Bağımsız lifecycle - Her process bağımsız olarak start/stop/restart edilebilir
- ✅ Process status tracking - PID, uptime, restart count, crash durumu
Auto-Restart & Monitoring
- ✅ Crash detection - Process çökerse otomatik algılama
- ✅ Auto-restart - Configurable retry limit ile otomatik yeniden başlatma
- ✅ Exponential backoff - Sürekli çöken process'lere karşı backoff stratejisi
- ✅ Max retry limit - Belirli bir limitten sonra restart'ı durdurma
Graceful Reload (Downtime Yok!)
- ✅ Linux: POSIX Signals - SIGHUP (reload), SIGUSR1 (graceful), SIGUSR2
- ✅ Windows: Custom Handlers - Apache graceful (
httpd.exe -k graceful), Nginx reload (nginx.exe -s reload) - ✅ PROCESS_SIGNAL IPC komutu - Remote graceful reload desteği
IPC Server
- ✅ JSON-based IPC Protocol - REST-like command/response yapısı
- ✅ Multi-transport - TCP, Named Pipe (Windows), Unix Socket (Linux)
- ✅ API Key Authentication - Güvenli erişim kontrolü
- ✅ 10+ IPC Commands - Process, file, service yönetimi
Windows Service / systemd Integration
- ✅ Windows Service API - SCM entegrasyonu,
sc.exekomutları - ✅ systemd wrapper - Linux daemon desteği
- ✅ Foreground mode - Console'da direkt çalıştırma (development)
Security
- ✅ Path traversal prevention - Dosya yolu doğrulama
- ✅ File write whitelist - Sadece izin verilen dizinlere yazma
- ✅ Command injection prevention - Güvenli komut çalıştırma
- ✅ API key validation - Her IPC request doğrulanır
Cross-Platform
- ✅ Windows 11 - Primary platform (production-ready)
- ✅ Linux - Secondary platform (systemd, POSIX signals)
- ✅ Platform-specific code - Build tags ile ayrılmış implementasyonlar
🏗️ Mimari
Modüler Yapı
ntg-service-manager/
├── cmd/ # Entry point
│ └── main.go
├── internal/ # Private packages
│ ├── admin/ # Admin operations (file, process, command)
│ │ ├── command.go # Custom command executor
│ │ ├── file.go # File operations handler
│ │ ├── process.go # Process operations handler
│ │ ├── process_linux.go # Linux POSIX signals
│ │ └── process_windows.go # Windows custom reload handlers
│ ├── config/ # Config management (Singleton)
│ │ ├── config.go # Config loader
│ │ └── validator.go # Config validation
│ ├── constants/ # Global constants (enum-like)
│ │ ├── constants.go
│ │ ├── ipc_commands.go
│ │ ├── log_level.go
│ │ └── service_status.go
│ ├── ipc/ # IPC server (Singleton)
│ │ ├── client.go # IPC client (health check)
│ │ ├── handler.go # Request handler
│ │ ├── security.go # Security layer
│ │ └── server.go # IPC server
│ ├── logger/ # Multi-output logger (Singleton)
│ │ ├── child.go # Child process logger
│ │ └── logger.go # Main logger
│ ├── process/ # Process manager (Singleton)
│ │ ├── manager.go # Multi-process manager
│ │ └── monitor.go # Crash detection & restart
│ ├── security/ # Security utilities
│ │ ├── path.go # Path validation
│ │ └── validation.go # Input validation
│ └── service/ # Service integration
│ ├── linux.go # systemd wrapper
│ ├── service.go # Service interface
│ └── windows.go # Windows Service API
├── pkg/ # Public packages (reusable)
│ ├── types/ # Shared types
│ └── utils/ # Shared utilities
├── tests/ # Tests
│ ├── integration/ # Integration tests (50 tests)
│ └── unit/ # Unit tests
├── config.template.yaml # Default config template
├── go.mod
├── go.sum
└── README.md
Singleton Pattern
Tüm core bileşenler singleton pattern kullanır (thread-safe):
- Config -
config.GetInstance() - Logger -
logger.GetInstance() - ProcessManager -
process.GetInstance() - IPCServer -
ipc.GetInstance()
Multi-Process Architecture
┌──────────────────────────────────────────────────────────┐
│ ntg-service-manager (Windows Service / systemd daemon) │
│ ┌────────────────────────────────────────────────────┐ │
│ │ ProcessManager (Multi-process tracking) │ │
│ │ ┌──────────────────────────────────────────────┐ │ │
│ │ │ processes map[string]*ProcessInfo │ │ │
│ │ │ ├─ apache@8.2 (PID: 1234, Running) │ │ │
│ │ │ ├─ apache@8.3 (PID: 1235, Running) │ │ │
│ │ │ ├─ mariadb@11.0 (PID: 1236, Running) │ │ │
│ │ │ └─ php@8.3 (PID: 1237, Running) │ │ │
│ │ └──────────────────────────────────────────────┘ │ │
│ │ │ │
│ │ IPC Server (TCP: 127.0.0.1:7251) │ │
│ │ ├─ PROCESS_START → StartProcess() │ │
│ │ ├─ PROCESS_STOP → StopProcess() │ │
│ │ ├─ PROCESS_RESTART → RestartProcess() │ │
│ │ ├─ PROCESS_STATUS → GetProcessStatus() │ │
│ │ ├─ PROCESS_LIST → ListProcesses() │ │
│ │ ├─ PROCESS_SIGNAL → SendSignal() (reload!) │ │
│ │ ├─ FILE_WRITE → WriteFile() │ │
│ │ └─ FILE_READ → ReadFile() │ │
│ └────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘
▲ ▲
│ IPC Client (Node.js, Python, Go, etc.) │
└───────────────────────────────────────────┘
📦 Kurulum
Gereksinimler
- Go 1.21+
- Windows 11 (primary) veya Linux (secondary)
- Admin/root yetkisi (Windows Service / systemd için)
Build
# Clone repository
git clone https://github.com/ByLegenS/ntg-service-manager.git
cd ntg-service-manager
# Build for Windows
GOOS=windows GOARCH=amd64 go build -o bin/ntg-service-manager.exe cmd/main.go
# Build for Linux
GOOS=linux GOARCH=amd64 go build -o bin/ntg-service-manager cmd/main.go
# Local build (current platform)
go build -o bin/ntg-service-manager cmd/main.go
Windows Service Olarak Kurulum
# Administrator PowerShell açın
# Service kur
.\bin\ntg-service-manager.exe install
# Service başlat
sc start NTGServiceManager
# Service status
sc query NTGServiceManager
# Service durdur
sc stop NTGServiceManager
# Service kaldır
.\bin\ntg-service-manager.exe uninstall
systemd Daemon Olarak Kurulum (Linux)
# systemd service file oluştur
sudo nano /etc/systemd/system/ntg-service-manager.service
# İçeriği:
# [Unit]
# Description=NTG Service Manager
# After=network.target
#
# [Service]
# Type=simple
# ExecStart=/usr/local/bin/ntg-service-manager --service
# Restart=on-failure
#
# [Install]
# WantedBy=multi-user.target
# Binary kopyala
sudo cp bin/ntg-service-manager /usr/local/bin/
# Service enable & start
sudo systemctl enable ntg-service-manager
sudo systemctl start ntg-service-manager
# Status kontrol
sudo systemctl status ntg-service-manager
Foreground Mode (Development)
# Doğrudan console'da çalıştır
.\bin\ntg-service-manager.exe --foreground
🐳 Docker Deployment
Docker container olarak çalıştırmak için en hızlı yol! Linux ortamında test etmek için idealdir.
Hızlı Başlangıç
# 1. Build
./docker-build.sh runtime latest
# veya Windows PowerShell: .\docker-build.ps1
# 2. Test
docker-compose run test
# 3. Çalıştır
docker-compose up -d ntg-manager
# 4. Logs
docker-compose logs -f ntg-manager
# 5. IPC Test
docker-compose run test-client
Docker Komutları
# Build runtime image
docker build --target runtime -t ntg-service-manager:latest .
# Build test image (tests dahil)
docker build --target test -t ntg-service-manager:test .
# Run container
docker run -d \
--name ntg-manager \
-p 7251:7251 \
-v $(pwd)/logs:/app/logs \
-e LOG_LEVEL=INFO \
ntg-service-manager:latest
# Test çalıştır
docker run --rm ntg-service-manager:test
# Interactive shell
docker exec -it ntg-manager sh
Docker Compose
# docker-compose.yml
version: '3.8'
services:
ntg-manager:
build: .
ports:
- "7251:7251"
volumes:
- ./logs:/app/logs
- ./config.docker.yaml:/app/config.yaml:ro
environment:
- LOG_LEVEL=INFO
- IPC_API_KEY=your-api-key
Multi-Stage Build
- Builder: Go build ve dependencies (~800 MB)
- Test: Integration ve unit testler (~800 MB)
- Runtime: Minimal Alpine image (~25 MB) ✅
Detaylı Dokümantasyon
Daha fazla bilgi için: DOCKER.md
🚀 Kullanım
1. Konfigürasyon Dosyası Oluştur
# Template kopyala
cp config.template.yaml config.yaml
# Düzenle
nano config.yaml
2. Multi-Process Başlatma
IPC Client ile (Önerilen):
# Apache 8.2 başlat
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_START",
"apiKey": "your-api-key",
"data": {
"name": "apache@8.2",
"executable": "C:\\Apache24\\bin\\httpd.exe",
"args": ["-D", "FOREGROUND"],
"restart": {"enabled": true, "maxRetries": 3}
}
}'
# MariaDB 11.0 başlat
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_START",
"apiKey": "your-api-key",
"data": {
"name": "mariadb@11.0",
"executable": "C:\\MariaDB\\bin\\mysqld.exe",
"args": ["--console"],
"restart": {"enabled": true, "maxRetries": 5}
}
}'
3. Process Yönetimi
# Process listele
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_LIST",
"apiKey": "your-api-key"
}'
# Process status
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_STATUS",
"apiKey": "your-api-key",
"data": {"name": "apache@8.2"}
}'
# Process durdur
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_STOP",
"apiKey": "your-api-key",
"data": {"name": "apache@8.2"}
}'
# Process restart
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_RESTART",
"apiKey": "your-api-key",
"data": {"name": "apache@8.2"}
}'
4. Graceful Reload (Downtime Yok!)
# Apache graceful reload (downtime yok!)
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_SIGNAL",
"apiKey": "your-api-key",
"data": {
"name": "apache@8.2",
"signal": "reload"
}
}'
# Linux: SIGHUP gönderir
# Windows: httpd.exe -k graceful çalıştırır
📡 IPC Komutları
Process Management
| Komut | Açıklama | Parametreler |
|---|---|---|
PROCESS_START |
Yeni process başlat | name, executable, args, restart, shutdown |
PROCESS_STOP |
Process durdur | name |
PROCESS_RESTART |
Process restart | name |
PROCESS_STATUS |
Process status | name |
PROCESS_LIST |
Tüm process'leri listele | - |
PROCESS_SIGNAL |
Signal gönder (graceful reload) | name, signal |
File Operations
| Komut | Açıklama | Parametreler |
|---|---|---|
FILE_WRITE |
Dosyaya yaz | path, content, backup |
FILE_READ |
Dosyadan oku | path |
FILE_APPEND |
Dosyaya ekle | path, content |
FILE_DELETE |
Dosyayı sil | path |
Service Operations (Windows/Linux)
| Komut | Açıklama | Parametreler |
|---|---|---|
SERVICE_START |
Windows Service/systemd başlat | name |
SERVICE_STOP |
Windows Service/systemd durdur | name |
SERVICE_RESTART |
Windows Service/systemd restart | name |
System
| Komut | Açıklama | Parametreler |
|---|---|---|
PING |
Health check | - |
COMMAND_EXECUTE |
Standalone komut çalıştır | command, args |
PROCESS_SIGNAL - Platform-Specific Signals
Linux (POSIX Signals):
| Signal | POSIX | Açıklama |
|---|---|---|
reload |
SIGHUP |
Config reload (graceful) |
graceful |
SIGUSR1 |
Graceful restart |
USR2 |
SIGUSR2 |
Custom signal |
TERM |
SIGTERM |
Terminate signal |
INT |
SIGINT |
Interrupt signal |
Windows (Custom Handlers):
| Process | Signal | Komut |
|---|---|---|
| Apache | reload |
httpd.exe -k graceful |
| Nginx | reload |
nginx.exe -s reload |
| Diğer | - | ❌ Hata (POSIX signal yok) |
⚙️ Konfigürasyon
config.yaml Örneği
# NTG Service Manager Configuration
process:
# DEPRECATED: Single-process config artık kullanılmıyor
# Multi-process için IPC PROCESS_START komutu kullanın
executable: ""
args: []
workingDir: ""
env: {}
restart:
enabled: true # Auto-restart aktif
maxRetries: 3 # Maksimum 3 restart
backoff:
initial: 1000 # İlk 1 saniye bekle
max: 60000 # Maksimum 60 saniye bekle
multiplier: 2.0 # Her restart'ta 2x artır
shutdown:
timeout: 5000 # Graceful shutdown 5 saniye
childProcess:
captureStdout: true # stdout yakala
captureStderr: true # stderr yakala
logging:
level: "INFO" # DEBUG, INFO, WARN, ERROR
file:
enabled: true
path: "./logs/service.log"
maxSize: 10485760 # 10 MB
maxBackups: 5
compress: true
childProcess:
enabled: true
path: "./logs/child-process.log"
maxSize: 10485760
maxBackups: 3
ipc:
enabled: true
transport: "tcp" # tcp, namedpipe, unixsocket
tcp:
host: "127.0.0.1"
port: 7251
namedPipe:
name: "ntg-privilege-manager"
unixSocket:
path: "/var/run/ntg-privilege-manager.sock"
security:
apiKey: "your-secure-api-key-here" # API key authentication
fileOperations:
allowedPaths:
- "C:\\Windows\\System32\\drivers\\etc\\hosts"
- "C:\\inetpub\\wwwroot\\*"
- "/etc/hosts"
- "/var/www/html/*"
service:
name: "NTGServiceManager"
displayName: "NTG Service Manager"
description: "Multi-process manager and IPC server for privileged operations"
📚 Örnekler
Örnek 1: Apache Multi-Version Setup
# Apache 8.2 başlat (port 80)
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_START",
"apiKey": "your-api-key",
"data": {
"name": "apache@8.2",
"executable": "C:\\Apache24-8.2\\bin\\httpd.exe",
"args": ["-D", "FOREGROUND", "-f", "C:\\Apache24-8.2\\conf\\httpd.conf"],
"restart": {"enabled": true, "maxRetries": 3}
}
}'
# Apache 8.3 başlat (port 8080)
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_START",
"apiKey": "your-api-key",
"data": {
"name": "apache@8.3",
"executable": "C:\\Apache24-8.3\\bin\\httpd.exe",
"args": ["-D", "FOREGROUND", "-f", "C:\\Apache24-8.3\\conf\\httpd.conf"],
"restart": {"enabled": true, "maxRetries": 3}
}
}'
# Apache 8.2 config reload (downtime yok!)
curl -X POST http://127.0.0.1:7251 \
-H "Content-Type: application/json" \
-d '{
"command": "PROCESS_SIGNAL",
"apiKey": "your-api-key",
"data": {"name": "apache@8.2", "signal": "reload"}
}'
Örnek 2: Full LAMP Stack
# Apache başlat
PROCESS_START: apache@8.2
# MariaDB başlat
PROCESS_START: mariadb@11.0
# PHP-FPM başlat
PROCESS_START: php@8.3
# Tüm process'leri listele
PROCESS_LIST
# Apache graceful reload
PROCESS_SIGNAL: apache@8.2, signal=reload
Örnek 3: Node.js Client
const net = require('net');
class IPCClient {
constructor(host, port, apiKey) {
this.host = host;
this.port = port;
this.apiKey = apiKey;
}
async send(command, data = {}) {
return new Promise((resolve, reject) => {
const client = net.createConnection({ host: this.host, port: this.port });
const request = {
command,
apiKey: this.apiKey,
data
};
client.on('connect', () => {
client.write(JSON.stringify(request) + '\n');
});
client.on('data', (chunk) => {
const response = JSON.parse(chunk.toString());
client.end();
if (response.success) {
resolve(response.data);
} else {
reject(new Error(response.error?.message || 'Unknown error'));
}
});
client.on('error', reject);
});
}
}
// Kullanım
const client = new IPCClient('127.0.0.1', 7251, 'your-api-key');
// Apache başlat
await client.send('PROCESS_START', {
name: 'apache@8.2',
executable: 'C:\\Apache24\\bin\\httpd.exe',
args: ['-D', 'FOREGROUND'],
restart: { enabled: true, maxRetries: 3 }
});
// Process listele
const processes = await client.send('PROCESS_LIST');
console.log('Running processes:', processes);
// Apache reload
await client.send('PROCESS_SIGNAL', {
name: 'apache@8.2',
signal: 'reload'
});
🧪 Testler
Test İstatistikleri
- Toplam Go dosyası: 34
- Test dosyası: 14
- Integration test: 50 (✅ tümü başarılı)
- Test coverage: Yüksek (kritik fonksiyonlar kapsanmış)
Test Kategorileri
| Kategori | Test Sayısı | Durum |
|---|---|---|
| AdminCommands | 9 | ✅ PASS |
| FileOperations | 9 | ✅ PASS |
| IPCCommunication | 8 | ✅ PASS |
| IPCProcess | 6 | ✅ PASS |
| MultiProcess | 5 | ✅ PASS |
| NodeJSClient | 4 | ✅ PASS |
| ProcessCrash | 4 | ✅ PASS |
| ServiceLifecycle | 4 | ✅ PASS |
Testleri Çalıştırma
# Tüm testler
go test ./...
# Integration testler
go test ./tests/integration/ -v
# Specific test
go test ./tests/integration/ -v -run TestIPCProcess_Signal
# Test coverage
go test ./... -cover
# Benchmark
go test ./... -bench=.
CI/CD
# .github/workflows/test.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-latest, ubuntu-latest]
go: ['1.21', '1.22']
steps:
- uses: actions/checkout@v3
- uses: actions/setup-go@v4
with:
go-version: ${{ matrix.go }}
- name: Build
run: go build -v ./...
- name: Test
run: go test -v -timeout 120s ./...
- name: Vet
run: go vet ./...
- name: Format check
run: |
go fmt ./...
git diff --exit-code
🛠️ Geliştirme
Proje Yapısı
- Singleton Pattern: Core bileşenler (Config, Logger, ProcessManager, IPCServer)
- Interface Programming: Concrete type yerine interface kullanımı
- Platform-Specific Code: Build tags (
//go:build windows,//go:build linux) - Type-Safe: Minimal
interface{}, strict typing - Error Handling: Panic yok, error return her yerde
Kod Standartları
# Format
go fmt ./...
# Vet (static analysis)
go vet ./...
# Lint (golangci-lint gerekli)
golangci-lint run
# Dependencies
go mod tidy
go mod verify
Build Tags
//go:build windows
// +build windows
package admin
// Windows-specific implementation
//go:build linux
// +build linux
package admin
// Linux-specific implementation
Yeni Özellik Ekleme
- Interface: Önce interface tasarla
- Implementation: Platform-specific code için build tags kullan
- Tests: Integration test yaz
- Documentation: README güncelle
Debug Mode
# Logger level DEBUG
export LOG_LEVEL=DEBUG
.\bin\ntg-service-manager.exe --foreground
# Verbose IPC logging
export IPC_DEBUG=true
📊 Performans
Benchmarks
BenchmarkIPCServer_Ping-8 10000 115 µs/op
BenchmarkProcessManager_Start-8 1000 1245 µs/op
BenchmarkProcessManager_Stop-8 1000 2012 µs/op
BenchmarkLogger_Write-8 100000 12 µs/op
Resource Usage
- Memory: ~15 MB (idle), ~50 MB (10 process)
- CPU: <1% (idle), 2-5% (active)
- Startup Time: ~200ms (Windows Service), ~100ms (foreground)