forked from newrelic/newrelic-lambda-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
351 lines (295 loc) · 11.1 KB
/
main.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
348
349
350
351
package main
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/newrelic/newrelic-lambda-extension/checks"
"github.com/newrelic/newrelic-lambda-extension/lambda/logserver"
"github.com/newrelic/newrelic-lambda-extension/util"
"github.com/newrelic/newrelic-lambda-extension/config"
"github.com/newrelic/newrelic-lambda-extension/credentials"
"github.com/newrelic/newrelic-lambda-extension/lambda/extension/api"
"github.com/newrelic/newrelic-lambda-extension/lambda/extension/client"
"github.com/newrelic/newrelic-lambda-extension/telemetry"
)
var (
invokedFunctionARN string
lastEventStart time.Time
lastRequestId string
rootCtx context.Context
)
func init() {
rootCtx = context.Background()
}
func main() {
extensionStartup := time.Now()
ctx, cancel := context.WithCancel(rootCtx)
defer cancel()
// exit cleanly on SIGTERM or SIGINT
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
go func() {
s := <-sigs
cancel()
util.Logf("Received %v Exiting", s)
}()
// Allow extension to be interrupted with CTRL-C
ctrlCChan := make(chan os.Signal, 1)
signal.Notify(ctrlCChan, os.Interrupt)
go func() {
for range ctrlCChan {
cancel()
util.Fatal("Exiting...")
}
}()
// Parse various env vars for our config
conf := config.ConfigurationFromEnvironment()
// Optionally enable debug logging, disabled by default
util.ConfigLogger(conf.LogsEnabled, conf.LogLevel == config.DebugLogLevel)
// Extensions must register
registrationClient := client.New(http.Client{})
regReq := api.RegistrationRequest{
Events: []api.LifecycleEvent{api.Invoke, api.Shutdown},
}
invocationClient, registrationResponse, err := registrationClient.Register(ctx, regReq)
if err != nil {
util.Panic(err)
}
// If extension disabled, go into no op mode
if !conf.ExtensionEnabled {
util.Logln("Extension telemetry processing disabled")
noopLoop(ctx, invocationClient)
return
}
// Attempt to find the license key for telemetry sending
licenseKey, err := credentials.GetNewRelicLicenseKey(ctx, conf)
if err != nil {
util.Logln("Failed to retrieve New Relic license key", err)
// We fail open; telemetry will go to CloudWatch instead
noopLoop(ctx, invocationClient)
return
}
// Set up the telemetry buffer
batch := telemetry.NewBatch(int64(conf.RipeMillis), int64(conf.RotMillis), conf.CollectTraceID)
// Start the Logs API server, and register it
logServer, err := logserver.Start(conf)
if err != nil {
err2 := invocationClient.InitError(ctx, "logServer.start", err)
if err2 != nil {
util.Logln(err2)
}
util.Panic("Failed to start logs HTTP server", err)
}
eventTypes := []api.LogEventType{api.Platform}
if conf.SendFunctionLogs {
eventTypes = append(eventTypes, api.Function)
}
subscriptionRequest := api.DefaultLogSubscription(eventTypes, logServer.Port())
err = invocationClient.LogRegister(ctx, subscriptionRequest)
if err != nil {
err2 := invocationClient.InitError(ctx, "logServer.register", err)
if err2 != nil {
util.Logln(err2)
}
util.Panic("Failed to register with Logs API", err)
}
// Init the telemetry sending client
telemetryClient := telemetry.New(registrationResponse.FunctionName, licenseKey, conf.TelemetryEndpoint, conf.LogEndpoint, batch, conf.CollectTraceID, conf.ClientTimeout)
telemetryChan, err := telemetry.InitTelemetryChannel()
if err != nil {
err2 := invocationClient.InitError(ctx, "telemetryClient.init", err)
if err2 != nil {
util.Logln(err2)
}
util.Panic("telemetry pipe init failed: ", err)
}
// Run startup checks
go func() {
checks.RunChecks(ctx, conf, registrationResponse, telemetryClient)
}()
// Send function logs as they arrive. When disabled, function logs aren't delivered to the extension.
backgroundTasks := &sync.WaitGroup{}
backgroundTasks.Add(1)
go func() {
defer backgroundTasks.Done()
logShipLoop(ctx, logServer, telemetryClient)
}()
// Call next, and process telemetry, until we're shut down
eventCounter := mainLoop(ctx, invocationClient, batch, telemetryChan, logServer, telemetryClient)
util.Logf("New Relic Extension shutting down after %v events\n", eventCounter)
err = logServer.Close()
if err != nil {
util.Logln("Error shutting down Log API server", err)
}
pollLogServer(logServer, batch)
finalHarvest := batch.Close()
shipHarvest(ctx, finalHarvest, telemetryClient)
util.Debugln("Waiting for background tasks to complete")
backgroundTasks.Wait()
shutdownAt := time.Now()
ranFor := shutdownAt.Sub(extensionStartup)
util.Logf("Extension shutdown after %vms", ranFor.Milliseconds())
}
// logShipLoop ships function logs to New Relic as they arrive.
func logShipLoop(ctx context.Context, logServer *logserver.LogServer, telemetryClient *telemetry.Client) {
for {
functionLogs, more := logServer.AwaitFunctionLogs()
if !more {
return
}
err := telemetryClient.SendFunctionLogs(ctx, invokedFunctionARN, functionLogs)
if err != nil {
util.Logf("Failed to send %d function logs", len(functionLogs))
}
}
}
// mainLoop repeatedly calls the /next api, and processes telemetry and platform logs. The timing is rather complicated.
func mainLoop(ctx context.Context, invocationClient *client.InvocationClient, batch *telemetry.Batch, telemetryChan chan []byte, logServer *logserver.LogServer, telemetryClient *telemetry.Client) int {
eventCounter := 0
probablyTimeout := false
for {
select {
case <-ctx.Done():
// We're already done
return eventCounter
default:
// Our call to next blocks. It is likely that the container is frozen immediately after we call NextEvent.
util.Debugln("mainLoop: blocking while awaiting next invocation event...")
event, err := invocationClient.NextEvent(ctx)
// We've thawed.
eventStart := time.Now()
if err != nil {
util.Logln(err)
err = invocationClient.ExitError(ctx, "NextEventError.Main", err)
if err != nil {
util.Logln(err)
}
continue
}
eventCounter++
if probablyTimeout {
// We suspect a timeout. Either way, we've gotten to the next event, so telemetry will
// have arrived for the last request if it's going to. Non-blocking poll for telemetry.
// If we have indeed timed out, there's a chance we got telemetry out anyway. If we haven't
// timed out, this will catch us up to the current state of telemetry, allowing us to resume.
select {
case telemetryBytes := <-telemetryChan:
// We received telemetry
util.Debugf("Agent telemetry bytes: %s", base64.URLEncoding.EncodeToString(telemetryBytes))
batch.AddTelemetry(lastRequestId, telemetryBytes)
util.Logf("We suspected a timeout for request %s but got telemetry anyway", lastRequestId)
default:
}
}
if event.EventType == api.Shutdown {
if event.ShutdownReason == api.Timeout && lastRequestId != "" {
// Synthesize the timeout error message that the platform produces, and LLC parses
timestamp := eventStart.UTC()
timeoutSecs := eventStart.Sub(lastEventStart).Seconds()
timeoutMessage := fmt.Sprintf(
"%s %s Task timed out after %.2f seconds",
timestamp.Format(time.RFC3339),
lastRequestId,
timeoutSecs,
)
batch.AddTelemetry(lastRequestId, []byte(timeoutMessage))
} else if event.ShutdownReason == api.Failure && lastRequestId != "" {
// Synthesize a generic platform error. Probably an OOM, though it could be any runtime crash.
errorMessage := fmt.Sprintf("RequestId: %s A platform error caused a shutdown", lastRequestId)
batch.AddTelemetry(lastRequestId, []byte(errorMessage))
}
return eventCounter
} else {
// Reset probablyTimeout if the event after the suspected timeout wasn't a timeout shutdown.
probablyTimeout = false
}
// Note: shutdown events do not have these properties; we now know this is an invocation event.
invokedFunctionARN = event.InvokedFunctionARN
lastRequestId = event.RequestID
// Create an invocation record to hold telemetry
batch.AddInvocation(lastRequestId, eventStart)
// Await agent telemetry, which may time out.
// timeoutInstant is when the invocation will time out
timeoutInstant := time.Unix(0, event.DeadlineMs*int64(time.Millisecond))
// Set the timeout timer for a smidge before the actual timeout; we can recover from false timeouts.
timeoutWatchBegins := 200 * time.Millisecond
timeLimitContext, timeLimitCancel := context.WithDeadline(ctx, timeoutInstant.Add(-timeoutWatchBegins))
// Before we begin to await telemetry, harvest and ship. Ripe telemetry will mostly be handled here. Even that is a
// minority of invocations. Putting this here lets us run the HTTP request to send to NR in parallel with the Lambda
// handler, reducing or eliminating our latency impact.
pollLogServer(logServer, batch)
shipHarvest(ctx, batch.Harvest(time.Now()), telemetryClient)
select {
case <-timeLimitContext.Done():
timeLimitCancel()
// We are about to timeout
probablyTimeout = true
continue
case telemetryBytes := <-telemetryChan:
timeLimitCancel()
// We received telemetry
util.Debugf("Agent telemetry bytes: %s", base64.URLEncoding.EncodeToString(telemetryBytes))
inv := batch.AddTelemetry(lastRequestId, telemetryBytes)
if inv == nil {
util.Logf("Failed to add telemetry for request %v", lastRequestId)
}
// Opportunity for an aggressive harvest, in which case, we definitely want to wait for the HTTP POST
// to complete. Mostly, nothing really happens here.
pollLogServer(logServer, batch)
shipHarvest(ctx, batch.Harvest(time.Now()), telemetryClient)
}
lastEventStart = eventStart
}
}
}
// pollLogServer polls for platform logs, and annotates telemetry
func pollLogServer(logServer *logserver.LogServer, batch *telemetry.Batch) {
for _, platformLog := range logServer.PollPlatformChannel() {
inv := batch.AddTelemetry(platformLog.RequestID, platformLog.Content)
if inv == nil {
util.Debugf("Skipping platform log for request %v", platformLog.RequestID)
}
}
}
func shipHarvest(ctx context.Context, harvested []*telemetry.Invocation, telemetryClient *telemetry.Client) {
if len(harvested) > 0 {
util.Debugf("shipHarvest: harvesting agent telemetry")
telemetrySlice := make([][]byte, 0, 2*len(harvested))
for _, inv := range harvested {
telemetrySlice = append(telemetrySlice, inv.Telemetry...)
}
util.Debugf("shipHarveset: %d telemetry payloads harvested", len(telemetrySlice))
err, _ := telemetryClient.SendTelemetry(ctx, invokedFunctionARN, telemetrySlice)
if err != nil {
util.Logf("Failed to send harvested telemetry for %d invocations %s", len(harvested), err)
}
}
}
func noopLoop(ctx context.Context, invocationClient *client.InvocationClient) {
util.Logln("Starting no-op mode, no telemetry will be sent")
for {
select {
case <-ctx.Done():
return
default:
event, err := invocationClient.NextEvent(ctx)
if err != nil {
util.Logln(err)
errErr := invocationClient.ExitError(ctx, "NextEventError.Noop", err)
if errErr != nil {
util.Logln(errErr)
}
continue
}
if event.EventType == api.Shutdown {
return
}
}
}
}