2016-12-12 22:26:51 +00:00
|
|
|
package events
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2017-02-06 22:57:43 +00:00
|
|
|
"encoding/json"
|
|
|
|
"time"
|
2016-12-12 22:26:51 +00:00
|
|
|
|
2017-02-06 22:57:43 +00:00
|
|
|
"github.com/Sirupsen/logrus"
|
2016-12-12 22:26:51 +00:00
|
|
|
"github.com/docker/containerd/log"
|
2017-02-06 22:57:43 +00:00
|
|
|
"github.com/nats-io/go-nats-streaming"
|
|
|
|
"github.com/pkg/errors"
|
2016-12-12 22:26:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type natsPoster struct {
|
2017-02-06 22:57:43 +00:00
|
|
|
sc stan.Conn
|
2016-12-12 22:26:51 +00:00
|
|
|
}
|
|
|
|
|
2017-02-06 22:57:43 +00:00
|
|
|
func NewNATSPoster(clusterID, clientID string) (Poster, error) {
|
|
|
|
sc, err := stan.Connect(clusterID, clientID, stan.ConnectWait(5*time.Second))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "failed to connect to nats streaming server")
|
|
|
|
}
|
|
|
|
return &natsPoster{sc}, nil
|
|
|
|
|
2016-12-12 22:26:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *natsPoster) Post(ctx context.Context, e Event) {
|
|
|
|
topic := getTopic(ctx)
|
2017-02-06 22:57:43 +00:00
|
|
|
if topic == "" {
|
|
|
|
log.G(ctx).WithField("event", e).Warn("unable to post event, topic is empty")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := json.Marshal(e)
|
|
|
|
if err != nil {
|
|
|
|
log.G(ctx).WithError(err).WithFields(logrus.Fields{"event": e, "topic": topic}).
|
|
|
|
Warn("unable to marshal event")
|
|
|
|
return
|
2016-12-12 22:26:51 +00:00
|
|
|
}
|
|
|
|
|
2017-02-06 22:57:43 +00:00
|
|
|
err = p.sc.Publish(topic, data)
|
|
|
|
if err != nil {
|
|
|
|
log.G(ctx).WithError(err).WithFields(logrus.Fields{"event": e, "topic": topic}).
|
|
|
|
Warn("unable to post event")
|
2016-12-12 22:26:51 +00:00
|
|
|
}
|
|
|
|
|
2017-02-06 22:57:43 +00:00
|
|
|
log.G(ctx).WithFields(logrus.Fields{"event": e, "topic": topic}).
|
|
|
|
Debug("Posted event")
|
2016-12-12 22:26:51 +00:00
|
|
|
}
|