/
http.go
379 lines (307 loc) · 8.56 KB
/
http.go
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"logdy/utils"
"net/http"
"strconv"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"logdy/models"
)
func handleCheckPass(uiPass string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
utils.Logger.Debug("/api/check-pass")
pass := r.URL.Query().Get("password")
if uiPass == "" {
w.WriteHeader(200)
return
}
if pass == "" || uiPass != pass {
utils.Logger.WithFields(logrus.Fields{
"ip": r.RemoteAddr,
"ua": r.Header.Get("user-agent"),
}).Info("Client denied")
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(200)
}
}
func handleStatus(configFilePath string, analyticsEnabled bool, uiPass string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
utils.Logger.Debug("/api/status")
configStr := ""
if configFilePath != "" {
utils.Logger.Debug("Reading config file")
configStr = utils.LoadFile(configFilePath)
}
initMsg, _ := json.Marshal(models.InitMessage{
BaseMessage: models.BaseMessage{
MessageType: models.MessageTypeInit,
},
AnalyticsEnabled: analyticsEnabled,
AuthRequired: uiPass != "",
ConfigStr: configStr,
})
w.Write(initMsg)
}
}
func handleWs(uiPass string, clients *Clients) func(w http.ResponseWriter, r *http.Request) {
wsUpgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
return func(w http.ResponseWriter, r *http.Request) {
if uiPass != "" {
pass := r.URL.Query().Get("password")
if pass == "" || uiPass != pass {
utils.Logger.WithFields(logrus.Fields{
"ip": r.RemoteAddr,
"ua": r.Header.Get("user-agent"),
}).Info("Client denied")
w.WriteHeader(http.StatusForbidden)
return
}
}
// Upgrade the HTTP connection to a WebSocket connection.
conn, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
utils.Logger.Info("New Web UI client connected")
ch := clients.Join(100, r.URL.Query().Get("should_follow") == "true")
clientId := ch.id
bts, err := json.Marshal(models.ClientJoined{
BaseMessage: models.BaseMessage{
MessageType: models.MessageTypeClientJoined,
},
ClientId: ch.id,
})
if err != nil {
fmt.Println(err)
return
}
err = conn.WriteMessage(1, bts)
if err != nil {
fmt.Println(err)
return
}
go func(clienId string) {
for {
time.Sleep(1 * time.Second)
_, _, err := conn.ReadMessage()
log.Println("ERROR", err)
if err != nil {
utils.Logger.Debug(err)
utils.Logger.WithField("client_id", clientId).Info("Closed client")
clients.Close(clientId)
return
}
}
}(clientId)
mtx := sync.Mutex{}
go func(clientId string) {
for {
time.Sleep(1 * time.Second)
if ch.cursorStatus == CURSOR_STOPPED {
bts, err = json.Marshal(models.ClientMsgStatus{
BaseMessage: models.BaseMessage{
MessageType: models.MessageTypeClientMsgStatus,
},
Client: clients.ClientStats(ch.id),
Stats: clients.Stats(),
})
if err != nil {
fmt.Println("Error while serializing message", err)
continue
}
mtx.Lock()
err = conn.WriteMessage(1, bts)
mtx.Unlock()
if err != nil {
utils.Logger.Error("Err", err)
clients.Close(clientId)
utils.Logger.WithField("client_id", clientId).Info("Closed client")
break
}
}
}
}(clientId)
for {
msgs := <-ch.ch
bulk := models.MessageBulk{
BaseMessage: models.BaseMessage{
MessageType: models.MessageTypeLogBulk,
},
Messages: msgs,
Status: clients.Stats(),
}
utils.Logger.WithField("count", len(msgs)).Debug("Received messages")
if utils.Logger.Level <= logrus.DebugLevel {
for _, msg := range msgs {
mbts, _ := json.Marshal(msg)
utils.Logger.WithFields(logrus.Fields{
"msg": utils.Trunc(string(mbts), 45),
"clientId": clientId,
}).Debug("Sending message through WebSocket")
}
}
bts, err := json.Marshal(bulk)
if err != nil {
fmt.Println("Error while serializing message", err)
continue
}
mtx.Lock()
err = conn.WriteMessage(1, bts)
if err != nil {
utils.Logger.Error("Err", err)
clients.Close(clientId)
utils.Logger.WithField("client_id", clientId).Info("Closed client")
break
}
bts, err = json.Marshal(models.ClientMsgStatus{
BaseMessage: models.BaseMessage{
MessageType: models.MessageTypeClientMsgStatus,
},
Client: clients.ClientStats(ch.id),
Stats: clients.Stats(),
})
if err != nil {
fmt.Println("Error while serializing message", err)
continue
}
err = conn.WriteMessage(1, bts)
mtx.Unlock()
if err != nil {
utils.Logger.Error("Err", err)
clients.Close(clientId)
utils.Logger.WithField("client_id", clientId).Info("Closed client")
break
}
}
}
}
func getClientId(r *http.Request) (string, error) {
kname := "logdy-client-id"
cid := r.Header.Get(kname)
if cid == "" {
cid = r.URL.Query().Get(kname)
}
if cid == "" {
return "", errors.New("missing client id")
}
return cid, nil
}
func getClientOrErr(r *http.Request, w http.ResponseWriter, clients *Clients) *Client {
cid, err := getClientId(r)
if err != nil {
utils.Logger.Error("Missing client id")
w.WriteHeader(http.StatusBadRequest)
return nil
}
cl, ok := clients.GetClient(cid)
if !ok {
utils.Logger.WithField("client_id", cid).Error("Missing client")
w.WriteHeader(http.StatusBadRequest)
return nil
}
return cl
}
func handleClientStatus(clients *Clients) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
cl := getClientOrErr(r, w, clients)
if cl == nil {
return
}
status := r.URL.Query().Get("status")
switch status {
case string(CURSOR_FOLLOWING):
clients.ResumeFollowing(cl.id, r.URL.Query().Has("from_cursor"))
case string(CURSOR_STOPPED):
clients.PauseFollowing(cl.id)
default:
utils.Logger.Error("Unrecognized status")
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}
}
func handleClientLoad(clients *Clients) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
cl := getClientOrErr(r, w, clients)
if cl == nil {
return
}
start := r.URL.Query().Get("start")
count := r.URL.Query().Get("count")
startInt, err := strconv.Atoi(start)
if err != nil {
utils.Logger.Error("Invalid start")
w.WriteHeader(http.StatusBadRequest)
return
}
countInt, err := strconv.Atoi(count)
if err != nil {
utils.Logger.Error("Invalid count")
w.WriteHeader(http.StatusBadRequest)
return
}
clients.Load(cl.id, startInt, countInt, true)
w.WriteHeader(http.StatusOK)
}
}
func handleClientPeek(clients *Clients) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
cl := getClientOrErr(r, w, clients)
if cl == nil {
return
}
type Req struct {
Idxs []int `json:"idxs"`
}
var p Req
// Try to decode the request body into the struct. If there is an error,
// respond to the client with the error message and a 400 status code.
err := json.NewDecoder(r.Body).Decode(&p)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
msgs := clients.PeekLog(p.Idxs)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(msgs)
}
}
var clients *Clients
func handleHttp(httpPort string, uiIp string, analyticsEnabled bool, uiPass string, configFilePath string, bulkWindowMs int64) {
assets, _ := Assets()
BULK_WINDOW_MS = bulkWindowMs
// Use the file system to serve static files
fs := http.FileServer(http.FS(assets))
http.Handle("/", http.StripPrefix("/", fs))
http.HandleFunc("/api/check-pass", handleCheckPass(uiPass))
http.HandleFunc("/api/status", handleStatus(configFilePath, analyticsEnabled, uiPass))
http.HandleFunc("/api/client/set-status", handleClientStatus(clients))
http.HandleFunc("/api/client/load", handleClientLoad(clients))
http.HandleFunc("/api/client/peek-log", handleClientPeek(clients))
// Listen for WebSocket connections on port 8080.
http.HandleFunc("/ws", handleWs(uiPass, clients))
utils.Logger.WithFields(logrus.Fields{
"port": httpPort,
}).Info("WebUI started, visit http://" + uiIp + ":" + httpPort)
err := http.ListenAndServe(uiIp+":"+httpPort, nil)
if err != nil {
panic(err)
}
}