freifunkmanager/websocket/server.go

73 lines
1.5 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-30 16:39:14 +02:00
var commands *runtime.Commands
2017-05-08 19:13:29 +02:00
2017-05-30 16:39:14 +02:00
func Start(nodeBind *runtime.Nodes, commandsBind *runtime.Commands) {
2017-05-08 19:13:29 +02:00
nodes = nodeBind
2017-05-30 16:39:14 +02:00
commands = commandsBind
2017-05-08 19:13:29 +02:00
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
}
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() {
log.Log.Infof("websocket stopped with %d clients", len(clients))
2017-05-08 19:13:29 +02:00
}