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"
"github.com/genofire/golang-lib/log"
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
func Start(nodeBind *runtime.Nodes) {
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()
log.HTTP(r).Info("client disconnected")
2017-05-08 19:13:29 +02:00
}()
2017-05-08 19:13:29 +02:00
log.HTTP(r).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
}
2017-05-15 21:59:48 +02:00
func NotifyNode(node *runtime.Node, real bool) {
msgType := MessageTypeUpdateNode
2017-05-08 19:13:29 +02:00
if real {
msgType = MessageTypeCurrentNode
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() {
log.Log.Infof("websocket stopped with %d clients", len(clients))
2017-05-08 19:13:29 +02:00
}