Skip to content
Snippets Groups Projects
appUtility_test.go 1.72 KiB
Newer Older
  • Learn to ignore specific revisions
  • package integration_test_application
    
    import (
    	"context"
    	"os"
    	"os/signal"
    	"syscall"
    
    	"code.fbi.h-da.de/danet/gosdn/application-framework/event"
    	"code.fbi.h-da.de/danet/gosdn/application-framework/registration"
    	"github.com/sirupsen/logrus"
    	"google.golang.org/grpc"
    )
    
    // Application is an example for a sdn application.
    type Application struct {
    	eventService   event.ServiceInterface
    	stopChannel    chan os.Signal
    	grpcClientConn *grpc.ClientConn
    	eventChannel   chan event.Event
    }
    
    func NewApplication(ctx context.Context, grpcClientConn *grpc.ClientConn, controllerAddress string, topics []event.Topic) *Application {
    	queueCredentials, err := registration.Register(ctx, controllerAddress, "integration-test-application", "SecurePresharedToken")
    	if err != nil {
    		logrus.Errorf("failed to register application on control plane. %v", err)
    		os.Exit(1)
    	}
    
    	eventService, err := event.NewEventService(
    		queueCredentials,
    		topics,
    	)
    	if err != nil {
    		logrus.Errorf("failed to create event service. %v", err)
    		os.Exit(1)
    	}
    
    	return &Application{
    		eventService:   eventService,
    		stopChannel:    make(chan os.Signal, 1),
    		grpcClientConn: grpcClientConn,
    		eventChannel:   make(chan event.Event, 1),
    	}
    }
    
    // Run runs the application.
    func (a *Application) Run(eventTypeCallbackTuples []event.TypeToCallbackTuple) {
    	signal.Notify(a.stopChannel, os.Interrupt, syscall.SIGTERM)
    
    	a.eventService.SubscribeToEventType(eventTypeCallbackTuples)
    	a.eventService.SetupEventReciever(a.stopChannel)
    
    	var forever chan struct{}
    
    	go func() {
    		for {
    			select {
    			case <-a.stopChannel:
    				close(forever)
    				_ = a.grpcClientConn.Close()
    
    				return
    			}
    		}
    	}()
    
    	<-forever
    }
    
    func (a *Application) callback(event *event.Event) {
    	a.eventChannel <- *event
    }