forked from instana/go-sensor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fsm_test.go
347 lines (286 loc) · 8.37 KB
/
fsm_test.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// (c) Copyright IBM Corp. 2022
package instana
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"testing"
"time"
f "github.com/looplab/fsm"
"github.com/stretchr/testify/assert"
)
func getTestServer(fn func(w http.ResponseWriter, r *http.Request)) *httptest.Server {
handler := http.NewServeMux()
handler.HandleFunc("/", fn)
return httptest.NewServer(handler)
}
// Case: Current state is ANNOUNCED, trying to be READY
func Test_fsmS_testAgent(t *testing.T) {
// Forces the mocked agent to fail with HTTP 400 in the first call to lead fsm to retry once
var serverGaveErrorOnFirstCall bool
server := getTestServer(func(w http.ResponseWriter, r *http.Request) {
if serverGaveErrorOnFirstCall {
w.WriteHeader(http.StatusOK)
} else {
serverGaveErrorOnFirstCall = true
w.WriteHeader(http.StatusBadRequest)
}
})
defer server.Close()
surl := server.URL
u, err := url.Parse(surl)
assert.NoError(t, err)
res := make(chan bool, 1)
r := &fsmS{
agentComm: newAgentCommunicator(u.Hostname(), u.Port(), &fromS{EntityID: "12345"}, defaultLogger),
fsm: f.NewFSM(
"announced",
f.Events{
{Name: eTest, Src: []string{"announced"}, Dst: "ready"},
},
f.Callbacks{
"ready": func(_ context.Context, event *f.Event) {
res <- true
},
}),
retriesLeft: maximumRetries,
expDelayFunc: func(retryNumber int) time.Duration {
return 0
},
logger: defaultLogger,
}
r.testAgent(context.Background(), &f.Event{})
assert.True(t, <-res)
// after a successful request, retriesLeft is reset to maximumRetries
assert.Equal(t, maximumRetries, r.retriesLeft)
}
func Test_fsmS_testAgent_Error(t *testing.T) {
// Forces the mocked agent to fail with HTTP 400 to lead fsm to retry
server := getTestServer(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
})
defer server.Close()
surl := server.URL
u, err := url.Parse(surl)
assert.NoError(t, err)
res := make(chan bool, 1)
r := &fsmS{
agentComm: newAgentCommunicator(u.Hostname(), u.Port(), &fromS{}, defaultLogger),
fsm: f.NewFSM(
"announced",
f.Events{
{Name: eInit, Src: []string{"announced"}, Dst: "init"}},
f.Callbacks{
"init": func(_ context.Context, event *f.Event) {
res <- true
},
}),
retriesLeft: maximumRetries,
expDelayFunc: func(retryNumber int) time.Duration {
return 0
},
logger: defaultLogger,
}
r.testAgent(context.Background(), &f.Event{})
assert.True(t, <-res)
assert.Equal(t, 0, r.retriesLeft)
}
func Test_fsmS_announceSensor(t *testing.T) {
// initializes the global sensor as it is needed when the announcement is successful
InitSensor(DefaultOptions())
defer ShutdownSensor()
// Forces the mocked agent to fail with HTTP 400 in the first call to lead fsm to retry once
var serverGaveErrorOnFirstCall bool
server := getTestServer(func(w http.ResponseWriter, r *http.Request) {
if serverGaveErrorOnFirstCall {
pid := strconv.FormatInt(int64(os.Getpid()), 10)
io.WriteString(w, `{"pid":`+pid+`}`)
} else {
serverGaveErrorOnFirstCall = true
w.WriteHeader(http.StatusBadRequest)
}
})
defer server.Close()
surl := server.URL
u, err := url.Parse(surl)
assert.NoError(t, err)
res := make(chan bool, 1)
r := &fsmS{
agentComm: newAgentCommunicator(u.Hostname(), u.Port(), &fromS{}, defaultLogger),
fsm: f.NewFSM(
"unannounced",
f.Events{
{Name: eAnnounce, Src: []string{"unannounced"}, Dst: "announced"}},
f.Callbacks{
"announced": func(_ context.Context, event *f.Event) {
res <- true
},
}),
retriesLeft: maximumRetries,
expDelayFunc: func(retryNumber int) time.Duration {
return 0
},
logger: defaultLogger,
}
r.announceSensor(context.Background(), &f.Event{})
assert.True(t, <-res)
assert.Equal(t, maximumRetries, r.retriesLeft)
}
func Test_fsmS_announceSensor_Error(t *testing.T) {
server := getTestServer(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
})
defer server.Close()
surl := server.URL
u, err := url.Parse(surl)
assert.NoError(t, err)
res := make(chan bool, 1)
r := &fsmS{
agentComm: newAgentCommunicator(u.Hostname(), u.Port(), &fromS{}, defaultLogger),
fsm: f.NewFSM(
"unannounced",
f.Events{
{Name: eInit, Src: []string{"unannounced"}, Dst: "init"}},
f.Callbacks{
"init": func(_ context.Context, event *f.Event) {
res <- true
},
}),
retriesLeft: maximumRetries,
expDelayFunc: func(retryNumber int) time.Duration {
return 0
},
logger: defaultLogger,
}
r.announceSensor(context.Background(), &f.Event{})
assert.True(t, <-res)
assert.Equal(t, 0, r.retriesLeft)
}
func Test_fsmS_lookupAgentHost(t *testing.T) {
// Forces the mocked agent to fail with HTTP 400 in the first call to lead fsm to retry once
var serverGaveErrorOnFirstCall bool
server := getTestServer(func(w http.ResponseWriter, r *http.Request) {
if serverGaveErrorOnFirstCall {
w.Header().Add("Server", agentHeader)
w.WriteHeader(http.StatusOK)
} else {
serverGaveErrorOnFirstCall = true
w.WriteHeader(http.StatusBadRequest)
}
})
defer server.Close()
surl := server.URL
u, err := url.Parse(surl)
assert.NoError(t, err)
res := make(chan bool, 1)
r := &fsmS{
agentComm: newAgentCommunicator(u.Hostname(), u.Port(), &fromS{}, defaultLogger),
lookupAgentHostRetryPeriod: 0,
fsm: f.NewFSM(
"init",
f.Events{
{Name: eLookup, Src: []string{"init"}, Dst: "unannounced"}},
f.Callbacks{
"enter_unannounced": func(_ context.Context, event *f.Event) {
res <- true
},
}),
retriesLeft: maximumRetries,
expDelayFunc: func(retryNumber int) time.Duration {
return 0
},
logger: defaultLogger,
}
r.lookupAgentHost(context.Background(), &f.Event{})
assert.True(t, <-res)
assert.Equal(t, maximumRetries, r.retriesLeft)
}
// Case:
// 1. Connection between the application and the agent is established.
// 2. Connection with Agent is lost.
// 3. Former Agent host is no longer available.
// 4. A valid Agent hostname is available in the INSTANA_AGENT_HOST env var.
// 5. A connection with the Agent is reestablished via env var.
func Test_fsmS_agentConnectionReestablished(t *testing.T) {
agentResponseJSON := `{
"pid": 37808,
"agentUuid": "88:66:5a:ff:fe:05:a5:f0",
"extraHeaders": ["expected-value"],
"secrets": {
"matcher": "contains-ignore-case",
"list": ["key","pass","secret"]
}
}`
sensor = &sensorS{
options: DefaultOptions(),
}
defer func() {
sensor = nil
}()
server := getTestServer(func(w http.ResponseWriter, r *http.Request) {
p := r.URL.Path
// announce phase (enter_unannounced)
if p == "/com.instana.plugin.golang.discovery" {
io.WriteString(w, agentResponseJSON)
return
}
w.WriteHeader(http.StatusOK)
})
defer server.Close()
surl := server.URL
u, err := url.Parse(surl)
os.Setenv("INSTANA_AGENT_HOST", u.Hostname())
defer func() {
os.Unsetenv("INSTANA_AGENT_HOST")
}()
assert.NoError(t, err)
res := make(chan bool)
r := &fsmS{
agentComm: newAgentCommunicator(u.Hostname(), u.Port(), &fromS{EntityID: "12345"}, defaultLogger),
lookupAgentHostRetryPeriod: 0,
retriesLeft: maximumRetries,
expDelayFunc: func(retryNumber int) time.Duration {
return 0
},
logger: defaultLogger,
}
r.fsm = f.NewFSM(
"none",
f.Events{
{Name: eInit, Src: []string{"none", "unannounced", "announced", "ready"}, Dst: "init"},
{Name: eLookup, Src: []string{"init"}, Dst: "unannounced"},
{Name: eAnnounce, Src: []string{"unannounced"}, Dst: "announced"},
{Name: eTest, Src: []string{"announced"}, Dst: "ready"}},
f.Callbacks{
"init": func(ctx context.Context, e *f.Event) {
r.lookupAgentHost(ctx, e)
},
"enter_unannounced": func(ctx context.Context, e *f.Event) {
r.announceSensor(ctx, e)
},
"enter_announced": func(ctx context.Context, e *f.Event) {
r.testAgent(ctx, e)
},
"ready": func(ctx context.Context, e *f.Event) {
r.ready(ctx, e)
res <- true
},
})
// We fail the test if the channel does not resolve after 5 seconds
go func() {
time.AfterFunc(time.Second*5, func() {
res <- false
})
}()
r.fsm.Event(context.Background(), eInit)
assert.True(t, <-res)
// Simulate Agent connection lost
r.agentComm.host = "invalid_host"
r.reset()
assert.True(t, <-res)
assert.Equal(t, os.Getenv("INSTANA_AGENT_HOST"), r.agentComm.host, "Configured host to be updated with env var value")
}