/
muleemitter.go
198 lines (167 loc) · 5.44 KB
/
muleemitter.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package traceability
import (
"encoding/json"
"fmt"
"time"
"github.com/Axway/agent-sdk/pkg/cache"
"github.com/Axway/agent-sdk/pkg/jobs"
"github.com/Axway/agent-sdk/pkg/util/log"
"github.com/sirupsen/logrus"
hc "github.com/Axway/agent-sdk/pkg/util/healthcheck"
"github.com/Axway/agents-mulesoft/pkg/anypoint"
"github.com/Axway/agents-mulesoft/pkg/config"
)
const (
healthCheckEndpoint = "ingestion"
CacheKeyTimeStamp = "LAST_RUN"
)
type Emitter interface {
Start() error
OnConfigChange(gatewayCfg *config.AgentConfig)
}
type healthChecker func(name, endpoint string, check hc.CheckStatus) (string, error)
// MuleEventEmitter - Gathers analytics data for publishing to Central.
type MuleEventEmitter struct {
client anypoint.AnalyticsClient
eventChannel chan string
cache cache.Cache
cachePath string
}
// MuleEventEmitterJob wraps an Emitter and implements the Job interface so that it can be executed by the sdk.
type MuleEventEmitterJob struct {
Emitter
consecutiveErrors int
jobID string
pollInterval time.Duration
getStatusLevel hc.GetStatusLevel
}
// NewMuleEventEmitter - Creates a client to poll for events.
func NewMuleEventEmitter(cachePath string, eventChannel chan string, client anypoint.AnalyticsClient) *MuleEventEmitter {
me := &MuleEventEmitter{
eventChannel: eventChannel,
client: client,
}
me.cachePath = formatCachePath(cachePath)
me.cache = cache.Load(me.cachePath)
return me
}
// Start retrieves analytics data from anypoint and sends them on the event channel for processing.
func (me *MuleEventEmitter) Start() error {
strStartTime, strEndTime := me.getLastRun()
events, err := me.client.GetAnalyticsWindow(strStartTime, strEndTime)
if err != nil {
logrus.WithError(err).Error("failed to get analytics data")
return err
}
var lastTime time.Time
lastTime, err = time.Parse(time.RFC3339, strStartTime)
if err != nil {
logrus.WithFields(logrus.Fields{"strStartTime": strStartTime}).Warn("Unable to Parse Last Time")
}
for _, event := range events {
// Results are not sorted. We want the most recent time to bubble up
if event.Timestamp.After(lastTime) {
lastTime = event.Timestamp
}
j, err := json.Marshal(event)
if err != nil {
log.Warnf("failed to marshal event: %s", err.Error())
}
me.eventChannel <- string(j)
}
// Add 1 second to the last time stamp if we found records from this pull.
// This will prevent duplicate records from being retrieved
if len(events) > 0 {
lastTime = lastTime.Add(time.Second * 1)
}
me.saveLastRun(lastTime.Format(time.RFC3339))
return nil
}
func (me *MuleEventEmitter) getLastRun() (string, string) {
tStamp, _ := me.cache.Get(CacheKeyTimeStamp)
now := time.Now()
tNow := now.Format(time.RFC3339Nano)
if tStamp == nil {
tStamp = tNow
me.saveLastRun(tNow)
}
return tStamp.(string), tNow
}
func (me *MuleEventEmitter) saveLastRun(lastTime string) {
me.cache.Set(CacheKeyTimeStamp, lastTime)
me.cache.Save(me.cachePath)
}
// OnConfigChange passes the new config to the client to handle config changes
// since the MuleEventEmitter only has cache config value references and should not be changed
func (me *MuleEventEmitter) OnConfigChange(gatewayCfg *config.AgentConfig) {
me.client.OnConfigChange(gatewayCfg.MulesoftConfig)
}
// NewMuleEventEmitterJob creates a struct that implements the Emitter and Job interfaces.
func NewMuleEventEmitterJob(
emitter Emitter,
pollInterval time.Duration,
checkStatus hc.CheckStatus,
getStatus func(endpoint string) hc.StatusLevel,
registerHC healthChecker,
) (*MuleEventEmitterJob, error) {
_, err := registerHC("Data Ingestion Endpoint", healthCheckEndpoint, checkStatus)
if err != nil {
return nil, err
}
return &MuleEventEmitterJob{
Emitter: emitter,
pollInterval: pollInterval,
getStatusLevel: getStatus,
}, nil
}
// Start registers the job with the sdk.
func (m *MuleEventEmitterJob) Start() error {
jobID, err := jobs.RegisterIntervalJob(m, m.pollInterval)
m.jobID = jobID
return err
}
// OnConfigChange updates the MuleEventEmitterJob with any config changes, and calls OnConfigChange on the Emitter
func (m *MuleEventEmitterJob) OnConfigChange(gatewayCfg *config.AgentConfig) {
m.pollInterval = gatewayCfg.MulesoftConfig.PollInterval
m.Emitter.OnConfigChange(gatewayCfg)
}
// Execute called by the sdk on each interval.
func (m *MuleEventEmitterJob) Execute() error {
return m.Emitter.Start()
}
// Status Performs a health check for this job before it is executed.
func (m *MuleEventEmitterJob) Status() error {
max := 3
status := m.getStatusLevel(healthCheckEndpoint)
if status == hc.OK {
m.consecutiveErrors = 0
} else {
m.consecutiveErrors++
}
if m.consecutiveErrors >= max {
// If the job fails 3 times return an error
return fmt.Errorf("failed to start the Traceability agent %d times in a row", max)
}
return nil
}
// Ready determines if the job is ready to run.
func (m *MuleEventEmitterJob) Ready() bool {
status := m.getStatusLevel(healthCheckEndpoint)
return status == hc.OK
}
// Check the status of the connection to mulesoft
func traceabilityHealthCheck(name string) *hc.Status {
health := hc.GetStatus(anypoint.HealthCheckEndpoint)
if health == hc.FAIL {
return &hc.Status{
Result: hc.FAIL,
Details: fmt.Sprintf("%s Failed. Unable to connect to Mulesoft, check Mulesoft configuration.", name),
}
}
return &hc.Status{
Result: hc.OK,
}
}
func formatCachePath(path string) string {
return fmt.Sprintf("%s/anypoint.cache", path)
}