Skip to content
Snippets Groups Projects
app.go 1.54 KiB
Newer Older
  • Learn to ignore specific revisions
  • 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)
    }