-
Notifications
You must be signed in to change notification settings - Fork 48
/
logserver.go
221 lines (188 loc) · 5.08 KB
/
logserver.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
package logserver
import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"regexp"
"strconv"
"sync"
"time"
"github.com/newrelic/newrelic-lambda-extension/config"
"github.com/newrelic/newrelic-lambda-extension/lambda/extension/api"
"github.com/newrelic/newrelic-lambda-extension/util"
)
const (
platformLogBufferSize = 100
)
type LogLine struct {
Time time.Time
RequestID string
Content []byte
}
type LogServer struct {
listenString string
server *http.Server
platformLogChan chan LogLine
functionLogChan chan []LogLine
lastRequestId string
lastRequestIdLock *sync.Mutex
}
func (ls *LogServer) Port() uint16 {
_, portStr, _ := net.SplitHostPort(ls.listenString)
port, _ := strconv.ParseUint(portStr, 10, 16)
return uint16(port)
}
func (ls *LogServer) Close() error {
// Pause briefly to allow final platform logs to arrive
time.Sleep(200 * time.Millisecond)
ret := ls.server.Close()
close(ls.platformLogChan)
close(ls.functionLogChan)
return ret
}
func (ls *LogServer) PollPlatformChannel() []LogLine {
var ret []LogLine
for {
select {
case report, more := <-ls.platformLogChan:
if more {
ret = append(ret, report)
} else {
return ret
}
default:
return ret
}
}
}
func (ls *LogServer) AwaitFunctionLogs() ([]LogLine, bool) {
ll, more := <-ls.functionLogChan
return ll, more
}
func formatReport(metrics map[string]interface{}) string {
ret := ""
if val, ok := metrics["durationMs"]; ok {
ret += fmt.Sprintf("\tDuration: %.2f ms", val)
}
if val, ok := metrics["billedDurationMs"]; ok {
ret += fmt.Sprintf("\tBilled Duration: %.0f ms", val)
}
if val, ok := metrics["memorySizeMB"]; ok {
ret += fmt.Sprintf("\tMemory Size: %.0f MB", val)
}
if val, ok := metrics["maxMemoryUsedMB"]; ok {
ret += fmt.Sprintf("\tMax Memory Used: %.0f MB", val)
}
if val, ok := metrics["initDurationMs"]; ok {
ret += fmt.Sprintf("\tInit Duration: %.2f ms", val)
}
util.Debugf("Formatted Return Report: %s", ret)
return ret
}
var reportStringRegExp, _ = regexp.Compile("RequestId: ([a-fA-F0-9-]+)(.*)")
func (ls *LogServer) handler(res http.ResponseWriter, req *http.Request) {
defer util.Close(req.Body)
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
util.Logf("Error processing log request: %v", err)
}
var logEvents []api.LogEvent
err = json.Unmarshal(bodyBytes, &logEvents)
if err != nil {
util.Logf("Error parsing log payload: %v", err)
}
var functionLogs []LogLine
for _, event := range logEvents {
switch event.Type {
case "platform.start":
ls.lastRequestIdLock.Lock()
switch event.Record.(type) {
case map[string]interface{}:
ls.lastRequestId = event.Record.(map[string]interface{})["requestId"].(string)
case string:
recordString := event.Record.(string)
results := reportStringRegExp.FindStringSubmatch(recordString)
if len(results) > 1 {
ls.lastRequestId = results[1]
}
}
ls.lastRequestIdLock.Unlock()
case "platform.report":
metricString := ""
requestId := ""
switch event.Record.(type) {
case map[string]interface{}:
record := event.Record.(map[string]interface{})
metrics := record["metrics"].(map[string]interface{})
metricString = formatReport(metrics)
requestId = record["requestId"].(string)
case string:
recordString := event.Record.(string)
results := reportStringRegExp.FindStringSubmatch(recordString)
if len(results) > 1 {
requestId = results[1]
if len(results) > 2 {
metricString = results[2]
}
} else {
util.Debugf("Unknown platform log: %s", recordString)
}
}
reportStr := fmt.Sprintf(
"REPORT RequestId: %v%s",
requestId,
metricString,
)
reportLine := LogLine{
Time: event.Time,
RequestID: requestId,
Content: []byte(reportStr),
}
ls.platformLogChan <- reportLine
case "platform.logsDropped":
util.Logf("Platform dropped logs: %v", event.Record)
case "function":
record := event.Record.(string)
ls.lastRequestIdLock.Lock()
functionLogs = append(functionLogs, LogLine{
Time: event.Time,
RequestID: ls.lastRequestId,
Content: []byte(record),
})
ls.lastRequestIdLock.Unlock()
default:
//util.Debugln("Ignored log event of type ", event.Type, string(bodyBytes))
}
}
if len(functionLogs) > 0 {
ls.functionLogChan <- functionLogs
}
_, _ = res.Write(nil)
}
func Start(conf *config.Configuration) (*LogServer, error) {
return startInternal(conf.LogServerHost)
}
func startInternal(host string) (*LogServer, error) {
listener, err := net.Listen("tcp", host+":")
if err != nil {
return nil, err
}
server := &http.Server{}
logServer := &LogServer{
listenString: listener.Addr().String(),
server: server,
platformLogChan: make(chan LogLine, platformLogBufferSize),
functionLogChan: make(chan []LogLine),
lastRequestIdLock: &sync.Mutex{},
}
mux := http.NewServeMux()
mux.HandleFunc("/", logServer.handler)
server.Handler = mux
go func() {
util.Logln("Starting log server.")
util.Logf("Log server terminating: %v\n", server.Serve(listener))
}()
return logServer, nil
}