-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_handler.go
More file actions
118 lines (101 loc) · 2.38 KB
/
Copy pathlog_handler.go
File metadata and controls
118 lines (101 loc) · 2.38 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
// Copyright (C) 2025-2026 Jose R F Junior <web2ajax@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-or-later
package main
import (
"bufio"
"context"
"net/http"
"os/exec"
"strconv"
"time"
gws "github.com/gorilla/websocket"
"github.com/rs/zerolog/log"
)
var logWSUpgrader = gws.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type logMessage struct {
Type string `json:"type"`
Data string `json:"data"`
}
func (s *SignalingServer) handleLogStream(w http.ResponseWriter, r *http.Request) {
conn, err := logWSUpgrader.Upgrade(w, r, nil)
if err != nil {
log.Error().Err(err).Msg("Log WS upgrade failed")
return
}
defer conn.Close()
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
// Number of historical lines
lines := 200
if q := r.URL.Query().Get("lines"); q != "" {
if n, err := strconv.Atoi(q); err == nil && n > 0 && n <= 5000 {
lines = n
}
}
// Start journalctl subprocess
cmd := exec.CommandContext(ctx, "journalctl",
"-u", "eva-mind",
"-f",
"-o", "short-iso",
"-n", strconv.Itoa(lines),
)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Error().Err(err).Msg("Failed to create journalctl stdout pipe")
conn.WriteJSON(logMessage{Type: "error", Data: "failed to start log stream"})
return
}
if err := cmd.Start(); err != nil {
log.Error().Err(err).Msg("Failed to start journalctl")
conn.WriteJSON(logMessage{Type: "error", Data: "journalctl not available"})
return
}
log.Info().Msg("Log stream session started")
conn.WriteJSON(logMessage{Type: "status", Data: "connected"})
// Goroutine: read from client (detect disconnect)
go func() {
for {
if _, _, err := conn.ReadMessage(); err != nil {
cancel()
return
}
}
}()
// Ping keepalive
pingTicker := time.NewTicker(30 * time.Second)
defer pingTicker.Stop()
go func() {
for {
select {
case <-ctx.Done():
return
case <-pingTicker.C:
if err := conn.WriteMessage(gws.PingMessage, nil); err != nil {
cancel()
return
}
}
}
}()
// Stream journal lines to WebSocket
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
select {
case <-ctx.Done():
cmd.Process.Kill()
return
default:
line := scanner.Text()
if err := conn.WriteJSON(logMessage{Type: "log", Data: line}); err != nil {
cmd.Process.Kill()
return
}
}
}
cmd.Wait()
log.Info().Msg("Log stream session ended")
}