const fastify = require('fastify')({ logger: true }); const { spawn } = require('child_process'); let OMNITOOL_READY = false; let ALREADY_STARTING = false; let MANAGEMENT_SERVER_PORT = 7860; let SERVER_HOST = '0.0.0.0'; console.log(`************ Management Server ************`); let omnitoolLogs = []; async function startOmnitoolServer() { if (ALREADY_STARTING) return; ALREADY_STARTING = true; console.log('Starting Omnitool Server...'); return new Promise((resolve, reject) => { const omnitoolStartProcess = spawn('./omnitool_start.sh'); omnitoolStartProcess.stdout.on('data', (data) => { omnitoolLogs.push(data.toString()); console.log(`omnitool stdout: ${data}`); if (data.toString().includes(`Server has started and is ready to accept connections`)) { OMNITOOL_READY = true; console.log('Omnitool server started successfully'); resolve(); } }); omnitoolStartProcess.stderr.on('data', (data) => { console.error(`omnitool stderr: ${data}`); }); omnitoolStartProcess.on('close', (code) => { console.log(`Omnitool server process exited with code ${code}`); if (!OMNITOOL_READY) { ALREADY_STARTING = false; reject(`Omnitool server did not start within the timeout period.`); } }); }); } fastify.get('/', async (request, reply) => { const localUrl = request.headers['host']; if (!OMNITOOL_READY) { let htmlContent = ` Proxy Server
`; reply.type('text/html').send(htmlContent); } else { let htmlContent = ` Proxy Server
`; reply.type('text/html').send(htmlContent); } }); fastify.get('/omnitool-logs', async (request, reply) => { reply.send({ logs: omnitoolLogs, ready: OMNITOOL_READY }); }); fastify.get('/start-omnitool-server', async (request, reply) => { if (!OMNITOOL_READY) { if (ALREADY_STARTING) { return { message: "Omnitool server already starting" }; } try { await startOmnitoolServer(); reply.send({ message: "Omnitool server started successfully" }); } catch (error) { console.error(error); reply.send({ message: `Error starting Omnitool server: ${error}` }); } } else { reply.send({ message: "Omnitool server already running" }); } }); const start = async () => { try { await fastify.listen({ port: MANAGEMENT_SERVER_PORT, host: SERVER_HOST }); console.log(`Server is listening on port ${MANAGEMENT_SERVER_PORT}`); } catch (err) { console.error(`Error starting server: ${err}`); process.exit(1); } }; start();