2021-10-27 23:05:36 +02:00
|
|
|
package events
|
2021-11-03 22:34:55 +01:00
|
|
|
|
2021-11-14 15:07:20 +01:00
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
)
|
2021-11-03 22:34:55 +01:00
|
|
|
|
|
|
|
var ls net.Listener
|
|
|
|
var done <-chan struct{}
|
2021-11-15 22:04:59 +01:00
|
|
|
var callbacks []func(map[string]string)
|
2021-11-03 22:34:55 +01:00
|
|
|
|
2021-11-14 15:07:20 +01:00
|
|
|
// Init initializes the unix socket.
|
2021-11-03 22:34:55 +01:00
|
|
|
func Init(socketPath string) {
|
2021-11-15 22:04:59 +01:00
|
|
|
var err error
|
|
|
|
ls, err = net.Listen("unix", socketPath)
|
2021-11-03 22:34:55 +01:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-11-15 22:04:59 +01:00
|
|
|
callbacks = make([]func(map[string]string), 3)
|
2021-11-03 22:34:55 +01:00
|
|
|
}
|
|
|
|
|
2021-11-14 15:07:20 +01:00
|
|
|
// Listen starts the event loop.
|
|
|
|
func Listen() {
|
2021-11-03 22:34:55 +01:00
|
|
|
for {
|
|
|
|
go func() {
|
|
|
|
process()
|
|
|
|
}()
|
|
|
|
}
|
2021-11-14 15:07:20 +01:00
|
|
|
}
|
2021-11-03 22:34:55 +01:00
|
|
|
|
2021-11-14 15:07:20 +01:00
|
|
|
// RegisterCallback adds a function to the list of callback functions for processing of events.
|
2021-11-15 22:04:59 +01:00
|
|
|
func RegisterCallback(cb func(map[string]string)) {
|
|
|
|
callbacks = append(callbacks, cb)
|
2021-11-03 22:34:55 +01:00
|
|
|
}
|
|
|
|
|
2021-11-14 15:07:20 +01:00
|
|
|
// process processes each and every unix socket event, Unmarshals the json data and calls the list of callbacks.
|
2021-11-03 22:34:55 +01:00
|
|
|
func process() {
|
2021-11-15 22:04:59 +01:00
|
|
|
client, err := ls.Accept()
|
2021-11-03 22:34:55 +01:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-11-14 15:07:20 +01:00
|
|
|
data := make([]byte, 2048)
|
|
|
|
for {
|
|
|
|
buf := make([]byte, 512)
|
|
|
|
nr, err := client.Read(buf)
|
|
|
|
if err != nil && err != io.EOF {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-11-15 22:04:59 +01:00
|
|
|
app := buf[0:nr]
|
|
|
|
data = append(data, app)
|
2021-11-14 15:07:20 +01:00
|
|
|
if err == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
env := map[string]string{}
|
2021-11-15 22:04:59 +01:00
|
|
|
errjson := json.Unmarshal(data, &env)
|
|
|
|
if errjson != nil {
|
|
|
|
panic(errjson)
|
2021-11-14 15:07:20 +01:00
|
|
|
}
|
2021-11-15 22:04:59 +01:00
|
|
|
for _, v := range callbacks {
|
2021-11-14 15:07:20 +01:00
|
|
|
v(env)
|
2021-11-03 22:34:55 +01:00
|
|
|
}
|
|
|
|
}
|