forked from airbrake/gobrake
-
Notifications
You must be signed in to change notification settings - Fork 1
/
notifier.go
236 lines (202 loc) · 5.08 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
package gobrake // import "github.com/Restream/gobrake"
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"runtime"
"sync"
"time"
)
const statusTooManyRequests = 429
var (
errClosed = errors.New("gobrake: notifier is closed")
errRateLimited = errors.New("gobrake: you are rate limited")
)
var httpClient = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 15 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: &tls.Config{
ClientSessionCache: tls.NewLRUClientSessionCache(1024),
},
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: 10 * time.Second,
},
Timeout: 10 * time.Second,
}
var buffers = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
type filter func(*Notice) *Notice
type Notifier struct {
// http.Client that is used to interact with Airbrake API.
Client *http.Client
projectId int64
projectKey string
createNoticeURL string
context map[string]string
filters []filter
wg sync.WaitGroup
noticeCh chan *Notice
closed chan struct{}
}
func NewNotifier(host string, projectId int64, projectKey string) *Notifier {
n := &Notifier{
projectId: projectId,
projectKey: projectKey,
createNoticeURL: getCreateNoticeURL(host, projectId, projectKey),
Client: httpClient,
context: map[string]string{
"language": runtime.Version(),
"os": runtime.GOOS,
"architecture": runtime.GOARCH,
},
noticeCh: make(chan *Notice, 1000),
closed: make(chan struct{}),
}
if hostname, err := os.Hostname(); err == nil {
n.context["hostname"] = hostname
}
if wd, err := os.Getwd(); err == nil {
n.context["rootDirectory"] = wd
}
for i := 0; i < 10; i++ {
go n.worker()
}
return n
}
// Sets Airbrake host name. Default is https://airbrake.io.
func (n *Notifier) SetHost(h string) {
n.createNoticeURL = getCreateNoticeURL(h, n.projectId, n.projectKey)
}
// AddFilter adds filter that can modify or ignore notice.
func (n *Notifier) AddFilter(fn filter) {
n.filters = append(n.filters, fn)
}
// Notify notifies Airbrake about the error.
func (n *Notifier) Notify(e interface{}, req *http.Request) {
notice := n.Notice(e, req, 1)
n.SendNoticeAsync(notice)
}
// Notice returns Aibrake notice created from error and request. depth
// determines which call frame to use when constructing backtrace.
func (n *Notifier) Notice(err interface{}, req *http.Request, depth int) *Notice {
notice := NewNotice(err, req, depth+3)
for k, v := range n.context {
notice.Context[k] = v
}
return notice
}
type sendResponse struct {
Id string `json:"id"`
}
// SendNotice sends notice to Airbrake.
func (n *Notifier) SendNotice(notice *Notice) (string, error) {
for _, fn := range n.filters {
notice = fn(notice)
if notice == nil {
// Notice is ignored.
return "", nil
}
}
buf := buffers.Get().(*bytes.Buffer)
defer buffers.Put(buf)
buf.Reset()
if err := json.NewEncoder(buf).Encode(notice); err != nil {
return "", err
}
resp, err := n.Client.Post(n.createNoticeURL, "application/json", buf)
if err != nil {
return "", err
}
defer resp.Body.Close()
buf.Reset()
_, err = buf.ReadFrom(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusCreated {
if resp.StatusCode == statusTooManyRequests {
return "", errRateLimited
}
err := fmt.Errorf("gobrake: got response code=%d, wanted 201 CREATED", resp.StatusCode)
return "", err
}
var sendResp sendResponse
err = json.NewDecoder(buf).Decode(&sendResp)
if err != nil {
return "", err
}
return sendResp.Id, nil
}
// SendNoticeAsync acts as SendNotice, but sends notice asynchronously
// and pending notices can be flushed with Flush.
func (n *Notifier) SendNoticeAsync(notice *Notice) {
n.wg.Add(1)
select {
case n.noticeCh <- notice:
default:
n.wg.Done()
logger.Printf(
"notice=%q is ignored, because queue is full (len=%d)",
notice, len(n.noticeCh),
)
}
}
func (n *Notifier) worker() {
for {
select {
case notice := <-n.noticeCh:
if _, err := n.SendNotice(notice); err != nil && err != errRateLimited {
logger.Printf("gobrake failed reporting notice=%q: error=%q", notice, err)
}
n.wg.Done()
case <-n.closed:
return
}
}
}
// NotifyOnPanic notifies Airbrake about the panic and should be used
// with defer statement.
func (n *Notifier) NotifyOnPanic() {
if v := recover(); v != nil {
notice := n.Notice(v, nil, 3)
n.SendNotice(notice)
panic(v)
}
}
// Flush does nothing.
//
// Deprecated. Use CloseAndWait instead.
func (n *Notifier) Flush() {}
// WaitAndClose waits for pending requests to finish and then closes the notifier.
func (n *Notifier) WaitAndClose(timeout time.Duration) error {
done := make(chan struct{})
go func() {
n.wg.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(timeout):
}
close(n.closed)
return nil
}
func getCreateNoticeURL(host string, projectId int64, key string) string {
return fmt.Sprintf(
"%s/api/v3/projects/%d/notices?key=%s",
host, projectId, key,
)
}