Newer
Older
Fabian Seidl
committed
package eventservice
import (
Fabian Seidl
committed
"encoding/json"
"code.fbi.h-da.de/danet/gosdn/controller/config"
Fabian Seidl
committed
"code.fbi.h-da.de/danet/gosdn/controller/customerrs"
Fabian Seidl
committed
"code.fbi.h-da.de/danet/gosdn/controller/event"
interfaces "code.fbi.h-da.de/danet/gosdn/controller/interfaces/event"
amqp "github.com/rabbitmq/amqp091-go"
log "github.com/sirupsen/logrus"
Fabian Seidl
committed
)
// EventService is used to setup a connection to a broker and publish events to topics.
type EventService struct {
connection *amqp.Connection
channel *amqp.Channel
}
// NewEventService creates a new connection to the broker and opens a channel for later usage.
func NewEventService() (interfaces.Service, error) {
// TODO: This is an fugly hack to mitigate that some tests are trying to connect to an actual broker. (staester)
if config.AMQPPrefix == "" {
return NewMockEventService(), nil
}
conn, err := amqp.Dial(amqpURIBuilder(config.AMQPPrefix, config.AMQPUser, config.AMQPPassword, config.AMQPHost, config.AMQPPort))
if err != nil {
Fabian Seidl
committed
return nil, &customerrs.AMQPInitFailError{Action: "failed to connect to RabbitMQ", Err: err}
Fabian Seidl
committed
}
ch, err := conn.Channel()
if err != nil {
Fabian Seidl
committed
return nil, &customerrs.AMQPInitFailError{Action: "failed to open a channel", Err: err}
Fabian Seidl
committed
}
return &EventService{
connection: conn,
channel: ch,
}, nil
}
// PublishEvent declares a queue and publishes events.
func (e *EventService) PublishEvent(topic string, event event.Event) error {
q, err := e.channel.QueueDeclare(
topic, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
Fabian Seidl
committed
return &customerrs.AMQPInitFailError{Action: "failed declaring queue", Err: err}
Fabian Seidl
committed
}
eventBody, err := json.Marshal(event)
if err != nil {
Fabian Seidl
committed
return &customerrs.CouldNotMarshallError{Identifier: topic + " " + event.EntityID.String(), Type: event.Type, Err: err}
Fabian Seidl
committed
}
err = e.channel.PublishWithContext(
context.TODO(),
Fabian Seidl
committed
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/json",
Body: eventBody,
})
if err != nil {
Fabian Seidl
committed
return &customerrs.AMQPMessageFailError{Action: "failed to publish message", Err: err}
Fabian Seidl
committed
}
return nil
}
// CloseConnection closes an exisiting connection.
func (e *EventService) CloseConnection() {
if err := e.connection.Close(); err != nil {
log.Error(err)
}