Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"code.fbi.h-da.de/danet/gosdn/application-framework/event"
"github.com/lesismal/nbio/nbhttp"
"github.com/sirupsen/logrus"
)
// Application is an example for a sdn application.
type Application struct {
eventService event.ServiceInterface
stopChannel chan os.Signal
}
// Run runs the application.
func (a *Application) Run() error {
signal.Notify(a.stopChannel, os.Interrupt, syscall.SIGTERM)
// subscribe to Add,Delete and Update event types.
a.eventService.SubscribeToEventType([]event.TypeToCallbackTuple{
{Type: event.Add, Callback: a.callback},
{Type: event.Delete, Callback: a.callback},
{Type: event.Update, Callback: a.callback},
})
a.eventService.SetupEventReciever(a.stopChannel)
mux := &http.ServeMux{}
mux.HandleFunc("/events", onWebsocket)
svr := nbhttp.NewServer(nbhttp.Config{
Network: "tcp",
Addrs: []string{"localhost:4000"},
Handler: mux,
})
err := svr.Start()
if err != nil {
return fmt.Errorf("Server start failed: %w\n", err)
}
<-a.stopChannel
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return svr.Shutdown(ctx)
}
// callback handles an incoming event from the event system. The event is
// turned into JSON encoding and published to all websocket clients through the
// ClientManager.
func (a *Application) callback(event *event.Event) {
b, err := json.Marshal(event)
if err != nil {
logrus.Error("Failed marshal of event")
}
clientManager.Publish(b)
}