File size: 3,491 Bytes
03b405b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
const os = require('os');
const fs = require('fs');
const { getDb } = require('../config/db');
const { createLogger } = require('./logger');

const log = createLogger('SystemMonitor');

let isMonitoring = false;
let monitorInterval = null;

// CPU calculation helper
let lastCpuUsage = { idle: 0, total: 0 };
const getCpuUsage = () => {
  const cpus = os.cpus();
  let user = 0;
  let nice = 0;
  let sys = 0;
  let idle = 0;
  let irq = 0;

  for (const cpu of cpus) {
    user += cpu.times.user;
    nice += cpu.times.nice;
    sys += cpu.times.sys;
    idle += cpu.times.idle;
    irq += cpu.times.irq;
  }

  const total = user + nice + sys + idle + irq;
  const diffIdle = idle - lastCpuUsage.idle;
  const diffTotal = total - lastCpuUsage.total;

  lastCpuUsage = { idle, total };

  if (diffTotal === 0) return 0;
  return Math.round((1 - diffIdle / diffTotal) * 100);
};

// Storage helper
const getStorageUsage = () => {
  try {
    if (fs.statfsSync) {
      const stats = fs.statfsSync(process.cwd());
      const total = stats.bsize * stats.blocks;
      const free = stats.bsize * stats.bfree;
      const used = total - free;
      return {
        usedBytes: used,
        totalBytes: total,
        percent: Math.round((used / total) * 100)
      };
    }
  } catch { /* fallback below */ }
  
  return {
    usedBytes: 10 * 1024 * 1024 * 1024,
    totalBytes: 100 * 1024 * 1024 * 1024,
    percent: 10
  };
};

/**
 * Gather a single system snapshot for the dashboard API
 */
function getSystemSnapshot() {
  const cpu = getCpuUsage();
  const freeMem = os.freemem();
  const totalMem = os.totalmem();
  const usedMem = totalMem - freeMem;
  const memPercent = Math.round((usedMem / totalMem) * 100);
  const storage = getStorageUsage();

  const db = getDb();
  const activeJobs = db.prepare("SELECT COUNT(*) as count FROM jobs WHERE status NOT IN ('completed', 'failed')").get().count;
  const totalJobs = db.prepare("SELECT COUNT(*) as count FROM jobs").get().count;
  const failedJobs = db.prepare("SELECT COUNT(*) as count FROM jobs WHERE status = 'failed'").get().count;
  const doneJobs = db.prepare("SELECT COUNT(*) as count FROM jobs WHERE status = 'completed'").get().count;

  return {
    type: 'sysinfo',
    cpu: { usage: cpu, cores: os.cpus().length },
    memory: { used: usedMem, total: totalMem, percent: memPercent },
    storage: { used: storage.usedBytes, total: storage.totalBytes, percent: storage.percent },
    queue: { active: activeJobs, total: totalJobs, failed: failedJobs, completed: doneJobs },
    uptime: os.uptime(),
    timestamp: Date.now()
  };
}

/**
 * Start background system utilization monitor (polling via setInterval)
 */
function startSystemMonitoring(broadcastFn) {
  if (isMonitoring) return;
  isMonitoring = true;
  
  log.info('System utilization monitor started.');
  getCpuUsage(); // Pre-fill CPU stats

  monitorInterval = setInterval(() => {
    try {
      const stats = getSystemSnapshot();
      if (typeof broadcastFn === 'function') {
        broadcastFn(stats);
      }
    } catch (err) {
      log.error({ error: err.message }, 'Error gathering system stats');
    }
  }, 5000);
}

/**
 * Stop system monitoring loop
 */
function stopSystemMonitoring() {
  isMonitoring = false;
  if (monitorInterval) {
    clearInterval(monitorInterval);
    monitorInterval = null;
  }
  log.info('System utilization monitor stopped.');
}

module.exports = { getSystemSnapshot, startSystemMonitoring, stopSystemMonitoring };