2017-04-27 19:09:46 +00:00
|
|
|
package socket
|
|
|
|
|
2017-05-29 19:33:51 +00:00
|
|
|
/*
|
|
|
|
* This socket database is to run another service
|
|
|
|
* (without flooding the network with respondd packages)
|
|
|
|
* e.g. https://github.com/FreifunkBremen/freifunkmanager
|
2017-04-27 19:09:46 +00:00
|
|
|
*/
|
2017-05-29 19:33:51 +00:00
|
|
|
|
2017-04-27 19:09:46 +00:00
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net"
|
2017-04-27 20:44:06 +00:00
|
|
|
"sync"
|
2017-04-27 19:09:46 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/FreifunkBremen/yanic/database"
|
|
|
|
"github.com/FreifunkBremen/yanic/runtime"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Connection struct {
|
|
|
|
database.Connection
|
2017-04-27 20:44:06 +00:00
|
|
|
listener net.Listener
|
|
|
|
clients map[net.Addr]net.Conn
|
|
|
|
clientMux sync.Mutex
|
2017-04-27 19:09:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
database.RegisterAdapter("socket", Connect)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Connect(configuration interface{}) (database.Connection, error) {
|
2017-04-27 20:28:31 +00:00
|
|
|
config := configuration.(map[string]interface{})
|
|
|
|
|
|
|
|
if !config["enable"].(bool) {
|
2017-04-27 19:09:46 +00:00
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2017-04-27 20:28:31 +00:00
|
|
|
ln, err := net.Listen(config["type"].(string), config["address"].(string))
|
2017-04-27 19:09:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2017-04-27 20:28:31 +00:00
|
|
|
conn := &Connection{listener: ln, clients: make(map[net.Addr]net.Conn)}
|
2017-04-27 19:09:46 +00:00
|
|
|
go conn.handleSocketConnection(ln)
|
|
|
|
|
|
|
|
log.Println("[socket-database] listen on: ", ln.Addr())
|
|
|
|
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn *Connection) InsertNode(node *runtime.Node) {
|
2017-05-29 19:33:51 +00:00
|
|
|
conn.sendJSON(Message{Event: MessageEventInsertNode, Body: node})
|
2017-04-27 19:09:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (conn *Connection) InsertGlobals(stats *runtime.GlobalStats, time time.Time) {
|
2017-05-29 19:33:51 +00:00
|
|
|
conn.sendJSON(Message{Event: MessageEventInsertGlobals, Body: stats})
|
2017-04-27 19:09:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (conn *Connection) PruneNodes(deleteAfter time.Duration) {
|
2017-05-29 19:33:51 +00:00
|
|
|
conn.sendJSON(Message{Event: MessageEventPruneNodes})
|
2017-04-27 19:09:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (conn *Connection) Close() {
|
2017-04-27 20:44:06 +00:00
|
|
|
conn.clientMux.Lock()
|
2017-04-27 19:09:46 +00:00
|
|
|
for _, c := range conn.clients {
|
2017-04-27 19:45:44 +00:00
|
|
|
c.Close()
|
2017-04-27 19:09:46 +00:00
|
|
|
}
|
2017-04-27 20:44:06 +00:00
|
|
|
conn.clientMux.Unlock()
|
2017-04-27 19:45:44 +00:00
|
|
|
conn.listener.Close()
|
2017-04-27 19:09:46 +00:00
|
|
|
}
|