From 9b8bb3437812159a11b259006701f29d94e3de78 Mon Sep 17 00:00:00 2001 From: moonrailgun Date: Sun, 1 Oct 2023 00:01:43 +0800 Subject: [PATCH] feat: add basic framework for udp reporter --- reporter/cmd/reporter/main.go | 84 ++++++++++++++++++++++++++++------- src/server/main.ts | 3 ++ src/server/udp/server.ts | 34 ++++++++++++++ 3 files changed, 104 insertions(+), 17 deletions(-) create mode 100644 src/server/udp/server.ts diff --git a/reporter/cmd/reporter/main.go b/reporter/cmd/reporter/main.go index 55f530f..50e2dde 100644 --- a/reporter/cmd/reporter/main.go +++ b/reporter/cmd/reporter/main.go @@ -1,25 +1,34 @@ package main import ( - "fmt" - "flag" - "net/url" - "log" - - socketio "github.com/googollee/go-socket.io" + "encoding/json" + "flag" + "fmt" + "log" + "net" + "net/url" + "os" ) var ( - URL = flag.String("url", "", "The http url of tianji, for example: https://tianji.msgbyte.com") - WORKSPACE_ID = flag.String("workspace", "", "The workspace id for tianji, this should be a uuid") - INTERVAL = flag.Float64("interval", 2.0, "Input the INTERVAL") - isVnstat = flag.Bool("vnstat", false, "Use vnstat for traffic statistics, linux only") + Url = flag.String("url", "", "The http url of tianji, for example: https://tianji.msgbyte.com") + WorkspaceId = flag.String("workspace", "", "The workspace id for tianji, this should be a uuid") + Name = flag.String("name", "", "The identification name for this machine") + Interval = flag.Float64("interval", 5.0, "Input the INTERVAL") + IsVnstat = flag.Bool("vnstat", false, "Use vnstat for traffic statistics, linux only") ) +type ReportData struct { + WorkspaceId string `json:"workspaceId"` + Name string `json:"name"` + Hostname string `json:"hostname"` + Payload any `json:"payload"` +} + func main() { flag.Parse() - parsedURL, err := url.Parse(*URL) + parsedURL, err := url.Parse(*Url) if err != nil { log.Fatal("Invalid URL:", err) @@ -29,14 +38,55 @@ func main() { log.Fatal("Invalid URL: Missing scheme") } - if *WORKSPACE_ID == "" { + if *WorkspaceId == "" { log.Fatal("WORKSPACE_ID must not be blank!") } - client, _ := socketio.NewClient(*URL, nil) + hostname, _ := os.Hostname() + var name string + if *Name != "" { + name = *Name + } else { + name = hostname + } - client.Connect() - client.Emit("notice", "hello") - - fmt.Println("Hello, World!", *URL) + sendUDPTestPack(*parsedURL, ReportData{ + WorkspaceId: *WorkspaceId, + Name: name, + Hostname: hostname, + }) +} + +func sendUDPTestPack(url url.URL, payload ReportData) { + // parse target url + addr, err := net.ResolveUDPAddr("udp", url.Hostname()+":"+url.Port()) + if err != nil { + fmt.Println("Error resolving address:", err) + return + } + + // create UDP connection + conn, err := net.DialUDP("udp", nil, addr) + if err != nil { + fmt.Println("Error creating connection:", err) + return + } + defer conn.Close() + + // serialized message + jsonData, err := json.Marshal(payload) + fmt.Printf("[Report] %s\n", jsonData) + if err != nil { + fmt.Println("Error encoding JSON:", err) + return + } + + // Send message + _, err = conn.Write(jsonData) + if err != nil { + fmt.Println("Error sending message:", err) + return + } + + fmt.Println("Message sent successfully!") } diff --git a/src/server/main.ts b/src/server/main.ts index 875b465..4e1e23f 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -12,11 +12,14 @@ import { workspaceRouter } from './router/workspace'; import { telemetryRouter } from './router/telemetry'; import { initSocketio } from './ws'; import { trpcExpressMiddleware } from './trpc'; +import { initUdpServer } from './udp/server'; const port = Number(process.env.PORT || 12345); const app = express(); +initUdpServer(port); + initSocketio(app); app.use(compression()); diff --git a/src/server/udp/server.ts b/src/server/udp/server.ts new file mode 100644 index 0000000..904dc3e --- /dev/null +++ b/src/server/udp/server.ts @@ -0,0 +1,34 @@ +import dgram from 'dgram'; + +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)); + const { workspaceId, name, hostname, payload } = json; + + if (!workspaceId || !name || !hostname) { + console.warn( + '[UDP] lost some necessary params, request will be ignore', + json + ); + } + + console.log('recevice tianji report:', raw, 'info', rinfo); + } catch (err) {} + }); + + server.on('listening', () => { + const address = server.address(); + console.log(`UDP Server is listening: ${address.address}:${address.port}`); + }); + + server.bind(port); +}