-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard-server.js
More file actions
executable file
·340 lines (308 loc) · 10 KB
/
dashboard-server.js
File metadata and controls
executable file
·340 lines (308 loc) · 10 KB
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/env node
// Simple dashboard server for VR Flight Tracker
// Serves a web dashboard showing server stats and logs
const express = require('express');
const { readFile } = require('fs');
const { createServer } = require('http');
const path = require('path');
const { execSync } = require('child_process');
// Get directory - works when run directly as script
const scriptDir = (() => {
try {
// Try to use __dirname if available (CommonJS)
if (typeof __dirname !== 'undefined') {
return __dirname;
}
} catch {}
// Fallback: use the script's directory
return path.dirname(process.argv[1] || '.');
})();
const app = express();
const server = createServer(app);
const DASHBOARD_PORT = 8081;
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(scriptDir, 'dashboard')));
const BACKEND_URL = 'http://localhost:8080';
// Proxy debug mode state
app.get('/api/debug', async (_req, res) => {
try {
const response = await fetch(`${BACKEND_URL}/api/debug`);
if (!response.ok) {
throw new Error(`Backend responded with ${response.status}`);
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Debug state fetch failed:', error);
res.status(502).json({ success: false, error: 'Unable to reach backend debug endpoint' });
}
});
app.post('/api/debug', async (req, res) => {
try {
const response = await fetch(`${BACKEND_URL}/api/debug`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(req.body || {}),
});
if (!response.ok) {
throw new Error(`Backend responded with ${response.status}`);
}
const data = await response.json();
res.json(data);
} catch (error) {
console.error('Debug mode toggle failed:', error);
res.status(502).json({ success: false, error: 'Unable to toggle debug mode on backend' });
}
});
// Serve log files
app.get('/api/logs/server', (req, res) => {
const logPath = path.join(scriptDir, 'logs', 'server.log');
readFile(logPath, 'utf8', (err, data) => {
if (err) {
return res.json({ error: 'Log file not found', lines: [] });
}
const lines = data.split('\n').slice(-100); // Last 100 lines
res.json({ lines });
});
});
app.get('/api/logs/client', (req, res) => {
const logPath = path.join(scriptDir, 'logs', 'client.log');
readFile(logPath, 'utf8', (err, data) => {
if (err) {
return res.json({ error: 'Log file not found', lines: [] });
}
const lines = data.split('\n').slice(-100); // Last 100 lines
res.json({ lines });
});
});
// Get server stats
app.get('/api/stats', async (req, res) => {
try {
// Check if main server is running
let cacheStats = null;
let openskyStatus = {
mode: 'unknown',
details: null,
};
try {
const http = require('http');
const response = await new Promise((resolve, reject) => {
const req = http.get('http://localhost:8080/api/cache/stats', (res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch (err) {
console.warn('Failed to parse cache stats response', err);
resolve(null);
}
});
});
req.on('error', () => resolve(null));
req.setTimeout(1000, () => {
req.destroy();
resolve(null);
});
});
if (response && response.data) {
cacheStats = response.data.cache || null;
if (response.data.flight) {
openskyStatus = {
mode: response.data.flight.openskyAuthentication || 'unknown',
details: response.data.flight.openskyAuthDetails || null,
};
}
} else {
cacheStats = response;
}
} catch {
cacheStats = null;
}
// Check ports
const checkPort = (port) => {
try {
const result = execSync(`lsof -ti:${port}`, { encoding: 'utf8', stdio: 'pipe' });
return result.trim().length > 0;
} catch {
return false;
}
};
const stats = {
server: {
running: checkPort(8080),
port: 8080,
cache: cacheStats || null,
},
client: {
running: checkPort(3000) || checkPort(5173),
port: checkPort(3000) ? 3000 : checkPort(5173) ? 5173 : null,
},
opensky: openskyStatus,
dashboard: {
running: true,
port: DASHBOARD_PORT,
},
timestamp: new Date().toISOString(),
};
res.json(stats);
} catch (error) {
res.json({
server: { running: false },
client: { running: false },
dashboard: { running: true, port: DASHBOARD_PORT },
error: error.message,
timestamp: new Date().toISOString(),
});
}
});
// Stop all servers endpoint
app.post('/api/stop', (req, res) => {
console.log('🛑 Stop request received');
// Send response immediately to ensure client gets it
res.json({
success: true,
message: 'Stopping all servers...',
killedCount: 0,
});
// Use setImmediate to ensure response is sent before we start killing processes
setImmediate(() => {
try {
const fs = require('fs');
const pidFile = path.join(scriptDir, '.vr-flight-tracker.pids');
// Function to kill a PID and all its children
const killProcessTree = (pid) => {
try {
// Kill all children first
try {
const children = execSync(`pgrep -P ${pid}`, {
encoding: 'utf8',
stdio: 'pipe',
}).trim();
if (children) {
children.split('\n').forEach((childPid) => {
killProcessTree(childPid.trim());
});
}
} catch (e) {
// No children or already dead
}
// Kill the process itself
try {
execSync(`kill -9 ${pid}`, { stdio: 'pipe' });
console.log(`✅ Killed process ${pid} and its children`);
return 1;
} catch (e) {
console.log(`⚠️ Could not kill process ${pid}: ${e.message}`);
return 0;
}
} catch (e) {
return 0;
}
};
// Function to kill processes by port
const killByPort = (port, excludeSelf = false) => {
try {
const result = execSync(`lsof -ti:${port}`, { encoding: 'utf8', stdio: 'pipe' });
const pids = result.trim();
if (pids) {
const pidArray = pids.split('\n').filter((pid) => {
const pidNum = pid.trim();
if (excludeSelf && pidNum === String(process.pid)) {
return false;
}
return pidNum;
});
let count = 0;
pidArray.forEach((pid) => {
count += killProcessTree(pid.trim());
});
return count;
}
} catch (e) {
console.log(`ℹ️ No process found on port ${port}`);
}
return 0;
};
// Function to kill processes by name pattern (kills entire process tree)
const killByName = (pattern, excludeSelf = false) => {
try {
const result = execSync(`pgrep -f "${pattern}"`, { encoding: 'utf8', stdio: 'pipe' });
const pids = result.trim();
if (pids) {
const pidArray = pids.split('\n').filter((pid) => {
const pidNum = pid.trim();
if (excludeSelf && pidNum === String(process.pid)) {
return false;
}
return pidNum;
});
let count = 0;
pidArray.forEach((pid) => {
count += killProcessTree(pid.trim());
});
return count;
}
} catch (e) {
console.log(`ℹ️ No process found matching "${pattern}"`);
}
return 0;
};
console.log('🛑 Stopping all servers...');
let killedCount = 0;
// Try to read PIDs from file first (more reliable)
try {
if (fs.existsSync(pidFile)) {
const pidData = fs.readFileSync(pidFile, 'utf8');
const lines = pidData.split('\n');
lines.forEach((line) => {
const match = line.match(/(SERVER|CLIENT|DASHBOARD)_PID=(\d+)/);
if (match) {
const pid = match[2];
console.log(`Killing ${match[1]} process ${pid} from PID file...`);
killedCount += killProcessTree(pid);
}
});
}
} catch (e) {
console.log('⚠️ Could not read PID file, using fallback methods');
}
// Fallback: Kill by port
killedCount += killByPort(8080); // Backend server
killedCount += killByPort(3000); // Frontend (if using port 3000)
killedCount += killByPort(5173); // Frontend (Vite default)
// Also kill by process name patterns (kills entire trees)
killedCount += killByName('tsx watch src/index.ts'); // Backend dev server
killedCount += killByName('vite'); // Frontend dev server
killedCount += killByName('npm run dev'); // npm processes
console.log(`✅ Stopped ${killedCount} process(es)`);
// Clean up PID file
try {
if (fs.existsSync(pidFile)) {
fs.unlinkSync(pidFile);
}
} catch (e) {
// Ignore
}
// Kill dashboard server last, after a delay to ensure response was sent
setTimeout(() => {
console.log('🛑 Shutting down dashboard server...');
killByPort(8081, true);
killByName('node.*dashboard-server', true);
setTimeout(() => {
process.exit(0);
}, 200);
}, 1000);
} catch (error) {
console.error('❌ Error stopping servers:', error);
setTimeout(() => {
process.exit(1);
}, 500);
}
});
});
server.listen(DASHBOARD_PORT, () => {
console.log(`📊 Dashboard server running on http://localhost:${DASHBOARD_PORT}`);
});