freifunkmanager/websocket/server.go

71 lines
1.4 KiB
Go
Raw Normal View History

2017-05-08 19:13:29 +02:00
package websocket
import (
"net/http"
2017-05-12 21:32:10 +02:00
"sync"
2017-05-08 19:13:29 +02:00
2017-05-15 21:59:48 +02:00
runtimeYanic "github.com/FreifunkBremen/yanic/runtime"
2017-05-29 22:55:38 +02:00
httpLib "github.com/genofire/golang-lib/http"
2018-06-30 01:45:51 +02:00
log "github.com/sirupsen/logrus"
2017-05-08 19:13:29 +02:00
"golang.org/x/net/websocket"
"github.com/FreifunkBremen/freifunkmanager/runtime"
)
var nodes *runtime.Nodes
var clients map[string]*Client
2017-05-12 21:32:10 +02:00
var clientsMutex sync.Mutex
2017-05-15 21:59:48 +02:00
var stats *runtimeYanic.GlobalStats
2017-05-08 19:13:29 +02:00
2018-06-30 01:45:51 +02:00
func Start(nodeBind *runtime.Nodes) {
2017-05-08 19:13:29 +02:00
nodes = nodeBind
clients = make(map[string]*Client)
http.Handle("/websocket", websocket.Handler(func(ws *websocket.Conn) {
r := ws.Request()
ip := httpLib.GetRemoteIP(r)
2017-05-08 19:13:29 +02:00
defer func() {
ws.Close()
2017-05-12 21:32:10 +02:00
clientsMutex.Lock()
delete(clients, ip)
2017-05-12 21:32:10 +02:00
clientsMutex.Unlock()
2018-06-30 01:45:51 +02:00
log.Info("client disconnected")
2017-05-08 19:13:29 +02:00
}()
2018-06-30 01:45:51 +02:00
log.Infof("new client")
2017-05-08 19:13:29 +02:00
client := NewClient(ip, ws)
2017-05-12 21:32:10 +02:00
clientsMutex.Lock()
2017-05-08 19:13:29 +02:00
clients[ip] = client
2017-05-12 21:32:10 +02:00
clientsMutex.Unlock()
2017-05-08 19:13:29 +02:00
client.Listen()
2017-05-08 19:13:29 +02:00
}))
2017-05-15 21:59:48 +02:00
nodes.AddNotify(NotifyNode)
2017-05-08 19:13:29 +02:00
}
func NotifyNode(node *runtime.Node, system bool) {
msgType := MessageTypeCurrentNode
if system {
msgType = MessageTypeSystemNode
2017-05-08 19:13:29 +02:00
}
2017-05-15 21:59:48 +02:00
SendAll(Message{Type: msgType, Node: node})
}
func NotifyStats(data *runtimeYanic.GlobalStats) {
stats = data
SendAll(Message{Type: MessageTypeStats, Body: data})
}
func SendAll(msg Message) {
2017-05-12 21:32:10 +02:00
clientsMutex.Lock()
2017-05-08 19:13:29 +02:00
for _, c := range clients {
2017-05-15 21:59:48 +02:00
c.Write(&msg)
2017-05-08 19:13:29 +02:00
}
2017-05-12 21:32:10 +02:00
clientsMutex.Unlock()
2017-05-08 19:13:29 +02:00
}
func Close() {
2018-06-30 01:45:51 +02:00
log.Infof("websocket stopped with %d clients", len(clients))
2017-05-08 19:13:29 +02:00
}