-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathserver_test.go
More file actions
1584 lines (1366 loc) · 64.3 KB
/
Copy pathserver_test.go
File metadata and controls
1584 lines (1366 loc) · 64.3 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package lifecycle
import (
"context"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"os/signal"
"slices"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/DataDog/datadog-agent/pkg/metrics"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
)
// mockFlusher counts how many times Flush was called and records when each
// Flush call returned. The completedAt pointer is nil until the first Flush.
// onFlush, if set, is invoked after each Flush — used by tests that need to
// synchronize deterministically on flush completion instead of sleeping.
type mockFlusher struct {
count atomic.Int32
completedAt atomic.Pointer[time.Time]
onFlush func()
}
func (m *mockFlusher) Flush() {
m.count.Add(1)
now := time.Now()
m.completedAt.Store(&now)
if m.onFlush != nil {
m.onFlush()
}
}
// mockLogsAgent counts how many times Flush was called and records when each
// call returned. onFlush, if set, is invoked after each Flush.
type mockLogsAgent struct {
count atomic.Int32
completedAt atomic.Pointer[time.Time]
onFlush func()
}
func (m *mockLogsAgent) Flush(_ context.Context) {
m.count.Add(1)
now := time.Now()
m.completedAt.Store(&now)
if m.onFlush != nil {
m.onFlush()
}
}
// mockSampleDrainer counts how many times WaitForPendingSamples was called.
type mockSampleDrainer struct{ count atomic.Int32 }
func (m *mockSampleDrainer) WaitForPendingSamples() { m.count.Add(1) }
// neverDrainer blocks in WaitForPendingSamples forever, simulating a stuck aggregator worker.
// Used to exercise the drain-timeout path in flushAll.
type neverDrainer struct{}
func (n *neverDrainer) WaitForPendingSamples() { select {} }
func newTestServer() (*Server, *mockFlusher, *mockFlusher, *mockLogsAgent, *mockMetricEmitter, *mockSampleDrainer) {
metric := &mockFlusher{}
trace := &mockFlusher{}
logs := &mockLogsAgent{}
emitter := &mockMetricEmitter{}
drainer := &mockSampleDrainer{}
// port 0 — handler-level tests don't bind. Tests that need a childHandle,
// forwarder, or heartbeat assign srv.childHandle / srv.fwd / srv.heartbeat
// after construction.
srv := NewServer(0, metric, trace, logs, emitter, drainer, metrics.MetricSourceAWSMicroVMEnhanced, 2*time.Second, nil, nil, nil)
return srv, metric, trace, logs, emitter, drainer
}
// /ready with a nil ChildHandle is a wiring bug. The handler logs WARN and
// returns 503. Production setup() always constructs a non-nil handle (real
// *Child in init mode, NoopChildHandle in sidecar mode); only legacy unit
// tests can hit this path.
func TestHandleReady_NilChildHandle_Returns503(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
req := httptest.NewRequest(http.MethodPost, pathReady, nil)
rec := httptest.NewRecorder()
srv.handleReady(rec, req)
assert.Equal(t, http.StatusServiceUnavailable, rec.Code)
}
func TestHandleValidateEmitsMetricAndReturns200(t *testing.T) {
srv, _, _, _, emitter, _ := newTestServer()
rec := httptest.NewRecorder()
srv.handleValidate(rec, httptest.NewRequest(http.MethodPost, pathValidate, nil))
assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, emitter.getEmitted(), validateMetricName)
}
func TestHandleRunEmitsMetricAndReturns200(t *testing.T) {
srv, _, _, _, emitter, _ := newTestServer()
req := httptest.NewRequest(http.MethodPost, pathRun, nil)
rec := httptest.NewRecorder()
srv.handleRun(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Contains(t, emitter.getEmitted(), runMetricName)
}
func TestHandleRunParsesInstanceID(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
body := strings.NewReader(`{"microvmId":"vm-abc123"}`)
req := httptest.NewRequest(http.MethodPost, pathRun, body)
rec := httptest.NewRecorder()
srv.handleRun(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
id := srv.instanceID.Load()
assert.Equal(t, "vm-abc123", id, "instance ID must be stored on the server for lifecycle metric tags")
}
// TestHandleRun_BodyReadError_Returns500 verifies that a body read failure
// aborts the handler before any state is mutated, rather than silently
// proceeding with a truncated/empty body. errReader is defined in
// forwarder_test.go.
func TestHandleRun_BodyReadError_Returns500(t *testing.T) {
srv, _, _, _, emitter, _ := newTestServer()
req := httptest.NewRequest(http.MethodPost, pathRun, io.NopCloser(errReader{}))
rec := httptest.NewRecorder()
srv.handleRun(rec, req)
assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.Equal(t, "", srv.instanceID.Load(), "instance ID must not be set when the body could not be read")
assert.NotContains(t, emitter.getEmitted(), runMetricName, "run metric must not be emitted when the body could not be read")
}
// TestHandleRun_OversizedBody_Returns500 verifies that a /run body exceeding
// maxRunBodyBytes is rejected instead of being buffered unbounded.
func TestHandleRun_OversizedBody_Returns500(t *testing.T) {
srv, _, _, _, emitter, _ := newTestServer()
oversized := strings.NewReader(strings.Repeat("a", int(maxRunBodyBytes)+1))
req := httptest.NewRequest(http.MethodPost, pathRun, oversized)
rec := httptest.NewRecorder()
srv.handleRun(rec, req)
assert.Equal(t, http.StatusInternalServerError, rec.Code)
assert.Equal(t, "", srv.instanceID.Load(), "instance ID must not be set when the body exceeds the cap")
assert.NotContains(t, emitter.getEmitted(), runMetricName, "run metric must not be emitted when the body exceeds the cap")
}
// TestInstanceID_EmptyBeforeRun verifies that InstanceID returns "" before
// /run fires, and the captured ID afterward — the accessor the enhanced
// metrics collector uses to attach a per-instance tag to the usage metric.
func TestInstanceID_EmptyBeforeRun(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
assert.Empty(t, srv.InstanceID(), "InstanceID must be empty before /run fires")
body := strings.NewReader(`{"microvmId":"vm-abc123"}`)
srv.handleRun(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, pathRun, body))
assert.Equal(t, "vm-abc123", srv.InstanceID())
}
// TestInstanceID_NilServer verifies InstanceID is safe to call on a nil
// *Server, mirroring the existing nil-safety of Child().
func TestInstanceID_NilServer(t *testing.T) {
var srv *Server
assert.Empty(t, srv.InstanceID())
}
// TestHandleRunWithForwarderParsesInstanceID verifies that when a forwarder is
// configured, /run still decodes the MicroVM instance ID from the request body
// before delegating to handleWithForwarder. Without the decode-then-restore fix, the
// forwarder path consumed r.Body first, so instanceID was never stored and all
// subsequent lifecycle metrics lost the instance_id tag.
func TestHandleRunWithForwarderParsesInstanceID(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
srv, _, _, _, _, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
body := strings.NewReader(`{"microvmId":"vm-fwd123"}`)
srv.handleRun(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, pathRun, body))
id := srv.instanceID.Load()
assert.Equal(t, "vm-fwd123", id, "instance ID must be stored even when forwarder is configured")
}
func TestHandleRunEmptyBodyDoesNotSetInstanceID(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
req := httptest.NewRequest(http.MethodPost, pathRun, nil)
rec := httptest.NewRecorder()
srv.handleRun(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
id := srv.instanceID.Load()
assert.Empty(t, id, "empty body must not set instance ID")
}
func TestHandleSuspendFlushesBeforeResponding(t *testing.T) {
srv, metric, trace, logs, emitter, drainer := newTestServer()
req := httptest.NewRequest(http.MethodPost, pathSuspend, nil)
rec := httptest.NewRecorder()
srv.handleSuspend(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, int32(1), metric.count.Load(), "metric agent must be flushed")
assert.Equal(t, int32(1), trace.count.Load(), "trace agent must be flushed")
assert.Equal(t, int32(1), logs.count.Load(), "logs agent must be flushed")
assert.Contains(t, emitter.getEmitted(), suspendMetricName)
assert.Equal(t, int32(1), drainer.count.Load(), "pending samples must be drained before flush")
}
func TestHandleResumeReturns200WithoutFlush(t *testing.T) {
srv, metric, trace, logs, emitter, drainer := newTestServer()
req := httptest.NewRequest(http.MethodPost, pathResume, nil)
rec := httptest.NewRecorder()
srv.handleResume(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, int32(0), metric.count.Load(), "must not flush on resume")
assert.Equal(t, int32(0), trace.count.Load())
assert.Equal(t, int32(0), logs.count.Load())
assert.Equal(t, int32(0), drainer.count.Load(), "must not drain on resume")
assert.Contains(t, emitter.getEmitted(), resumeMetricName)
}
// /terminate (no forwarder) flushes telemetry, emits the metric, and returns
// 200. After the user-app-owns-response amendment it does NOT synthesize
// SIGTERM: the platform owns process termination via OS signals delivered
// independently. This test pins both the flush and the no-SIGTERM behavior.
func TestHandleTerminate_NoForwarder_FlushesAndEmitsMetric_NoSigterm(t *testing.T) {
srv, metric, trace, logs, emitter, drainer := newTestServer()
// Register a SIGTERM watcher BEFORE invoking the handler so we can detect
// any synthetic signal that fires before or after the response.
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGTERM)
defer signal.Stop(sigCh)
req := httptest.NewRequest(http.MethodPost, pathTerminate, nil)
rec := httptest.NewRecorder()
srv.handleTerminate(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, int32(1), metric.count.Load(), "metric agent must be flushed")
assert.Equal(t, int32(1), trace.count.Load())
assert.Equal(t, int32(1), logs.count.Load())
assert.Contains(t, emitter.getEmitted(), terminateMetricName)
assert.Equal(t, int32(1), drainer.count.Load(), "pending samples must be drained before flush")
// No SIGTERM should reach the test process within a reasonable window.
// 100ms is generous: today's removed code runed the syscall in a
// fire-and-forget goroutine that fires immediately after WriteHeader.
select {
case sig := <-sigCh:
t.Fatalf("/terminate must not synthesize SIGTERM after the user-app-owns-response amendment; got %v", sig)
case <-time.After(100 * time.Millisecond):
// Pass — no synthetic signal observed.
}
}
// TestEmittedMetricsCarryCurrentTimestamp verifies the lifecycle handlers pass
// a current Unix-seconds timestamp to AddEnhancedMetric rather than the `0`
// sentinel that defers timestamp assignment to the metric agent. The window
// check also guards against unit regressions (e.g. ms vs. s).
func TestEmittedMetricsCarryCurrentTimestamp(t *testing.T) {
srv, _, _, _, emitter, _ := newTestServer()
before := float64(time.Now().UnixNano()) / float64(time.Second)
rec := httptest.NewRecorder()
srv.handleRun(rec, httptest.NewRequest(http.MethodPost, pathRun, nil))
after := float64(time.Now().UnixNano()) / float64(time.Second)
emitted := emitter.getEmittedMetrics()
require.Len(t, emitted, 1)
ts := emitted[0].timestamp
assert.Greater(t, ts, 0.0, "timestamp must not be the 0 sentinel")
assert.GreaterOrEqual(t, ts, before, "timestamp must be at or after pre-call time")
assert.LessOrEqual(t, ts, after, "timestamp must be at or before post-call time")
}
// TestEmittedMetricsCarryCurrentTimestamp_ForwarderPath verifies the same
// timestamp guarantee for the handleWithForwarder code path (forwarder enabled).
// handleWithForwarder runs metric emission in a goroutine but joins before the
// handler returns, so the before/after window technique still applies.
func TestEmittedMetricsCarryCurrentTimestamp_ForwarderPath(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
srv, _, _, _, emitter, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
before := float64(time.Now().UnixNano()) / float64(time.Second)
srv.handleRun(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, pathRun, nil))
after := float64(time.Now().UnixNano()) / float64(time.Second)
emitted := emitter.getEmittedMetrics()
require.Len(t, emitted, 1)
ts := emitted[0].timestamp
assert.Greater(t, ts, 0.0, "timestamp must not be the 0 sentinel")
assert.GreaterOrEqual(t, ts, before, "timestamp must be at or after pre-call time")
assert.LessOrEqual(t, ts, after, "timestamp must be at or before post-call time")
}
func TestRoutes(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
// /ready needs an alive child handle to return 200; the other hooks
// ignore childHandle when no forwarder is configured.
h := newFakeChildHandle()
h.alive.Store(true)
srv.childHandle = h
routes := []string{pathReady, pathValidate, pathRun, pathSuspend, pathResume, pathTerminate}
handler := srv.handler()
for _, route := range routes {
req := httptest.NewRequest(http.MethodPost, route, nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, "route %s should return 200", route)
}
}
// TestRoutes_NonPost_Returns405 verifies that the mux rejects non-POST requests
// with 405 Method Not Allowed. All lifecycle hooks are POST-only; the platform
// never sends GET/PUT/DELETE to these paths.
func TestRoutes_NonPost_Returns405(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
handler := srv.handler()
routes := []string{pathReady, pathValidate, pathRun, pathSuspend, pathResume, pathTerminate}
for _, route := range routes {
req := httptest.NewRequest(http.MethodGet, route, nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
require.Equal(t, http.StatusMethodNotAllowed, rec.Code, "route %s must reject GET with 405", route)
}
}
// fakeChildHandle drives /ready behavior in tests.
type fakeChildHandle struct {
alive atomic.Bool
}
func newFakeChildHandle() *fakeChildHandle { return &fakeChildHandle{} }
func (f *fakeChildHandle) IsAlive() bool { return f.alive.Load() }
func TestHandleReady_NoForwarder_ChildAlive_Returns200(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
h := newFakeChildHandle()
h.alive.Store(true)
srv.childHandle = h
rec := httptest.NewRecorder()
srv.handleReady(rec, httptest.NewRequest(http.MethodPost, pathReady, nil))
assert.Equal(t, http.StatusOK, rec.Code)
}
func TestHandleReady_NoForwarder_ChildNotAlive_Returns503(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
srv.childHandle = newFakeChildHandle() // alive=false (default)
rec := httptest.NewRecorder()
srv.handleReady(rec, httptest.NewRequest(http.MethodPost, pathReady, nil))
assert.Equal(t, http.StatusServiceUnavailable, rec.Code)
}
func TestHandleReady_WithForwarder_PassesThrough(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/x-ready")
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`{"ready":false,"reason":"warming"}`))
}))
defer upstream.Close()
srv, _, _, _, _, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
readyTimeout: 200 * time.Millisecond,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleReady(rec, httptest.NewRequest(http.MethodPost, pathReady, nil))
assert.Equal(t, http.StatusServiceUnavailable, rec.Code)
// /ready must mirror the user app's Content-Type AND body, not just the
// status code. The platform may surface the user-app reason string in
// readiness diagnostics; dropping body/Content-Type would silently
// hide that.
assert.Equal(t, "application/x-ready", rec.Header().Get("Content-Type"))
assert.Equal(t, `{"ready":false,"reason":"warming"}`, rec.Body.String())
}
// /run with a forwarder configured mirrors the user-app's status code,
// body, and Content-Type, and emits the run metric. Replaces the prior
// fire-and-forget contract.
func TestHandleRun_WithForwarder_MirrorsUserAppResponse(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/x-run")
w.WriteHeader(207)
_, _ = w.Write([]byte(`{"warmed":true}`))
}))
defer upstream.Close()
srv, metric, trace, logs, emitter, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleRun(rec, httptest.NewRequest(http.MethodPost, pathRun, nil))
assert.Equal(t, 207, rec.Code, "must mirror user-app status, not hardcoded 200")
assert.Equal(t, "application/x-run", rec.Header().Get("Content-Type"))
assert.Equal(t, `{"warmed":true}`, rec.Body.String())
assert.Contains(t, emitter.getEmitted(), runMetricName)
// /run does NOT flush — these are no-op for run/resume.
assert.Equal(t, int32(0), metric.count.Load(), "run must not flush")
assert.Equal(t, int32(0), trace.count.Load())
assert.Equal(t, int32(0), logs.count.Load())
}
// /resume with a forwarder configured mirrors the user-app's response and
// does NOT flush.
func TestHandleResume_WithForwarder_MirrorsUserAppResponse(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(418)
}))
defer upstream.Close()
srv, metric, trace, logs, emitter, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleResume(rec, httptest.NewRequest(http.MethodPost, pathResume, nil))
assert.Equal(t, 418, rec.Code)
assert.Contains(t, emitter.getEmitted(), resumeMetricName)
assert.Equal(t, int32(0), metric.count.Load(), "resume must not flush")
assert.Equal(t, int32(0), trace.count.Load())
assert.Equal(t, int32(0), logs.count.Load())
}
// /terminate with a forwarder configured mirrors the user-app's response,
// emits the terminate metric, AND flushes telemetry. After the amendment,
// /terminate also no longer synthesizes a SIGTERM (separate test).
func TestHandleTerminate_WithForwarder_MirrorsUserAppResponse(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(503)
}))
defer upstream.Close()
srv, metric, trace, logs, emitter, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleTerminate(rec, httptest.NewRequest(http.MethodPost, pathTerminate, nil))
assert.Equal(t, 503, rec.Code, "must mirror user-app status, not hardcoded 200")
assert.Contains(t, emitter.getEmitted(), terminateMetricName)
assert.Equal(t, int32(1), metric.count.Load(), "terminate must flush")
assert.Equal(t, int32(1), trace.count.Load())
assert.Equal(t, int32(1), logs.count.Load())
}
// When a forwarder is configured, /suspend must mirror the user app's
// status code, body, and Content-Type back to the platform — not the
// agent's previous hardcoded 200. This is the core behavior change of
// the user-app-owns-response amendment.
func TestHandleSuspend_WithForwarder_MirrorsUserAppResponse(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/x-suspend")
w.WriteHeader(207) // distinctive status to rule out any agent default
_, _ = w.Write([]byte(`{"drained":true}`))
}))
defer upstream.Close()
srv, metric, trace, logs, emitter, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleSuspend(rec, httptest.NewRequest(http.MethodPost, pathSuspend, nil))
assert.Equal(t, 207, rec.Code, "must mirror user-app status, not hardcoded 200")
assert.Equal(t, "application/x-suspend", rec.Header().Get("Content-Type"))
assert.Equal(t, `{"drained":true}`, rec.Body.String())
// Side-effect path still runs alongside the pass-through.
assert.Equal(t, int32(1), metric.count.Load(), "metric flush must still run")
assert.Equal(t, int32(1), trace.count.Load(), "trace flush must still run")
assert.Equal(t, int32(1), logs.count.Load(), "logs flush must still run")
assert.Contains(t, emitter.getEmitted(), suspendMetricName, "metric must still be emitted")
}
// Parallelism pin: the upstream handler blocks until all three flush mocks
// have signaled completion, then responds. A sequential "forward then flush"
// implementation would deadlock this handler (flush never runs until the
// forward it's waiting on returns) and the test would fail via timeout rather
// than a flaky sleep-based race. (A "flush then forward" implementation would
// also pass, but that variant is benign: still bounded, telemetry still
// flushes — just slower. This only catches the correctness-violating
// ordering.)
func TestHandleSuspend_WithForwarder_FlushCompletesBeforeForwardReturns(t *testing.T) {
flushesDone := make(chan struct{}, flushWorkerCount)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
for i := 0; i < flushWorkerCount; i++ {
select {
case <-flushesDone:
case <-time.After(2 * time.Second):
t.Errorf("timed out waiting for flush #%d to complete before the forward returned", i+1)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
w.WriteHeader(200)
}))
defer upstream.Close()
srv, metric, trace, logs, _, _ := newTestServer()
signal := func() { flushesDone <- struct{}{} }
metric.onFlush = signal
trace.onFlush = signal
logs.onFlush = signal
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleSuspend(rec, httptest.NewRequest(http.MethodPost, pathSuspend, nil))
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, int32(1), metric.count.Load())
assert.Equal(t, int32(1), trace.count.Load())
assert.Equal(t, int32(1), logs.count.Load())
}
// Dial-error pin: when the user app is not listening, /suspend returns 503
// (mirrored from the Forwarder's error stub) AND all three flushers were
// invoked anyway. This guards against an implementation that conditioned
// the side-effect path on the forward succeeding.
func TestHandleSuspend_WithForwarder_DialErrorStillRunsFlush(t *testing.T) {
srv, metric, trace, logs, _, _ := newTestServer()
srv.fwd = &Forwarder{
target: "http://127.0.0.1:1", // unbound port → dial error
client: &http.Client{},
forwardTimeout: 200 * time.Millisecond,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleSuspend(rec, httptest.NewRequest(http.MethodPost, pathSuspend, nil))
assert.Equal(t, http.StatusServiceUnavailable, rec.Code, "must mirror the Forwarder's 503 error stub")
assert.Equal(t, int32(1), metric.count.Load(), "metric flush must run even on forward dial error")
assert.Equal(t, int32(1), trace.count.Load(), "trace flush must run even on forward dial error")
assert.Equal(t, int32(1), logs.count.Load(), "logs flush must run even on forward dial error")
}
func TestHandleSuspend_WithForwarder_WaitsForForwardBeforeResponse(t *testing.T) {
forwardEntered := make(chan struct{})
releaseForward := make(chan struct{})
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
close(forwardEntered)
<-releaseForward
w.WriteHeader(200)
}))
defer upstream.Close()
srv, metric, trace, logs, _, _ := newTestServer()
srv.fwd = &Forwarder{target: upstream.URL, client: &http.Client{}, forwardTimeout: 5 * time.Second}
handlerReturned := make(chan struct{})
rec := httptest.NewRecorder()
go func() {
srv.handleSuspend(rec, httptest.NewRequest(http.MethodPost, pathSuspend, nil))
close(handlerReturned)
}()
<-forwardEntered
// Forward is mid-flight; handleSuspend must not have returned yet.
select {
case <-handlerReturned:
t.Fatal("handleSuspend returned before forward completed")
case <-time.After(50 * time.Millisecond):
}
close(releaseForward)
<-handlerReturned
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, int32(1), metric.count.Load())
assert.Equal(t, int32(1), trace.count.Load())
assert.Equal(t, int32(1), logs.count.Load())
}
// flushAll uses waitForFlushes to bound how long it waits for the metric,
// trace, and logs flushers. When a flusher exceeds flushTimeout, the handler
// MUST return promptly rather than blocking the platform's lifecycle window.
// This test pins the early-return path: a 50ms flushTimeout against a 1s
// flusher must not extend the handler's wall-clock past flushTimeout + ε.
//
// Without the timeout branch, /suspend and /terminate would block until the
// slowest flusher returned, potentially exceeding the platform's
// /terminate 60s deadline and getting the VM destroyed mid-flush.
func TestHandleSuspend_NoForwarder_FlushTimeout_ReturnsPromptly(t *testing.T) {
srv, _, _, logs, _, _ := newTestServer()
srv.flushTimeout = 50 * time.Millisecond
// Replace the logs flusher with one that ignores the context and
// blocks for far longer than flushTimeout. This is the realistic
// shape of a slow downstream — fail-soft on timeout, don't block.
slow := &slowLogsFlusher{block: 1 * time.Second}
srv.logsFlusher = slow
_ = logs // unused but documented in the test signature
start := time.Now()
rec := httptest.NewRecorder()
srv.handleSuspend(rec, httptest.NewRequest(http.MethodPost, pathSuspend, nil))
elapsed := time.Since(start)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Less(t, elapsed, 500*time.Millisecond,
"handler must return promptly when flushTimeout fires (≪ slow flusher's 1s)")
}
type slowLogsFlusher struct {
block time.Duration
}
func (s *slowLogsFlusher) Flush(_ context.Context) {
time.Sleep(s.block)
}
// When a forwarder is configured and the flush goroutine exceeds flushTimeout,
// handleSuspend must still return promptly. The flush runs concurrently with
// PassThrough inside handleWithForwarder; flushAll's waitForFlushes honours the
// timeout and closes sideDone so the handler is not blocked on the slow flusher.
func TestHandleSuspend_WithForwarder_FlushTimeout_ReturnsPromptly(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
srv, _, _, _, _, _ := newTestServer()
srv.flushTimeout = 50 * time.Millisecond
srv.logsFlusher = &slowLogsFlusher{block: 1 * time.Second}
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
start := time.Now()
rec := httptest.NewRecorder()
srv.handleSuspend(rec, httptest.NewRequest(http.MethodPost, pathSuspend, nil))
elapsed := time.Since(start)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Less(t, elapsed, 500*time.Millisecond,
"handleSuspend with forwarder must return promptly when flush times out (≪ slow flusher's 1s)")
}
// TestHandleSuspend_WithForwarder_BodyBufferedBeforeFlush verifies that the
// response body from the user app is fully mirrored even when the parallel
// flush runs past the point where the forwardTimeout context would have
// expired. Without buffering, the forwardTimeout context deadline fires
// while flushAll is still running, cancels the underlying TCP connection,
// and mirrorResponse reads an empty or partial body. With buffering the body
// is read immediately after PassThrough returns — while the context is
// still alive — so mirrorResponse reads from an in-memory buffer that is
// context-independent.
func TestHandleSuspend_WithForwarder_BodyBufferedBeforeFlush(t *testing.T) {
// Larger than the transport's read-ahead buffer so the client cannot fully
// receive the body in the single read that happens while parsing headers —
// finishing the read requires an additional network read against the
// connection, which is what the forwardTimeout context cancellation breaks
// when the read is delayed until after the flush.
wantBody := strings.Repeat("A", 256*1024)
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, wantBody)
}))
defer upstream.Close()
srv, _, _, _, _, _ := newTestServer()
// flushTimeout is longer than forwardTimeout so the parallel flush runs
// past the point where the forwardTimeout context would have expired.
srv.flushTimeout = 200 * time.Millisecond
srv.logsFlusher = &slowLogsFlusher{block: 150 * time.Millisecond}
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
// forwardTimeout is short: expires during the flush, which means the
// cancelOnCloseReader's context deadline fires before mirrorResponse
// reads the body — unless the body was already buffered.
forwardTimeout: 100 * time.Millisecond,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleSuspend(rec, httptest.NewRequest(http.MethodPost, pathSuspend, nil))
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, wantBody, rec.Body.String(),
"response body must be fully mirrored even after parallel flush runs past forwardTimeout")
}
// Same as TestHandleSuspend_WithForwarder_FlushTimeout_ReturnsPromptly but for
// /terminate, which also calls handleWithForwarder with flushSequential.
func TestHandleTerminate_WithForwarder_FlushTimeout_ReturnsPromptly(t *testing.T) {
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer upstream.Close()
srv, _, _, _, _, _ := newTestServer()
srv.flushTimeout = 50 * time.Millisecond
srv.logsFlusher = &slowLogsFlusher{block: 1 * time.Second}
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 2 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
start := time.Now()
rec := httptest.NewRecorder()
srv.handleTerminate(rec, httptest.NewRequest(http.MethodPost, pathTerminate, nil))
elapsed := time.Since(start)
assert.Equal(t, http.StatusOK, rec.Code)
assert.Less(t, elapsed, 500*time.Millisecond,
"handleTerminate with forwarder must return promptly when flush times out (≪ slow flusher's 1s)")
}
// TestHandleTerminate_WithForwarder_BodyBufferedBeforeFlush verifies that the
// response body from the user app is fully mirrored even when the sequential
// flush runs after PassThrough returns and the forwardTimeout context expires
// during the flush. Without buffering, the forwardTimeout context deadline
// fires mid-flush, cancels the underlying TCP connection, and mirrorResponse
// reads an empty or partial body. With buffering the body is read immediately
// after PassThrough returns — while the context is still alive — so
// mirrorResponse reads from an in-memory buffer that is context-independent.
func TestHandleTerminate_WithForwarder_BodyBufferedBeforeFlush(t *testing.T) {
const wantBody = "terminate-response-body"
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, wantBody)
}))
defer upstream.Close()
srv, _, _, _, _, _ := newTestServer()
// flushTimeout is longer than forwardTimeout so the sequential flush runs
// past the point where the forwardTimeout context would have expired.
srv.flushTimeout = 200 * time.Millisecond
srv.logsFlusher = &slowLogsFlusher{block: 150 * time.Millisecond}
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
// forwardTimeout is short: expires during the flush, which means the
// cancelOnCloseReader's context deadline fires before mirrorResponse
// reads the body — unless the body was already buffered.
forwardTimeout: 100 * time.Millisecond,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
rec := httptest.NewRecorder()
srv.handleTerminate(rec, httptest.NewRequest(http.MethodPost, pathTerminate, nil))
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, wantBody, rec.Body.String(),
"response body must be fully mirrored even after sequential flush runs past forwardTimeout")
}
// /terminate with a forwarder waits for the user-app forward to complete
// before responding. Without this wait, /terminate's parallel
// flush-then-mirror would race against the platform's destruction of the VM
// at WriteHeader time.
func TestHandleTerminate_WithForwarder_WaitsForSlowForward(t *testing.T) {
forwardEntered := make(chan struct{})
releaseForward := make(chan struct{})
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
close(forwardEntered)
<-releaseForward
w.WriteHeader(200)
}))
defer upstream.Close()
srv, _, _, _, _, _ := newTestServer()
srv.fwd = &Forwarder{
target: upstream.URL,
client: &http.Client{},
forwardTimeout: 5 * time.Second,
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
handlerReturned := make(chan struct{})
rec := httptest.NewRecorder()
go func() {
srv.handleTerminate(rec, httptest.NewRequest(http.MethodPost, pathTerminate, nil))
close(handlerReturned)
}()
<-forwardEntered
// Forward is mid-flight inside the upstream handler. handleTerminate MUST
// NOT have returned yet — that would mean it skipped the forward wait.
select {
case <-handlerReturned:
t.Fatal("handleTerminate returned before forward completed")
case <-time.After(50 * time.Millisecond):
// Good — handler is correctly blocked on the forward.
}
close(releaseForward)
<-handlerReturned
assert.Equal(t, http.StatusOK, rec.Code, "must mirror user-app's 200")
}
// Stop on a nil *Server is safe so callers can defer Stop unconditionally —
// the contract main.go's defer chain depends on for non-MicroVM modes.
func TestStopOnNilServerReturnsNil(t *testing.T) {
var srv *Server
require.NoError(t, srv.Stop(context.Background()))
}
// Stop on a constructed-but-never-Started server is also safe — http.Server.Shutdown
// is documented to return immediately when there are no listeners.
func TestStopWithoutStartReturnsNil(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
require.NoError(t, srv.Stop(ctx))
}
// TestServeAndStopGracefulShutdown exercises the real HTTP server lifecycle.
// It binds a listener on a random free port, serves until Stop is called,
// and verifies that Serve returns http.ErrServerClosed — the contract that
// lets main.go's defer chain run cleanly when shutdown is triggered externally.
func TestServeAndStopGracefulShutdown(t *testing.T) {
srv, _, _, _, _, _ := newTestServer()
// /ready needs an alive child handle to return 200; without one the
// handler returns 503, but Serve+Stop semantics are independent of the
// route's reply, so injecting an alive handle keeps the smoke check meaningful.
h := newFakeChildHandle()
h.alive.Store(true)
srv.childHandle = h
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
serverDone := make(chan struct{})
go func() {
srv.Serve(listener)
close(serverDone)
}()
resp, err := http.Post("http://"+listener.Addr().String()+pathReady, "", nil)
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
require.Equal(t, http.StatusOK, resp.StatusCode)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
require.NoError(t, srv.Stop(ctx))
select {
case <-serverDone:
// Serve returned after Stop — correct.
case <-time.After(2 * time.Second):
t.Fatal("Serve did not return after Stop")
}
}
// TestNewServerConfiguresHTTPTimeouts verifies that NewServer sets ReadTimeout and
// WriteTimeout on the underlying http.Server.
//
// Without a forwarder, WriteTimeout is flushTimeout+writeTimeoutHeadroom (flush
// budget + heartbeat.Stop() + write headroom). The forwarder case (WriteTimeout
// sized to forwardTimeout+flushTimeout) is covered by
// TestNewServerWithForwarderWriteTimeoutCoversForwardBudget below.
func TestNewServerConfiguresHTTPTimeouts(t *testing.T) {
flushTimeout := 5 * time.Second
srv := NewServer(0, &mockFlusher{}, &mockFlusher{}, &mockLogsAgent{}, &mockMetricEmitter{}, &mockSampleDrainer{}, metrics.MetricSourceAWSMicroVMEnhanced, flushTimeout, nil, nil, nil)
assert.Equal(t, 30*time.Second, srv.httpServer.ReadTimeout)
assert.Equal(t, flushTimeout+writeTimeoutHeadroom, srv.httpServer.WriteTimeout)
}
// TestNewServerWithForwarderWriteTimeoutCoversForwardBudget verifies that when a
// Forwarder is configured, WriteTimeout accounts for the /terminate sequential
// flush path whose wall-clock is forwardTimeout+flushTimeout. This prevents the
// HTTP server from closing the platform-facing connection before the handler
// finishes forwarding and flushing.
func TestNewServerWithForwarderWriteTimeoutCoversForwardBudget(t *testing.T) {
flushTimeout := 5 * time.Second
fwd := &Forwarder{
forwardTimeout: 30 * time.Second,
client: &http.Client{},
maxResponseBodyBytes: defaultMaxResponseBodyBytes,
}
srv := NewServer(0, &mockFlusher{}, &mockFlusher{}, &mockLogsAgent{}, &mockMetricEmitter{}, &mockSampleDrainer{}, metrics.MetricSourceAWSMicroVMEnhanced, flushTimeout, nil, fwd, nil)
assert.Equal(t, fwd.forwardTimeout+flushTimeout+writeTimeoutHeadroom, srv.httpServer.WriteTimeout,
"WriteTimeout must cover forwardTimeout+flushTimeout (terminate sequential-flush path)")
}
// TestInstanceIDTagAppearsInMetricsAfterRun verifies that once /run stores a
// MicroVM instance ID, subsequent lifecycle metrics include lambda_microvm_id:<id> as
// an extra tag. This is the primary tagging path for identifying individual MicroVM
// instances in lifecycle metrics.
func TestInstanceIDTagAppearsInMetricsAfterRun(t *testing.T) {
srv, _, _, _, emitter, _ := newTestServer()
body := strings.NewReader(`{"microvmId":"vm-abc123"}`)
srv.handleRun(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, pathRun, body))
// Suspend after run — the suspend metric must carry the instance_id tag.
srv.handleSuspend(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, pathSuspend, nil))
emitted := emitter.getEmittedMetrics()
var found *emittedMetric
for i := range emitted {
if emitted[i].name == suspendMetricName {
found = &emitted[i]
break
}
}
require.NotNil(t, found, "suspend metric must be emitted")
assert.Contains(t, found.extraTags, lambdaMicroVMID+"vm-abc123")
}
// errorReader is a helper io.Reader that always returns the provided error.
// Used to simulate a body read failure in mirrorResponse tests.
type errorReader struct{ err error }
func (e *errorReader) Read(_ []byte) (int, error) { return 0, e.err }
// TestMirrorResponse_CopiesStatusContentTypeAndBody verifies the happy path:
// status code, Content-Type, and body are all forwarded to the platform.
func TestMirrorResponse_CopiesStatusContentTypeAndBody(t *testing.T) {
resp := &http.Response{
StatusCode: 207,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"ok":true}`)),
}
rec := httptest.NewRecorder()
mirrorResponse(rec, resp)
assert.Equal(t, 207, rec.Code)
assert.Equal(t, "application/json", rec.Header().Get("Content-Type"))
assert.Equal(t, `{"ok":true}`, rec.Body.String())
}
// TestMirrorResponse_NoContentType_HeaderOmitted verifies that an absent
// Content-Type in the upstream response is not forwarded (no sniff-trigger).
func TestMirrorResponse_NoContentType_HeaderOmitted(t *testing.T) {
resp := &http.Response{
StatusCode: 200,
Header: http.Header{},
Body: io.NopCloser(strings.NewReader("")),