-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathcloudwatch_test.go
More file actions
240 lines (214 loc) · 7.32 KB
/
Copy pathcloudwatch_test.go
File metadata and controls
240 lines (214 loc) · 7.32 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
package lifecycled
import (
"context"
"errors"
"io"
"strings"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
cwltypes "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
"github.com/aws/smithy-go"
"github.com/sirupsen/logrus"
)
type fakeCloudWatchLogsClient struct {
mu sync.Mutex
createdGroups []string
createdStreams []string
putInputs []*cloudwatchlogs.PutLogEventsInput
groupErr error
streamErr error
putErr error
lastDeadline time.Time
lastHasDeadline bool
}
func (c *fakeCloudWatchLogsClient) CreateLogGroup(_ context.Context, in *cloudwatchlogs.CreateLogGroupInput, _ ...func(*cloudwatchlogs.Options)) (*cloudwatchlogs.CreateLogGroupOutput, error) {
c.createdGroups = append(c.createdGroups, aws.ToString(in.LogGroupName))
return &cloudwatchlogs.CreateLogGroupOutput{}, c.groupErr
}
func (c *fakeCloudWatchLogsClient) CreateLogStream(_ context.Context, in *cloudwatchlogs.CreateLogStreamInput, _ ...func(*cloudwatchlogs.Options)) (*cloudwatchlogs.CreateLogStreamOutput, error) {
c.createdStreams = append(c.createdStreams, aws.ToString(in.LogStreamName))
return &cloudwatchlogs.CreateLogStreamOutput{}, c.streamErr
}
func (c *fakeCloudWatchLogsClient) PutLogEvents(ctx context.Context, in *cloudwatchlogs.PutLogEventsInput, _ ...func(*cloudwatchlogs.Options)) (*cloudwatchlogs.PutLogEventsOutput, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.putInputs = append(c.putInputs, in)
c.lastDeadline, c.lastHasDeadline = ctx.Deadline()
return &cloudwatchlogs.PutLogEventsOutput{}, c.putErr
}
func TestNewCloudWatchLogsHook(t *testing.T) {
exists := &cwltypes.ResourceAlreadyExistsException{Message: aws.String("exists")}
tests := []struct {
name string
groupErr error
streamErr error
wantErr bool
}{
{
name: "creates group and stream",
},
{
name: "tolerates pre-existing group and stream",
groupErr: exists,
streamErr: exists,
},
{
// Externally-managed log group + no logs:CreateLogGroup permission must
// not be fatal; CreateLogStream still gates a genuinely missing group.
name: "tolerates access denied on group",
groupErr: &smithy.GenericAPIError{Code: "AccessDeniedException", Message: "no perms"},
},
{
name: "propagates other group errors",
groupErr: errors.New("boom"),
wantErr: true,
},
{
// A pre-provisioned stream + a role without logs:CreateLogStream must not
// be fatal, mirroring the group tolerance above.
name: "tolerates access denied on stream",
streamErr: &smithy.GenericAPIError{Code: "AccessDeniedException", Message: "no perms"},
},
{
name: "propagates other stream errors",
streamErr: errors.New("access denied"),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &fakeCloudWatchLogsClient{groupErr: tt.groupErr, streamErr: tt.streamErr}
hook, err := NewCloudWatchLogsHook(context.Background(), client, "group", "stream")
if tt.wantErr {
if err == nil {
t.Fatal("expected an error, got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if hook == nil {
t.Fatal("expected a hook, got nil")
}
if got := client.createdGroups; len(got) != 1 || got[0] != "group" {
t.Errorf("created groups = %v, want [group]", got)
}
if got := client.createdStreams; len(got) != 1 || got[0] != "stream" {
t.Errorf("created streams = %v, want [stream]", got)
}
})
}
}
func TestCloudWatchLogsHookFireError(t *testing.T) {
sentinel := errors.New("put failed")
client := &fakeCloudWatchLogsClient{putErr: sentinel}
hook, err := NewCloudWatchLogsHook(context.Background(), client, "group", "stream")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
entry := logrus.NewEntry(logrus.New())
entry.Message = "boom"
if err := hook.Fire(entry); !errors.Is(err, sentinel) {
t.Errorf("Fire() error = %v, want %v", err, sentinel)
}
}
func TestCloudWatchLogsHookFire(t *testing.T) {
client := &fakeCloudWatchLogsClient{}
hook, err := NewCloudWatchLogsHook(context.Background(), client, "group", "stream")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
logger := logrus.New()
logger.SetOutput(io.Discard)
logger.AddHook(hook)
logger.Info("hello cloudwatch")
if len(client.putInputs) != 1 {
t.Fatalf("PutLogEvents calls = %d, want 1", len(client.putInputs))
}
in := client.putInputs[0]
if got := aws.ToString(in.LogGroupName); got != "group" {
t.Errorf("log group = %q, want %q", got, "group")
}
if got := aws.ToString(in.LogStreamName); got != "stream" {
t.Errorf("log stream = %q, want %q", got, "stream")
}
if len(in.LogEvents) != 1 {
t.Fatalf("log events = %d, want 1", len(in.LogEvents))
}
event := in.LogEvents[0]
if !strings.Contains(aws.ToString(event.Message), "hello cloudwatch") {
t.Errorf("event message = %q, want it to contain %q", aws.ToString(event.Message), "hello cloudwatch")
}
if aws.ToInt64(event.Timestamp) <= 0 {
t.Errorf("event timestamp = %d, want > 0", aws.ToInt64(event.Timestamp))
}
}
// Fire bounds delivery with a timeout so an unreachable endpoint can't wedge it.
func TestCloudWatchLogsHookFireAppliesTimeout(t *testing.T) {
client := &fakeCloudWatchLogsClient{}
hook, err := NewCloudWatchLogsHook(context.Background(), client, "group", "stream")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
entry := logrus.NewEntry(logrus.New())
entry.Message = "boom"
if err := hook.Fire(entry); err != nil {
t.Fatalf("Fire() error = %v", err)
}
if !client.lastHasDeadline {
t.Fatal("PutLogEvents context had no deadline; Fire must bound delivery with a timeout")
}
if remaining := time.Until(client.lastDeadline); remaining <= 0 || remaining > 5*time.Second {
t.Errorf("deadline remaining = %s, want within (0, 5s]", remaining)
}
}
// Concurrent Fire calls (the daemon runs several listeners) must all be delivered.
func TestCloudWatchLogsHookFireConcurrent(t *testing.T) {
client := &fakeCloudWatchLogsClient{}
hook, err := NewCloudWatchLogsHook(context.Background(), client, "group", "stream")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
const n = 50
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
entry := logrus.NewEntry(logrus.New())
entry.Message = "concurrent"
entry.Time = time.Now()
if err := hook.Fire(entry); err != nil {
t.Errorf("Fire() error = %v", err)
}
}()
}
wg.Wait()
if len(client.putInputs) != n {
t.Errorf("PutLogEvents calls = %d, want %d", len(client.putInputs), n)
}
}
// A hand-built entry has a zero Time; Fire must fall back to now rather than
// sending a negative timestamp AWS would reject.
func TestCloudWatchLogsHookFireZeroTime(t *testing.T) {
client := &fakeCloudWatchLogsClient{}
hook, err := NewCloudWatchLogsHook(context.Background(), client, "group", "stream")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
entry := logrus.NewEntry(logrus.New())
entry.Message = "boom"
if err := hook.Fire(entry); err != nil {
t.Fatalf("Fire() error = %v", err)
}
if len(client.putInputs) != 1 {
t.Fatalf("PutLogEvents calls = %d, want 1", len(client.putInputs))
}
if got := aws.ToInt64(client.putInputs[0].LogEvents[0].Timestamp); got <= 0 {
t.Errorf("timestamp = %d, want > 0 (zero entry.Time should fall back to now)", got)
}
}