This repository has been archived by the owner on Feb 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewer.go
103 lines (84 loc) · 2.43 KB
/
viewer.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package lifecycle
import (
"context"
"fmt"
"io"
"os"
"time"
"github.com/choria-io/go-choria/choria"
"github.com/choria-io/go-srvcache"
"github.com/sirupsen/logrus"
)
// SubscribeConnector is a connection to the middleware
type SubscribeConnector interface {
QueueSubscribe(ctx context.Context, name string, subject string, group string, output chan *choria.ConnectorMessage) error
ConnectedServer() string
}
type Framework interface {
NewConnector(ctx context.Context, servers func() (srvcache.Servers, error), name string, logger *logrus.Entry) (conn choria.Connector, err error)
Certname() string
Logger(name string) *logrus.Entry
NewRequestID() (string, error)
MiddlewareServers() (servers srvcache.Servers, err error)
}
// ViewOptions configure the view command
type ViewOptions struct {
TypeFilter string
ComponentFilter string
Debug bool
Output io.Writer
Choria Framework
Connector SubscribeConnector
}
// View connects and stream events to Output
func View(ctx context.Context, opt *ViewOptions) error {
var err error
log := opt.Choria.Logger("event_viewer")
opt.Connector, err = opt.Choria.NewConnector(ctx, opt.Choria.MiddlewareServers, opt.Choria.Certname(), log)
if err != nil {
return fmt.Errorf("cannot connect: %s", err)
}
if opt.Output == nil {
opt.Output = os.Stdout
}
fmt.Fprintf(opt.Output, "Waiting for events from topic choria.lifecycle.event.> on %s\n", opt.Connector.ConnectedServer())
return WriteEvents(ctx, opt)
}
// WriteEvents views the event stream to the output
func WriteEvents(ctx context.Context, opt *ViewOptions) error {
events := make(chan *choria.ConnectorMessage, 100)
rid, err := opt.Choria.NewRequestID()
if err != nil {
return err
}
err = opt.Connector.QueueSubscribe(ctx, rid, "choria.lifecycle.event.>", "", events)
if err != nil {
return fmt.Errorf("could not subscribe to event source: %s", err)
}
for {
select {
case e := <-events:
event, err := NewFromJSON(e.Data)
if err != nil {
continue
}
if opt.ComponentFilter != "" {
if event.Component() != opt.ComponentFilter {
continue
}
}
if opt.TypeFilter != "" {
if event.TypeString() != opt.TypeFilter {
continue
}
}
if opt.Debug {
fmt.Fprintf(opt.Output, "%s\n", string(e.Data))
continue
}
fmt.Fprintf(opt.Output, "%s %s\n", time.Now().Format("15:04:05"), event.String())
case <-ctx.Done():
return nil
}
}
}