mcp-ssh-manager 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/settings.local.json +87 -0
- package/.flake8 +15 -0
- package/.hooks-config.json +131 -0
- package/.pre-commit-config.yaml +105 -0
- package/CHANGELOG.md +137 -0
- package/CLAUDE.md +190 -0
- package/CONTRIBUTING.md +114 -0
- package/DESCRIPTION +1 -0
- package/INSTALLATION.md +180 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +77 -0
- package/README.md +718 -0
- package/cli/README.md +286 -0
- package/cli/build.sh +199 -0
- package/cli/commands/server.sh +284 -0
- package/cli/demo.sh +107 -0
- package/cli/install.sh +164 -0
- package/cli/lib/colors.sh +174 -0
- package/cli/lib/config.sh +284 -0
- package/cli/lib/menu.sh +430 -0
- package/cli/migrate.sh +168 -0
- package/cli/ssh-manager +525 -0
- package/docs/ALIASES_AND_HOOKS.md +285 -0
- package/docs/BACKUP_GUIDE.md +500 -0
- package/docs/DEPLOYMENT_GUIDE.md +241 -0
- package/docs/SEO.md +257 -0
- package/examples/backup-workflow.js +481 -0
- package/examples/claude-code-config.example.json +40 -0
- package/examples/codex-ssh-config.example.toml +71 -0
- package/examples/deploy-workflow.py +183 -0
- package/glama.json +6 -0
- package/package.json +85 -0
- package/profiles/README.md +40 -0
- package/profiles/default.json +52 -0
- package/profiles/docker.json +62 -0
- package/profiles/frappe.json +107 -0
- package/profiles/nodejs.json +63 -0
- package/pyproject.toml +17 -0
- package/scripts/setup-hooks.sh +60 -0
- package/scripts/validate.sh +76 -0
- package/src/backup-manager.js +469 -0
- package/src/command-aliases.js +151 -0
- package/src/config-loader.js +281 -0
- package/src/database-manager.js +555 -0
- package/src/deploy-helper.js +176 -0
- package/src/health-monitor.js +428 -0
- package/src/hooks-system.js +327 -0
- package/src/index.js +4499 -0
- package/src/logger.js +276 -0
- package/src/profile-loader.js +187 -0
- package/src/server-aliases.js +150 -0
- package/src/server-groups.js +409 -0
- package/src/session-manager.js +410 -0
- package/src/ssh-key-manager.js +378 -0
- package/src/ssh-manager.js +435 -0
- package/src/tunnel-manager.js +576 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import crypto from 'crypto';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Deploy helper functions for secure file deployment
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Generate a unique temporary filename
|
|
11
|
+
*/
|
|
12
|
+
export function getTempFilename(originalName) {
|
|
13
|
+
const timestamp = Date.now();
|
|
14
|
+
const random = crypto.randomBytes(4).toString('hex');
|
|
15
|
+
const ext = path.extname(originalName);
|
|
16
|
+
const base = path.basename(originalName, ext);
|
|
17
|
+
return `/tmp/${base}_${timestamp}_${random}${ext}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Build deployment strategy based on target path and permissions
|
|
22
|
+
*/
|
|
23
|
+
export function buildDeploymentStrategy(remotePath, options = {}) {
|
|
24
|
+
const {
|
|
25
|
+
sudoPassword = null,
|
|
26
|
+
owner = null,
|
|
27
|
+
permissions = null,
|
|
28
|
+
backup = true,
|
|
29
|
+
restart = null
|
|
30
|
+
} = options;
|
|
31
|
+
|
|
32
|
+
const strategy = {
|
|
33
|
+
steps: [],
|
|
34
|
+
requiresSudo: false
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// Step 1: Backup existing file if requested
|
|
38
|
+
if (backup) {
|
|
39
|
+
strategy.steps.push({
|
|
40
|
+
type: 'backup',
|
|
41
|
+
command: `if [ -f "${remotePath}" ]; then cp "${remotePath}" "${remotePath}.bak.$(date +%Y%m%d_%H%M%S)"; fi`
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Step 2: Determine if we need sudo
|
|
46
|
+
const needsSudo = remotePath.startsWith('/etc/') ||
|
|
47
|
+
remotePath.startsWith('/var/') ||
|
|
48
|
+
remotePath.startsWith('/usr/') ||
|
|
49
|
+
owner || permissions;
|
|
50
|
+
|
|
51
|
+
if (needsSudo) {
|
|
52
|
+
strategy.requiresSudo = true;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Step 3: Copy from temp to final location
|
|
56
|
+
const copyCmd = needsSudo && sudoPassword ?
|
|
57
|
+
`echo "${sudoPassword}" | sudo -S cp {{tempFile}} "${remotePath}"` :
|
|
58
|
+
needsSudo ?
|
|
59
|
+
`sudo cp {{tempFile}} "${remotePath}"` :
|
|
60
|
+
`cp {{tempFile}} "${remotePath}"`;
|
|
61
|
+
|
|
62
|
+
strategy.steps.push({
|
|
63
|
+
type: 'copy',
|
|
64
|
+
command: copyCmd
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// Step 4: Set ownership if specified
|
|
68
|
+
if (owner) {
|
|
69
|
+
const chownCmd = sudoPassword ?
|
|
70
|
+
`echo "${sudoPassword}" | sudo -S chown ${owner} "${remotePath}"` :
|
|
71
|
+
`sudo chown ${owner} "${remotePath}"`;
|
|
72
|
+
|
|
73
|
+
strategy.steps.push({
|
|
74
|
+
type: 'chown',
|
|
75
|
+
command: chownCmd
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Step 5: Set permissions if specified
|
|
80
|
+
if (permissions) {
|
|
81
|
+
const chmodCmd = sudoPassword ?
|
|
82
|
+
`echo "${sudoPassword}" | sudo -S chmod ${permissions} "${remotePath}"` :
|
|
83
|
+
`sudo chmod ${permissions} "${remotePath}"`;
|
|
84
|
+
|
|
85
|
+
strategy.steps.push({
|
|
86
|
+
type: 'chmod',
|
|
87
|
+
command: chmodCmd
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Step 6: Restart service if specified
|
|
92
|
+
if (restart) {
|
|
93
|
+
strategy.steps.push({
|
|
94
|
+
type: 'restart',
|
|
95
|
+
command: restart
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Step 7: Cleanup temp file
|
|
100
|
+
strategy.steps.push({
|
|
101
|
+
type: 'cleanup',
|
|
102
|
+
command: 'rm -f {{tempFile}}'
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
return strategy;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Parse deployment configuration from file path patterns
|
|
110
|
+
* Examples:
|
|
111
|
+
* /home/user/app/file.js -> normal deploy
|
|
112
|
+
* /etc/nginx/sites-available/site -> needs sudo
|
|
113
|
+
* /var/www/html/index.html -> needs sudo
|
|
114
|
+
*/
|
|
115
|
+
export function detectDeploymentNeeds(remotePath) {
|
|
116
|
+
const needs = {
|
|
117
|
+
sudo: false,
|
|
118
|
+
suggestedOwner: null,
|
|
119
|
+
suggestedPerms: null
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// System directories that typically need sudo
|
|
123
|
+
if (remotePath.startsWith('/etc/')) {
|
|
124
|
+
needs.sudo = true;
|
|
125
|
+
needs.suggestedOwner = 'root:root';
|
|
126
|
+
needs.suggestedPerms = '644';
|
|
127
|
+
} else if (remotePath.startsWith('/var/www/')) {
|
|
128
|
+
needs.sudo = true;
|
|
129
|
+
needs.suggestedOwner = 'www-data:www-data';
|
|
130
|
+
needs.suggestedPerms = '644';
|
|
131
|
+
} else if (remotePath.includes('/nginx/')) {
|
|
132
|
+
needs.sudo = true;
|
|
133
|
+
needs.suggestedOwner = 'root:root';
|
|
134
|
+
needs.suggestedPerms = '644';
|
|
135
|
+
} else if (remotePath.includes('/apache/') || remotePath.includes('/httpd/')) {
|
|
136
|
+
needs.sudo = true;
|
|
137
|
+
needs.suggestedOwner = 'www-data:www-data';
|
|
138
|
+
needs.suggestedPerms = '644';
|
|
139
|
+
} else if (remotePath.includes('/frappe-bench/')) {
|
|
140
|
+
// For ERPNext/Frappe deployments
|
|
141
|
+
needs.sudo = false;
|
|
142
|
+
needs.suggestedOwner = null; // Will be handled by the app
|
|
143
|
+
needs.suggestedPerms = '644';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return needs;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Create batch deployment script for multiple files
|
|
151
|
+
*/
|
|
152
|
+
export function createBatchDeployScript(deployments) {
|
|
153
|
+
const script = ['#!/bin/bash', 'set -e', ''];
|
|
154
|
+
|
|
155
|
+
script.push('# Batch deployment script');
|
|
156
|
+
script.push(`# Generated at ${new Date().toISOString()}`);
|
|
157
|
+
script.push('');
|
|
158
|
+
|
|
159
|
+
deployments.forEach((deploy, index) => {
|
|
160
|
+
script.push(`# File ${index + 1}: ${deploy.localPath} -> ${deploy.remotePath}`);
|
|
161
|
+
deploy.strategy.steps.forEach(step => {
|
|
162
|
+
if (step.type !== 'cleanup') {
|
|
163
|
+
script.push(step.command.replace('{{tempFile}}', deploy.tempFile));
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
script.push('');
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// Cleanup all temp files at the end
|
|
170
|
+
script.push('# Cleanup temporary files');
|
|
171
|
+
deployments.forEach(deploy => {
|
|
172
|
+
script.push(`rm -f ${deploy.tempFile}`);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
return script.join('\n');
|
|
176
|
+
}
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Health Monitor for MCP SSH Manager
|
|
3
|
+
* Provides system health checks, service monitoring, and process management
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { logger } from './logger.js';
|
|
7
|
+
|
|
8
|
+
// Health status levels
|
|
9
|
+
export const HEALTH_STATUS = {
|
|
10
|
+
HEALTHY: 'healthy',
|
|
11
|
+
WARNING: 'warning',
|
|
12
|
+
CRITICAL: 'critical',
|
|
13
|
+
UNKNOWN: 'unknown'
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// Common services to monitor
|
|
17
|
+
export const COMMON_SERVICES = {
|
|
18
|
+
nginx: { systemd: 'nginx', sysv: 'nginx' },
|
|
19
|
+
apache: { systemd: 'apache2', sysv: 'apache2' },
|
|
20
|
+
mysql: { systemd: 'mysql', sysv: 'mysql' },
|
|
21
|
+
postgresql: { systemd: 'postgresql', sysv: 'postgresql' },
|
|
22
|
+
mongodb: { systemd: 'mongod', sysv: 'mongod' },
|
|
23
|
+
redis: { systemd: 'redis', sysv: 'redis-server' },
|
|
24
|
+
docker: { systemd: 'docker', sysv: 'docker' },
|
|
25
|
+
ssh: { systemd: 'sshd', sysv: 'ssh' }
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Build command to check CPU usage
|
|
30
|
+
*/
|
|
31
|
+
export function buildCPUCheckCommand() {
|
|
32
|
+
// Get CPU usage using top, show idle percentage, calculate used
|
|
33
|
+
return `top -bn1 | grep "Cpu(s)" | sed "s/.*, *\\([0-9.]*\\)%* id.*/\\1/" | awk '{print 100 - $1}'`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Build command to check memory usage
|
|
38
|
+
*/
|
|
39
|
+
export function buildMemoryCheckCommand() {
|
|
40
|
+
// Returns: total, used, free, available in MB and percentage
|
|
41
|
+
return `free -m | awk 'NR==2{printf "{\\"total\\":%s,\\"used\\":%s,\\"free\\":%s,\\"percent\\":%.2f}", $2,$3,$4,$3*100/$2}'`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Build command to check disk usage
|
|
46
|
+
*/
|
|
47
|
+
export function buildDiskCheckCommand(mountPoint = '/') {
|
|
48
|
+
// Returns JSON with disk usage for specific mount point or all
|
|
49
|
+
if (mountPoint === 'all') {
|
|
50
|
+
return `df -h | awk 'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}\\n", $6,$2,$3,$4,$5}'`;
|
|
51
|
+
}
|
|
52
|
+
return `df -h "${mountPoint}" | awk 'NR>1 {gsub(/%/,"",$5); printf "{\\"mount\\":\\"%s\\",\\"size\\":\\"%s\\",\\"used\\":\\"%s\\",\\"avail\\":\\"%s\\",\\"percent\\":%s}", $6,$2,$3,$4,$5}'`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Build command to check network statistics
|
|
57
|
+
*/
|
|
58
|
+
export function buildNetworkCheckCommand() {
|
|
59
|
+
// Get basic network stats (RX/TX bytes)
|
|
60
|
+
return `cat /proc/net/dev | awk 'NR>2 {printf "{\\"interface\\":\\"%s\\",\\"rx_bytes\\":%s,\\"tx_bytes\\":%s}\\n", $1,$2,$10}' | grep -v "lo:"`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Build command to check load average
|
|
65
|
+
*/
|
|
66
|
+
export function buildLoadAverageCommand() {
|
|
67
|
+
return `uptime | awk -F'load average:' '{print $2}' | sed 's/^[ \\t]*//'`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Build command to check system uptime
|
|
72
|
+
*/
|
|
73
|
+
export function buildUptimeCommand() {
|
|
74
|
+
return `uptime -p 2>/dev/null || uptime | awk '{print $3,$4}' | sed 's/,//'`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Parse CPU usage output
|
|
79
|
+
*/
|
|
80
|
+
export function parseCPUUsage(output) {
|
|
81
|
+
const usage = parseFloat(output.trim());
|
|
82
|
+
return {
|
|
83
|
+
usage: usage.toFixed(2),
|
|
84
|
+
percent: usage,
|
|
85
|
+
status: usage > 90 ? HEALTH_STATUS.CRITICAL : usage > 70 ? HEALTH_STATUS.WARNING : HEALTH_STATUS.HEALTHY
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Parse memory usage output
|
|
91
|
+
*/
|
|
92
|
+
export function parseMemoryUsage(output) {
|
|
93
|
+
try {
|
|
94
|
+
const mem = JSON.parse(output.trim());
|
|
95
|
+
return {
|
|
96
|
+
total_mb: mem.total,
|
|
97
|
+
used_mb: mem.used,
|
|
98
|
+
free_mb: mem.free,
|
|
99
|
+
percent: parseFloat(mem.percent),
|
|
100
|
+
status: mem.percent > 90 ? HEALTH_STATUS.CRITICAL : mem.percent > 80 ? HEALTH_STATUS.WARNING : HEALTH_STATUS.HEALTHY
|
|
101
|
+
};
|
|
102
|
+
} catch (error) {
|
|
103
|
+
logger.warn('Failed to parse memory output', { error: error.message });
|
|
104
|
+
return { status: HEALTH_STATUS.UNKNOWN };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Parse disk usage output
|
|
110
|
+
*/
|
|
111
|
+
export function parseDiskUsage(output) {
|
|
112
|
+
const lines = output.trim().split('\n').filter(l => l);
|
|
113
|
+
const disks = [];
|
|
114
|
+
|
|
115
|
+
for (const line of lines) {
|
|
116
|
+
try {
|
|
117
|
+
const disk = JSON.parse(line);
|
|
118
|
+
disk.status = disk.percent > 90 ? HEALTH_STATUS.CRITICAL : disk.percent > 80 ? HEALTH_STATUS.WARNING : HEALTH_STATUS.HEALTHY;
|
|
119
|
+
disks.push(disk);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
logger.warn('Failed to parse disk line', { line, error: error.message });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return disks;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Parse network statistics
|
|
130
|
+
*/
|
|
131
|
+
export function parseNetworkStats(output) {
|
|
132
|
+
const lines = output.trim().split('\n').filter(l => l);
|
|
133
|
+
const interfaces = [];
|
|
134
|
+
|
|
135
|
+
for (const line of lines) {
|
|
136
|
+
try {
|
|
137
|
+
const iface = JSON.parse(line);
|
|
138
|
+
// Convert bytes to MB
|
|
139
|
+
iface.rx_mb = (iface.rx_bytes / 1024 / 1024).toFixed(2);
|
|
140
|
+
iface.tx_mb = (iface.tx_bytes / 1024 / 1024).toFixed(2);
|
|
141
|
+
interfaces.push(iface);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
logger.warn('Failed to parse network line', { line, error: error.message });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return interfaces;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Determine overall health status
|
|
152
|
+
*/
|
|
153
|
+
export function determineOverallHealth(cpu, memory, disks) {
|
|
154
|
+
const statuses = [cpu.status, memory.status, ...disks.map(d => d.status)];
|
|
155
|
+
|
|
156
|
+
if (statuses.includes(HEALTH_STATUS.CRITICAL)) {
|
|
157
|
+
return HEALTH_STATUS.CRITICAL;
|
|
158
|
+
}
|
|
159
|
+
if (statuses.includes(HEALTH_STATUS.WARNING)) {
|
|
160
|
+
return HEALTH_STATUS.WARNING;
|
|
161
|
+
}
|
|
162
|
+
if (statuses.includes(HEALTH_STATUS.UNKNOWN)) {
|
|
163
|
+
return HEALTH_STATUS.UNKNOWN;
|
|
164
|
+
}
|
|
165
|
+
return HEALTH_STATUS.HEALTHY;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Build command to check service status (systemd or sysv)
|
|
170
|
+
*/
|
|
171
|
+
export function buildServiceStatusCommand(serviceName) {
|
|
172
|
+
// Try systemd first, fallback to sysv
|
|
173
|
+
return `
|
|
174
|
+
if command -v systemctl >/dev/null 2>&1; then
|
|
175
|
+
systemctl is-active ${serviceName} 2>/dev/null >/dev/null && echo "ACTIVE" || echo "INACTIVE"
|
|
176
|
+
systemctl is-enabled ${serviceName} 2>/dev/null >/dev/null && echo "ENABLED" || echo "DISABLED"
|
|
177
|
+
systemctl status ${serviceName} 2>/dev/null | grep "Main PID" | awk '{print $3}' | cut -d'(' -f1
|
|
178
|
+
systemctl status ${serviceName} 2>/dev/null | grep "Active:" | sed 's/.*Active: //' | awk '{print $1,$2,$3}'
|
|
179
|
+
elif command -v service >/dev/null 2>&1; then
|
|
180
|
+
service ${serviceName} status >/dev/null 2>&1 && echo "ACTIVE" || echo "INACTIVE"
|
|
181
|
+
echo "UNKNOWN"
|
|
182
|
+
pgrep -f ${serviceName} | head -1 || echo ""
|
|
183
|
+
echo "sysv"
|
|
184
|
+
else
|
|
185
|
+
echo "UNKNOWN"
|
|
186
|
+
echo "UNKNOWN"
|
|
187
|
+
echo ""
|
|
188
|
+
echo "no-init-system"
|
|
189
|
+
fi
|
|
190
|
+
`.trim();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Parse service status output
|
|
195
|
+
*/
|
|
196
|
+
export function parseServiceStatus(output, serviceName) {
|
|
197
|
+
const lines = output.trim().split('\n');
|
|
198
|
+
const [status, enabled, pid, details] = lines;
|
|
199
|
+
|
|
200
|
+
return {
|
|
201
|
+
name: serviceName,
|
|
202
|
+
status: status === 'ACTIVE' ? 'running' : 'stopped',
|
|
203
|
+
enabled: enabled === 'ENABLED' ? 'yes' : enabled === 'DISABLED' ? 'no' : 'unknown',
|
|
204
|
+
pid: pid && pid !== '' ? parseInt(pid) : null,
|
|
205
|
+
details: details || 'unknown',
|
|
206
|
+
health: status === 'ACTIVE' ? HEALTH_STATUS.HEALTHY : HEALTH_STATUS.CRITICAL
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Build command to list running processes
|
|
212
|
+
*/
|
|
213
|
+
export function buildProcessListCommand(options = {}) {
|
|
214
|
+
const {
|
|
215
|
+
sortBy = 'cpu', // cpu, memory, pid
|
|
216
|
+
limit = 20,
|
|
217
|
+
filter = null
|
|
218
|
+
} = options;
|
|
219
|
+
|
|
220
|
+
let sortFlag = sortBy === 'memory' ? '-m' : '-c'; // -c for CPU, -m for memory
|
|
221
|
+
let command = `ps aux --sort=${sortFlag === '-c' ? '-pcpu' : '-pmem'} | head -n ${limit + 1}`;
|
|
222
|
+
|
|
223
|
+
if (filter) {
|
|
224
|
+
command += ` | grep -i "${filter}"`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Format output as JSON-like structure
|
|
228
|
+
command += ` | awk 'NR>1 {printf "{\\"user\\":\\"%s\\",\\"pid\\":%s,\\"cpu\\":%.1f,\\"mem\\":%.1f,\\"vsz\\":%s,\\"rss\\":%s,\\"stat\\":\\"%s\\",\\"start\\":\\"%s\\",\\"time\\":\\"%s\\",\\"command\\":\\"%s\\"}\\n", $1,$2,$3,$4,$5,$6,$8,$9,$10,substr($0,index($0,$11))}'`;
|
|
229
|
+
|
|
230
|
+
return command;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Parse process list output
|
|
235
|
+
*/
|
|
236
|
+
export function parseProcessList(output) {
|
|
237
|
+
const lines = output.trim().split('\n').filter(l => l);
|
|
238
|
+
const processes = [];
|
|
239
|
+
|
|
240
|
+
for (const line of lines) {
|
|
241
|
+
try {
|
|
242
|
+
const proc = JSON.parse(line);
|
|
243
|
+
processes.push(proc);
|
|
244
|
+
} catch (error) {
|
|
245
|
+
logger.warn('Failed to parse process line', { line, error: error.message });
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return processes;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Build command to kill a process
|
|
254
|
+
*/
|
|
255
|
+
export function buildKillProcessCommand(pid, signal = 'TERM') {
|
|
256
|
+
// Validate PID is numeric
|
|
257
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
258
|
+
throw new Error(`Invalid PID: ${pid}`);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const validSignals = ['TERM', 'KILL', 'HUP', 'INT', 'QUIT'];
|
|
262
|
+
if (!validSignals.includes(signal)) {
|
|
263
|
+
throw new Error(`Invalid signal: ${signal}. Valid signals: ${validSignals.join(', ')}`);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return `kill -${signal} ${pid}`;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Build command to get process info
|
|
271
|
+
*/
|
|
272
|
+
export function buildProcessInfoCommand(pid) {
|
|
273
|
+
return `ps -p ${pid} -o user,pid,pcpu,pmem,vsz,rss,stat,start,time,cmd --no-headers | awk '{printf "{\\"user\\":\\"%s\\",\\"pid\\":%s,\\"cpu\\":%.1f,\\"mem\\":%.1f,\\"vsz\\":%s,\\"rss\\":%s,\\"stat\\":\\"%s\\",\\"start\\":\\"%s\\",\\"time\\":\\"%s\\",\\"command\\":\\"%s\\"}", $1,$2,$3,$4,$5,$6,$7,$8,$9,substr($0,index($0,$10))}'`;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Create alert configuration
|
|
278
|
+
*/
|
|
279
|
+
export function createAlertConfig(thresholds) {
|
|
280
|
+
const defaults = {
|
|
281
|
+
cpu: 80,
|
|
282
|
+
memory: 90,
|
|
283
|
+
disk: 85,
|
|
284
|
+
enabled: true
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
return {
|
|
288
|
+
...defaults,
|
|
289
|
+
...thresholds,
|
|
290
|
+
created_at: new Date().toISOString()
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Build command to save alert config
|
|
296
|
+
*/
|
|
297
|
+
export function buildSaveAlertConfigCommand(config, configPath = '/etc/ssh-manager-alerts.json') {
|
|
298
|
+
const jsonData = JSON.stringify(config, null, 2);
|
|
299
|
+
const escapedJson = jsonData.replace(/'/g, "'\\''");
|
|
300
|
+
return `echo '${escapedJson}' > "${configPath}"`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Build command to load alert config
|
|
305
|
+
*/
|
|
306
|
+
export function buildLoadAlertConfigCommand(configPath = '/etc/ssh-manager-alerts.json') {
|
|
307
|
+
return `cat "${configPath}" 2>/dev/null || echo '{}'`;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Check if thresholds are exceeded
|
|
312
|
+
*/
|
|
313
|
+
export function checkAlertThresholds(metrics, thresholds) {
|
|
314
|
+
const alerts = [];
|
|
315
|
+
|
|
316
|
+
if (thresholds.cpu && metrics.cpu && metrics.cpu.percent > thresholds.cpu) {
|
|
317
|
+
alerts.push({
|
|
318
|
+
type: 'cpu',
|
|
319
|
+
severity: 'warning',
|
|
320
|
+
message: `CPU usage (${metrics.cpu.percent}%) exceeds threshold (${thresholds.cpu}%)`,
|
|
321
|
+
value: metrics.cpu.percent,
|
|
322
|
+
threshold: thresholds.cpu
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (thresholds.memory && metrics.memory && metrics.memory.percent > thresholds.memory) {
|
|
327
|
+
alerts.push({
|
|
328
|
+
type: 'memory',
|
|
329
|
+
severity: 'warning',
|
|
330
|
+
message: `Memory usage (${metrics.memory.percent}%) exceeds threshold (${thresholds.memory}%)`,
|
|
331
|
+
value: metrics.memory.percent,
|
|
332
|
+
threshold: thresholds.memory
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (thresholds.disk && metrics.disks) {
|
|
337
|
+
for (const disk of metrics.disks) {
|
|
338
|
+
if (disk.percent > thresholds.disk) {
|
|
339
|
+
alerts.push({
|
|
340
|
+
type: 'disk',
|
|
341
|
+
severity: 'warning',
|
|
342
|
+
message: `Disk usage on ${disk.mount} (${disk.percent}%) exceeds threshold (${thresholds.disk}%)`,
|
|
343
|
+
mount: disk.mount,
|
|
344
|
+
value: disk.percent,
|
|
345
|
+
threshold: thresholds.disk
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return alerts;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Build comprehensive health check command
|
|
356
|
+
*/
|
|
357
|
+
export function buildComprehensiveHealthCheckCommand() {
|
|
358
|
+
return `
|
|
359
|
+
echo "=== CPU ==="
|
|
360
|
+
${buildCPUCheckCommand()}
|
|
361
|
+
echo "=== MEMORY ==="
|
|
362
|
+
${buildMemoryCheckCommand()}
|
|
363
|
+
echo "=== DISK ==="
|
|
364
|
+
${buildDiskCheckCommand('all')}
|
|
365
|
+
echo "=== LOAD ==="
|
|
366
|
+
${buildLoadAverageCommand()}
|
|
367
|
+
echo "=== UPTIME ==="
|
|
368
|
+
${buildUptimeCommand()}
|
|
369
|
+
echo "=== NETWORK ==="
|
|
370
|
+
${buildNetworkCheckCommand()}
|
|
371
|
+
`.trim();
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Parse comprehensive health check output
|
|
376
|
+
*/
|
|
377
|
+
export function parseComprehensiveHealthCheck(output) {
|
|
378
|
+
const sections = output.split('=== ').filter(s => s);
|
|
379
|
+
const result = {};
|
|
380
|
+
|
|
381
|
+
for (const section of sections) {
|
|
382
|
+
const [name, ...content] = section.split('\n');
|
|
383
|
+
const data = content.join('\n').trim();
|
|
384
|
+
|
|
385
|
+
switch (name.toLowerCase().trim()) {
|
|
386
|
+
case 'cpu ===':
|
|
387
|
+
result.cpu = parseCPUUsage(data);
|
|
388
|
+
break;
|
|
389
|
+
case 'memory ===':
|
|
390
|
+
result.memory = parseMemoryUsage(data);
|
|
391
|
+
break;
|
|
392
|
+
case 'disk ===':
|
|
393
|
+
result.disks = parseDiskUsage(data);
|
|
394
|
+
break;
|
|
395
|
+
case 'load ===':
|
|
396
|
+
result.load_average = data;
|
|
397
|
+
break;
|
|
398
|
+
case 'uptime ===':
|
|
399
|
+
result.uptime = data;
|
|
400
|
+
break;
|
|
401
|
+
case 'network ===':
|
|
402
|
+
result.network = parseNetworkStats(data);
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Determine overall health
|
|
408
|
+
if (result.cpu && result.memory && result.disks) {
|
|
409
|
+
result.overall_status = determineOverallHealth(result.cpu, result.memory, result.disks);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
return result;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Get common service names for detection
|
|
417
|
+
*/
|
|
418
|
+
export function getCommonServices() {
|
|
419
|
+
return Object.keys(COMMON_SERVICES);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Resolve service name (handle both systemd and sysv names)
|
|
424
|
+
*/
|
|
425
|
+
export function resolveServiceName(shortName) {
|
|
426
|
+
const service = COMMON_SERVICES[shortName.toLowerCase()];
|
|
427
|
+
return service ? service.systemd : shortName;
|
|
428
|
+
}
|