-
Notifications
You must be signed in to change notification settings - Fork 0
/
notifier.go
432 lines (385 loc) · 12.3 KB
/
notifier.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
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
package bugsnag
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os/exec"
"reflect"
"runtime"
"runtime/metrics"
"strings"
"sync"
"time"
)
// Notifier is the key type of this package, and exposes methods for reporting
// errors and tracking sessions.
type Notifier struct {
cfg *Configuration
sessions []*session
sessionPublishInterval time.Duration
reportCh chan *JSONErrorReport
sessionCh chan *session
shutdownCh chan struct{}
shutdownDoneCh chan struct{}
loopOnce sync.Once
}
// ErrorReportSanitizer allows you to modify the payload being sent to Bugsnag just before it's being sent.
// The ctx param provided will be the ctx from the deepest location where
// Wrap is called, falling back to the ctx given to Notify.
// You may return a non-nil error in order to prevent the payload from being sent at all.
// This error is then forwarded to the InternalErrorCallback.
// No further modifications to the payload will happen to the payload after this is run.
type ErrorReportSanitizer func(ctx context.Context, p *JSONErrorReport) error
// New constructs a new Notifier with the given configuration.
// You should call Close before shutting down your app in order to ensure that
// all sessions and reports have been sent.
func New(config Configuration) (*Notifier, error) { //nolint:gocritic // We want to pass by value here as the configuration should be considered immutable
cfg := &config
cfg.populateDefaults()
cfg.runtimeConstants = makeRuntimeConstants()
if err := cfg.validate(); err != nil {
return nil, err
}
const bufChanSize = 16
return &Notifier{
cfg: cfg,
sessions: []*session{},
sessionPublishInterval: time.Minute,
sessionCh: make(chan *session, bufChanSize),
reportCh: make(chan *JSONErrorReport, bufChanSize),
shutdownCh: make(chan struct{}),
shutdownDoneCh: make(chan struct{}),
loopOnce: sync.Once{},
}, nil
}
// Close shuts down the notifier, flushing any unsent reports and sessions.
// Any further calls to StartSession and Notify will call the
// InternalErrorCallback, if provided, with an error.
func (n *Notifier) Close() {
// Ideally we wouldn't need this guard, but it's the best way I can see to
// prevent this package from ever panicking.
defer n.guard("Close")
// Need to ensure that the loop is running in the first place to not block
// if Close is called before StartSession/Notify.
n.loopOnce.Do(func() { go n.loop() })
// OK, so we have that warning above in the documentation about the panics,
// but I'd much rather just drop the sessions/reports. I haven't bothered
// figuring out how to do this yet in a clean (race-condition-free) manner.
n.shutdownCh <- struct{}{}
<-n.shutdownDoneCh
}
// Notify reports the given error to Bugsnag.
// Extracts diagnostic data from the context and any *bugsnag.Error errors,
// including wrapped errors.
// Invokes the ErrorReportSanitizer, if set, before sending the error report.
func (n *Notifier) Notify(ctx context.Context, err error) {
// Ideally we wouldn't need this guard, but it's the best way I can see to
// prevent this package from ever panicking.
defer n.guard("Notify")
if err == nil {
n.cfg.InternalErrorCallback(errors.New("error missing in call to (*bugsnag.Notifier).Notify. no error reported to Bugsnag"))
return
}
n.loopOnce.Do(func() { go n.loop() })
var report *JSONErrorReport
report, ctx = n.makeReport(ctx, err)
if sErr := n.cfg.ErrorReportSanitizer(ctx, report); sErr != nil {
n.cfg.InternalErrorCallback(sErr)
return
}
n.reportCh <- report
}
type severity int
const (
severityUndetermined severity = iota
// SeverityInfo indicates that the severity of the Error is "info"
SeverityInfo
// SeverityWarning indicates that the severity of the Error is "warning"
SeverityWarning
// SeverityError indicates that the severity of the Error is "error"
SeverityError
)
// loop is intended to be an infinitely running goroutine that periodically (as
// defined by sessionPublishInterval) sends sessions, and sends reports as they
// come in. This loop ensures that a spike in errors doesn't consume the upload
// bandwidth for highly concurrent applications.
func (n *Notifier) loop() {
ticker := time.NewTicker(n.sessionPublishInterval)
for {
select {
case r := <-n.reportCh:
if err := n.sendErrorReport(r); err != nil {
n.cfg.InternalErrorCallback(fmt.Errorf("unable to send error report: %w", err))
}
case s := <-n.sessionCh:
n.sessions = append(n.sessions, s)
case <-ticker.C:
n.flushSessions()
case <-n.shutdownCh:
n.shutdown(ticker)
close(n.shutdownDoneCh)
return
}
}
}
func (n *Notifier) shutdown(ticker *time.Ticker) {
close(n.shutdownCh)
close(n.reportCh)
for r := range n.reportCh {
if err := n.sendErrorReport(r); err != nil {
n.cfg.InternalErrorCallback(fmt.Errorf("unable to send error report when closing Notifier: %w", err))
}
}
close(n.sessionCh)
for s := range n.sessionCh {
n.sessions = append(n.sessions, s)
}
ticker.Stop()
n.flushSessions()
}
type causer interface {
Cause() error
}
func (n *Notifier) makeReport(ctx context.Context, err error) (*JSONErrorReport, context.Context) {
unhandled := makeUnhandled(err)
exs := makeExceptions(err)
contextData, augmentedCtx := extractAugmentedContextData(ctx, err, unhandled)
return &JSONErrorReport{
APIKey: n.cfg.APIKey,
Notifier: makeNotifier(n.cfg),
Events: []*JSONEvent{
{
PayloadVersion: "5",
Context: contextData.bContext,
Unhandled: unhandled,
Severity: makeSeverity(err),
SeverityReason: &JSONSeverityReason{Type: severityReasonType(err)},
Exceptions: exs,
Breadcrumbs: contextData.breadcrumbs,
User: contextData.user,
App: makeJSONApp(n.cfg),
Device: n.makeJSONDevice(),
Session: contextData.session,
Metadata: contextData.metadata,
GroupingHash: makeGroupingHash(exs),
},
},
}, augmentedCtx
}
func (n *Notifier) sendErrorReport(r *JSONErrorReport) error {
b, err := json.Marshal(r)
if err != nil {
return fmt.Errorf("unable to marshal JSON: %w", err)
}
req, err := http.NewRequest(http.MethodPost, n.cfg.EndpointNotify, bytes.NewBuffer(b))
if err != nil {
return fmt.Errorf("unable to create new request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Bugsnag-Api-Key", n.cfg.APIKey)
req.Header.Add("Bugsnag-Payload-Version", "5")
req.Header.Add("Bugsnag-Sent-At", time.Now().UTC().Format(time.RFC3339))
// Note we're using a background context here to avoid confusing bugs ala
// "my errors aren't being sent to Bugsnag" due to users not realizing that
// the context they provided (which usually is derived from a request) has
// already been canceled by the time that this request is being made.
res, err := http.DefaultClient.Do(req.WithContext(context.Background()))
if err != nil {
return fmt.Errorf("unable to perform HTTP request: %w", err)
}
if err := res.Body.Close(); err != nil {
return fmt.Errorf("unable to close the response body: %w", err)
}
return nil
}
func makeUnhandled(err error) bool {
for {
if berr, ok := err.(*Error); ok && berr.Unhandled {
return true
}
err = errors.Unwrap(err)
if err == nil {
break
}
}
return false
}
func makeSeverity(err error) string {
if berr := extractLowestBugsnagError(err); berr != nil {
if s := berr.Severity; s != severityUndetermined {
return []string{"undetermined", "info", "warning", "error"}[s]
}
if berr.Unhandled || berr.Panic {
return "error"
}
}
return "warning"
}
func severityReasonType(err error) string {
var (
prefix = "handled"
suffix = "Exception"
)
if lowestBugsnagErr := extractLowestBugsnagError(err); lowestBugsnagErr != nil {
if lowestBugsnagErr.Severity != severityUndetermined {
return "userSpecifiedSeverity"
}
if lowestBugsnagErr.Unhandled {
prefix = "unhandled"
}
if lowestBugsnagErr.Panic {
suffix = "Panic"
}
}
return prefix + suffix
}
func makeExceptions(err error) []*JSONException {
var errs []error
for {
if err == nil {
break
}
errs = append([]error{err}, errs...)
switch e := err.(type) {
case causer:
// the github.com/pkg/errors package nests its own internal errors,
// which makes it look like its wrapped twice
err = e.Cause()
if e, ok := err.(causer); ok {
err = e.Cause()
}
default:
err = errors.Unwrap(err)
}
}
eps := make([]*JSONException, len(errs))
for i, err := range errs { //nolint:varnamelen // indexes are conventionally i
var stacktrace []*JSONStackframe
if berr, ok := err.(*Error); ok {
stacktrace = berr.stacktrace
}
// reverse the order to match the API
eps[len(errs)-i-1] = &JSONException{
ErrorClass: reflect.TypeOf(err).String(),
Message: err.Error(),
Stacktrace: stacktrace,
}
}
return eps
}
func makeJSONApp(cfg *Configuration) *JSONApp {
return &JSONApp{
ID: cfg.runtimeConstants.appID,
Version: cfg.AppVersion,
ReleaseStage: cfg.ReleaseStage,
Type: "",
Duration: time.Since(cfg.appStartTime).Milliseconds(),
}
}
func (n *Notifier) makeJSONDevice() *JSONDevice {
return &JSONDevice{
Hostname: n.cfg.hostname,
OSName: n.cfg.osName,
OSVersion: n.cfg.osVersion,
RuntimeMetrics: runtimeMetrics(),
GoroutineCount: runtime.NumGoroutine(),
RuntimeVersions: map[string]string{"go": n.cfg.goVersion},
}
}
func runtimeMetrics() map[string]interface{} {
descs := metrics.All()
samples := make([]metrics.Sample, len(descs))
for i := range samples {
samples[i].Name = descs[i].Name
}
metrics.Read(samples)
runtimeMetrics := map[string]interface{}{}
for _, sample := range samples {
switch sample.Value.Kind() {
case metrics.KindUint64:
runtimeMetrics[sample.Name] = sample.Value.Uint64()
case metrics.KindFloat64:
runtimeMetrics[sample.Name] = sample.Value.Float64()
case metrics.KindBad:
// This should never happen because all metrics are supported by construction.
case metrics.KindFloat64Histogram:
// Ignore histograms as they contain too much data and we're likely
// to hit the 1MB limit, and wouldn't want to try and do any
// analysis on it at runtime for performance reasons.
default:
// This block may get invoked if there's a new metric kind being
// added in future Go versions. Worst case scenario, we miss out
// on a new metric.
}
}
return runtimeMetrics
}
// osVersion is only available on unix-like systems as it depends on the
// 'uname' command.
func osVersion() string {
if b, err := exec.Command("uname", "-r").Output(); err == nil {
return strings.TrimSpace(string(b))
}
return ""
}
func makeNotifier(cfg *Configuration) *JSONNotifier {
return &JSONNotifier{
Name: "Alternative Go Notifier",
URL: "https://github.com/kinbiko/bugsnag",
Version: cfg.runtimeConstants.notifierVersion,
}
}
// This bit of custom logic ensures a better experience when wrapping a
// non-Bugsnag err inside a Bugsnag Error.
// Without this events would all be grouped under the same error in the
// dashboard because the deepest "exception" (the non-Bugsnag err) which
// gets given a default stackframe of:
//
// {
// (... other fluff ...)
// "file": "unknown file",
// "in_project": null,
// "line_number": 0,
// "method": "unknown method"
// }
//
// Even though this frame is not in project (or rather "null in project",
// whatever that means), lower exceptions take priority over frames being
// in project or not.
//
// This logic returns a grouping hash based on the deepest in-project
// stackframe, regardless of which "exception" it comes from.
//
// You can disable this logic in a ErrorReportSanitizer by setting the grouping
// hash to "".
func makeGroupingHash(exs []*JSONException) string {
for i := len(exs) - 1; i >= 0; i-- {
for _, frame := range exs[i].Stacktrace {
if frame.InProject {
return fmt.Sprintf("%s:%d", frame.File, frame.LineNumber)
}
}
}
return ""
}
func extractLowestBugsnagError(err error) *Error {
var berr *Error
for {
if b, ok := err.(*Error); ok {
berr = b
}
err = errors.Unwrap(err)
if err == nil {
break
}
}
return berr
}
func (n *Notifier) guard(method string) {
if p := recover(); p != nil {
n.cfg.InternalErrorCallback(fmt.Errorf("panic when calling %s (did you invoke %s after calling Close?): %v", method, method, p))
}
}