-
Notifications
You must be signed in to change notification settings - Fork 0
/
router_register_path.go
549 lines (511 loc) · 16.4 KB
/
router_register_path.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
package main
import (
"encoding/json"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
var (
// websocket upgrader
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// Binary directory path
absPath string
// websocket ping/poing timeout for connection check
pongWait = 30 * time.Second
pingPeriod = (pongWait * 9) / 10
writeWait = 10 * time.Second
)
// registerPaths will register all paths at one go.
func registerPaths(r *mux.Router) {
staticDir := "/ui/"
r.PathPrefix(staticDir).Handler(http.StripPrefix(staticDir, http.FileServer(http.Dir(absPath+staticDir))))
fs := http.FileServer(http.Dir(config.Logs.Inlogs))
r.PathPrefix("/logs/").Handler(http.StripPrefix("/logs/", fileserve(fs)))
r.HandleFunc("/serialconsole", webSocketHandler).Queries("portname", "{.*}")
r.HandleFunc("/get/config", getConfig).Methods("GET")
r.HandleFunc("/port", servePortHtml).Methods("GET")
r.HandleFunc("/", serveHomeHtml).Methods("GET")
r.HandleFunc("/delete", deletePort).Methods("DELETE").Queries("portname", "{.*}")
r.HandleFunc("/edit", editPort).Methods("POST").Queries("portname", "{.*}")
r.HandleFunc("/add", addPort).Methods("POST")
r.HandleFunc("/stop", stopPort).Methods("POST").Queries("portname", "{.*}")
r.HandleFunc("/start", startPort).Methods("POST").Queries("portname", "{.*}")
r.HandleFunc("/getactivesession", getActiveSession).Methods("GET").Queries("portname", "{.*}")
r.HandleFunc("/version", serveVersion).Methods("GET")
}
// getActiveSession will return active session count on givne port
func getActiveSession(w http.ResponseWriter, r *http.Request) {
var pname = r.FormValue("portname")
if pname == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Portname is missing in reuqest."))
return
}
// check if there are element with respect to such ports, if not return error.
if !config.checkElement(pname) || !all.checkElement(pname) {
config.mu.Lock()
all.mu.Lock()
log.Println(config.Ports)
log.Println(all.ports)
config.mu.Unlock()
all.mu.Unlock()
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Config/allport struct missing given port."))
return
}
w.Write([]byte(strconv.Itoa(all.ports[pname].clientactive.getconncount())))
}
// startPort will start serial port
func startPort(w http.ResponseWriter, r *http.Request) {
var pname = r.FormValue("portname")
msg, st := commonCheck(pname)
if msg != "" {
w.WriteHeader(st)
w.Write([]byte(msg))
return
}
all.ports[pname].clientactive.increment(r.RemoteAddr)
defer all.ports[pname].clientactive.decrement()
if st, _ := config.getStatus(pname); st == 1 {
return
}
if st, _ := all.getStatus(pname); st == 1 {
return
}
_ = config.portStatusUpdate(pname, 1)
_ = all.portStatusUpdate(pname, 1)
err := config.writeYaml(*conf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error writing YAML file."))
log.Panicf("[Client:" + r.RemoteAddr + " Serial Port:" + "]" + pname + err.Error())
return
}
initializereader(pname)
}
// stopPort will stop serial port
func stopPort(w http.ResponseWriter, r *http.Request) {
var pname = r.FormValue("portname")
msg, st := commonCheck(pname)
if msg != "" {
w.WriteHeader(st)
w.Write([]byte(msg))
return
}
all.ports[pname].clientactive.increment(r.RemoteAddr)
defer all.ports[pname].clientactive.decrement()
if st, _ := config.getStatus(pname); st == 2 {
return
}
if st, _ := all.getStatus(pname); st == 2 {
return
}
_ = mainReaderClose(pname)
log.Printf("[Client:%s Serial Port:%s]Main reader go routine closed.",
r.RemoteAddr, pname)
config.portStatusUpdate(pname, 2)
all.mu.Lock()
tmp := all.ports[pname].baudrate
all.mu.Unlock()
all.initializeport(pname, tmp, 2)
err := config.writeYaml(*conf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error writing YAML file."))
log.Panicf("[Client:" + r.RemoteAddr + " Serial Port:" + "]" + pname + err.Error())
return
}
}
// mainReaderClose will close main reader go routine and return
func mainReaderClose(portname string) bool {
for {
select {
case <-all.ports[portname].ack:
log.Printf("[Port:%s]Mainreader go routine closed. Ack recived.", portname)
return true
default:
all.ports[portname].stop <- struct{}{}
log.Printf("[Port:%s]Mainreader go routine stop send.", portname)
// Not needed anymore as we have added timeout on port read and it is non blocking.
// if all.ports[portname].port != nil {
// all.ports[portname].port.Write([]byte("golang\n"))
// }
time.Sleep(200 * time.Millisecond)
}
}
}
// commonCheck function will check common condition for delete/edit request of API
// and return error string and respective http status code if any.
func commonCheck(pname string) (string, int) {
if pname == "" {
return "Portname is missing in reuqest.", http.StatusBadRequest
}
// check if there are element with respect to such ports, if not return error.
if !config.checkElement(pname) || !all.checkElement(pname) {
config.mu.Lock()
all.mu.Lock()
log.Println(config.Ports)
log.Println(all.ports)
config.mu.Unlock()
all.mu.Unlock()
return "Config/allport struct missing given port.", http.StatusInternalServerError
}
// check if there are any other existing session active or not.
// and lock session on this port any more.
if all.ports[pname].clientactive.getconncount() >= 1 {
msg := "Can not delete/edit/stop/start port .One session active with IP:" +
all.ports[pname].clientactive.getraaddr() + ".Try after sometime."
return msg, http.StatusForbidden
}
return "", http.StatusOK
}
// jsondecoder will decode given request body for port edit and add
// return error if any element missing or extra element present.
func (p *jsonport) jsondecoder(r *http.Request) error {
d := json.NewDecoder(r.Body)
d.DisallowUnknownFields()
err := d.Decode(&p)
if err != nil {
return err
}
return nil
}
// editPort will delete port configuration if portname or baudrate changing
// if only desc is changing then port deletion not required.
func editPort(w http.ResponseWriter, r *http.Request) {
var pname = r.FormValue("portname")
var jport jsonport
err := jport.jsondecoder(r)
if err != nil {
log.Printf("[Client:%s Serial Port:%s]Error in posted JSON decode:%s",
r.RemoteAddr, pname, err)
w.WriteHeader(http.StatusBadRequest)
return
}
msg, status := commonCheck(pname)
if msg != "" {
w.WriteHeader(status)
w.Write([]byte(msg))
return
}
all.ports[pname].clientactive.increment(r.RemoteAddr)
all.mu.Lock()
tmpbr := all.ports[pname].baudrate
all.mu.Unlock()
if jport.Baudrate == tmpbr && jport.Newname == pname {
err = config.updateElement(jport.Newname, jport.Desc)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
err = config.writeYaml(*conf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Some error while writing YAML.Service going into panic..."))
log.Panicf(err.Error())
}
all.ports[pname].clientactive.decrement()
} else {
if jport.Baudrate == tmpbr && (all.checkElement(jport.Newname) ||
config.checkElement(jport.Newname)) {
all.ports[pname].clientactive.decrement()
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Provided port name already exist."))
return
}
if st, _ := all.getStatus(pname); st == 1 {
mainReaderClose(pname)
log.Printf("[Client:%s Serial Port:%s]Main reader go routine closed.",
r.RemoteAddr, pname)
}
all.removeElement(pname)
log.Printf("[Client:%s Serial Port:%s]Port removed from allports struct.",
r.RemoteAddr, pname)
config.removeElement(pname)
log.Printf("[Client:%s Serial Port:%s]Port removed from config struct.",
r.RemoteAddr, pname)
err = all.addnewport(jport.Newname, jport.Baudrate, 1)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
err = config.addElement(jport.Newname, jport.Baudrate, jport.Desc)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
err = config.writeYaml(*conf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Service going into panic. Start again..."))
log.Panicf("[Client:" + r.RemoteAddr + " Serial Port:" + "]" + pname + err.Error())
}
log.Printf("[Client:%s Serial Port:%s]New port added to YAML.",
r.RemoteAddr, jport.Newname)
// start newly added port.
initializereader(jport.Newname)
}
}
// addPort will add new port configuration first and then
// start port.
func addPort(w http.ResponseWriter, r *http.Request) {
var jport jsonport
err := jport.jsondecoder(r)
if err != nil {
log.Printf("[Client:%s Serial Port:%s]Error in posted JSON decode:%s",
r.RemoteAddr, jport.Newname, err)
w.WriteHeader(http.StatusBadRequest)
return
}
if all.checkElement(jport.Newname) && config.checkElement(jport.Newname) {
log.Printf("[Client:%s Serial Port:%s]Given port already exist.",
r.RemoteAddr, jport.Newname)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Port already exist."))
return
}
err = all.addnewport(jport.Newname, jport.Baudrate, 1)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
err = config.addElement(jport.Newname, jport.Baudrate, jport.Desc)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
err = config.writeYaml(*conf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Service going into panic. Start again..."))
log.Panicf("[Client:" + r.RemoteAddr + " Serial Port:" + "]" + jport.Newname + err.Error())
}
log.Printf("[Client:%s Serial Port:%s]New port added to YAML.",
r.RemoteAddr, jport.Newname)
// start newly added port.
initializereader(jport.Newname)
}
// deletePort will delete port configuration and cleaup
// struct Config and allports as required and write to yaml configuration file
func deletePort(w http.ResponseWriter, r *http.Request) {
var pname = r.FormValue("portname")
msg, status := commonCheck(pname)
if msg != "" {
w.WriteHeader(status)
w.Write([]byte(msg))
return
}
all.ports[pname].clientactive.increment(r.RemoteAddr)
if st, _ := all.getStatus(pname); st == 1 {
_ = mainReaderClose(pname)
log.Printf("[Client:%s Serial Port:%s]Main reader go routine closed.",
r.RemoteAddr, pname)
}
_ = all.removeElement(pname)
log.Printf("[Client:%s Serial Port:%s]Port removed from allports struct.",
r.RemoteAddr, pname)
_ = config.removeElement(pname)
log.Printf("[Client:%s Serial Port:%s]Port removed from config struct.",
r.RemoteAddr, pname)
err := config.writeYaml(*conf)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error writing YAML file."))
log.Panicf("[Client:" + r.RemoteAddr + " Serial Port:" + "]" + pname + err.Error())
}
}
// serve static log files
func fileserve(fs http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/x-info")
fs.ServeHTTP(w, r)
}
}
// serveHomeHtml handler
func serveHomeHtml(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles(absPath + "/ui/home.html")
if err != nil {
log.Printf("Home.html serve error:%s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
tmpl.Execute(w, nil)
}
// servePortHtml handler
func servePortHtml(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles(absPath + "/ui/port.html")
if err != nil {
log.Printf("Port.html serve error:%s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
tmpl.Execute(w, nil)
}
// getConfig will return configuration of yaml file into JSON format
func getConfig(w http.ResponseWriter, r *http.Request) {
str, err := config.getJSON()
if err != nil {
log.Printf("Error in JSON Marshal: %s", err)
w.WriteHeader(http.StatusInternalServerError)
} else {
w.Write(str)
}
}
// webSocket handler handles any request to access serial port
// over websocket connection
func webSocketHandler(w http.ResponseWriter, r *http.Request) {
var raddr = r.RemoteAddr
var pname = r.FormValue("portname")
log.Printf("[Client:%s Serial Port:%s]Starting session",
raddr, pname)
done := make(chan struct{}, 2)
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("[Client:%s Serial Port:%s]Websocket upgrade failed: %s",
raddr, pname, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer func() {
conn.Close()
log.Printf("[Client:%s Serial Port:%s]Closed session.",
raddr, pname)
}()
if st, _ := all.getStatus(pname); st == 2 {
log.Printf("[Client:%s Serial Port:%s]Port status is disabled.", raddr, pname)
conn.WriteMessage(websocket.BinaryMessage, []byte("Please enable port first from UI."))
return
}
// Checking existing number of session and allow or disallow new
// session.
if all.ports[pname].clientactive.getconncount() >= 1 {
msg := "One user session already active with IP:" + all.ports[pname].clientactive.getraaddr() + "."
conn.WriteMessage(websocket.BinaryMessage, []byte(msg))
log.Printf("[Client:%s Serial Port:%s]Session not allowed.", raddr, pname)
return
} else {
// p.ports[pname].clientactive.increment(raddr)
log.Printf("[Client:%s Serial Port:%s]Session allowed. Active session count: %d",
raddr, pname, all.ports[pname].clientactive.getconncount())
all.ports[pname].clientactive.increment(raddr)
}
// Checking if port is already open and if not open then return
// without opening any port read/write.
all.mu.Lock()
if all.ports[pname].port == nil {
all.mu.Unlock()
all.ports[pname].clientactive.decrement()
msg := "Port is not yet opened. Please connect port and try again."
conn.WriteMessage(websocket.BinaryMessage, []byte(msg))
log.Printf("[Client:%s Serial Port:%s]Error: %s",
raddr, pname, msg)
return
}
all.mu.Unlock()
// goroutine to read from port and write to websocket
go func() {
ticker := time.NewTicker(pingPeriod)
defer func() {
log.Printf("[Client:%s Serial Port:%s]Go routine write to ws closed.",
raddr, pname)
ticker.Stop()
}()
for {
select {
case v, ok := <-all.ports[pname].comm:
if !ok {
log.Printf("[Client:%s Serial Port:%s]Comm channel is closed.",
raddr, pname)
done <- struct{}{}
return
}
conn.SetWriteDeadline(time.Now().Add(writeWait))
err := conn.WriteMessage(websocket.BinaryMessage, []byte(v)[:len([]byte(v))])
if err != nil {
log.Printf("[Client:%s Serial Port:%s]Write error %s\n",
raddr, pname, err)
done <- struct{}{}
return
}
case <-ticker.C:
conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
log.Printf("[Client:%s Serial Port:%s]Ping write error %s\n",
raddr, pname, err)
done <- struct{}{}
return
}
}
}
}()
// goroutine to read from websocket and write to port
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("[Client:%s Serial Port:%s]Panic writing to port: %s.",
raddr, pname, err)
done <- struct{}{}
}
all.ports[pname].clientactive.decrement()
log.Printf("[Client:%s Serial Port:%s]Go routine read from ws closed.",
raddr, pname)
}()
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
for {
_, reader, err := conn.ReadMessage()
if err != nil {
log.Printf("[Client:%s Serial Port:%s]Error reading: %s.",
raddr, pname, err)
break
}
_, err = all.ports[pname].port.Write(reader)
if err != nil {
log.Printf("[Client:%s Serial Port:%s]Error writing to port: %s.",
raddr, pname, err)
break
}
}
done <- struct{}{}
}()
//Wait for either goroutine to exit
<-done
}
// CreateRouterRegisterPaths will be exported and will create router and register paths.
func createRouterRegisterPaths() *mux.Router {
path, err := os.Executable()
if err != nil {
log.Println("Not able to determine executable path.")
os.Exit(1)
}
// Directory path from where binary started.
absPath = filepath.Dir(path)
router := mux.NewRouter().StrictSlash(true)
registerPaths(router)
return router
}
// serveVersion handler
func serveVersion(w http.ResponseWriter, r *http.Request) {
msg := "Current Version:" + ver
w.Write([]byte(msg))
}