2023-09-30 16:01:43 +00:00
|
|
|
import dgram from 'dgram';
|
2023-10-03 12:45:00 +00:00
|
|
|
import type { ServerStatusInfo } from '../../types';
|
|
|
|
import { createSubscribeInitializer, subscribeEventBus } from '../ws/shared';
|
|
|
|
|
|
|
|
const serverMap: Record<
|
|
|
|
string, // workspaceId
|
|
|
|
Record<
|
|
|
|
string, // nodeName or hostname
|
|
|
|
ServerStatusInfo
|
|
|
|
>
|
|
|
|
> = {};
|
|
|
|
|
|
|
|
createSubscribeInitializer('onServerStatusUpdate', (workspaceId) => {
|
|
|
|
return serverMap[workspaceId];
|
|
|
|
});
|
2023-09-30 16:01:43 +00:00
|
|
|
|
|
|
|
export function initUdpServer(port: number) {
|
|
|
|
const server = dgram.createSocket('udp4');
|
|
|
|
|
|
|
|
server.on('error', (err) => {
|
|
|
|
console.log(`Init error:\n${err.stack}`);
|
|
|
|
server.close();
|
|
|
|
});
|
|
|
|
|
|
|
|
server.on('message', (msg, rinfo) => {
|
|
|
|
try {
|
|
|
|
const raw = String(msg);
|
|
|
|
const json = JSON.parse(String(msg));
|
2023-10-03 12:45:00 +00:00
|
|
|
const { workspaceId, name, hostname, timeout, payload } = json;
|
2023-09-30 16:01:43 +00:00
|
|
|
|
|
|
|
if (!workspaceId || !name || !hostname) {
|
|
|
|
console.warn(
|
|
|
|
'[UDP] lost some necessary params, request will be ignore',
|
|
|
|
json
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
console.log('recevice tianji report:', raw, 'info', rinfo);
|
2023-10-03 12:45:00 +00:00
|
|
|
|
|
|
|
if (!serverMap[workspaceId]) {
|
|
|
|
serverMap[workspaceId] = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
serverMap[workspaceId][name || hostname] = {
|
|
|
|
workspaceId,
|
|
|
|
name,
|
|
|
|
hostname,
|
|
|
|
timeout,
|
|
|
|
updatedAt: Date.now(),
|
|
|
|
payload,
|
|
|
|
};
|
|
|
|
|
|
|
|
subscribeEventBus.emit(
|
|
|
|
'onServerStatusUpdate',
|
|
|
|
workspaceId,
|
|
|
|
serverMap[workspaceId]
|
|
|
|
);
|
2023-09-30 16:01:43 +00:00
|
|
|
} catch (err) {}
|
|
|
|
});
|
|
|
|
|
|
|
|
server.on('listening', () => {
|
|
|
|
const address = server.address();
|
|
|
|
console.log(`UDP Server is listening: ${address.address}:${address.port}`);
|
|
|
|
});
|
|
|
|
|
|
|
|
server.bind(port);
|
|
|
|
}
|