/
raven.go
301 lines (253 loc) · 7.81 KB
/
raven.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
/*
Package raven is a client and library for sending messages and exceptions to Sentry: http://getsentry.com
Usage:
Create a new client using the NewClient() function. The value for the DSN parameter can be obtained
from the project page in the Sentry web interface. After the client has been created use the CaptureMessage
method to send messages to the server.
client, err := raven.NewClient(dsn)
...
id, err := client.CaptureMessage("some text")
If you want to have more finegrained control over the send event, you can create the event instance yourself
client.Capture(&raven.Event{Message: "Some Text", Logger:"auth"})
*/
package raven
import (
"bytes"
"compress/zlib"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"path"
"strings"
"time"
)
type Client struct {
URL *url.URL
PublicKey string
SecretKey string
Project string
httpClient *http.Client
}
type Stackframe struct {
Filename string `json:"filename"`
Function string `json:"function"`
Module string `json:"module"`
LineNo int `json:"lineno"`
ColNo int `json:"colno"`
AbsPath string `json:"abs_path"`
ContextLine string `json:"context_line"`
PreContext []string `json:"pre_context"`
PostContext []string `json:"post_context"`
InApp bool `json:"in_app"`
Vars map[string]string `json:"vars"`
}
type Stacktrace struct {
// Required
Frames []Stackframe `json:"frames"`
}
type Exception struct {
Type string `json:"type"`
Value string `json:"value"`
Module string `json:"module"`
Stacktrace *Stacktrace `json:"stacktrace"`
}
type Message struct {
Message string `json:"message"`
Params []string `json:"params"`
}
type HttpRequest struct {
Url string `json:"url"`
Method string `json:"method"`
Data map[string]string `json:"data"`
Query string `json:"query_string"`
Cookies []string `json:"cookies"`
Headers map[string]string `json:"headers"`
Env map[string]string `json:"env"`
}
type User struct {
ID string `json:"id"`
UserName string `json:"user_name"`
Email string `json:"email"`
IPAddress string `json:"ip_address"`
}
type Template struct {
AbsPath string `json:"abs_path"`
FileName string `json:"filename"`
PreContext []string `json:"pre_context"`
ContextLine []string `json:"context_line"`
LineNo int `json:"lineno"`
PostContext []string `json:"post_context"`
}
type Query struct {
Query string `json:"query"`
Engine string `json:"engine"`
}
type Event struct {
EventId string `json:"event_id"`
Project string `json:"project"`
Message string `json:"message"`
Timestamp string `json:"timestamp"`
Level string `json:"level"`
Logger string `json:"logger"`
ServerName string `json:"server_name"`
Platform string `json:"platform"`
Culprit string `json:"culprit"`
// Mappings that are predefined in sentry for special use
Exception *Exception `json:"exception,omitempty"`
Request *HttpRequest `json:"request,omitempty"`
User *User `json:"user,omitempty"`
Stacktrace *Stacktrace `json:"stacktrace.omitempty"`
Template *Template `json:"template,omitempty"`
Query *Query `json:"query,omitempty"`
Modules map[string]string `json:"modules,omitempty"`
Extra map[string]string `json:"extra,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
}
type sentryResponse struct {
ResultId string `json:"result_id"`
}
// Template for the X-Sentry-Auth header
const xSentryAuthTemplate = "Sentry sentry_version=2.0, sentry_client=raven-go/0.1, sentry_timestamp=%v, sentry_key=%v"
// An iso8601 timestamp without the timezone. This is the format Sentry expects.
const iso8601 = "2006-01-02T15:04:05"
// NewClient creates a new client for a server identified by the given dsn
// A dsn is a string in the form:
// {PROTOCOL}://{PUBLIC_KEY}:{SECRET_KEY}@{HOST}/{PATH}{PROJECT_ID}
// eg:
// http://abcd:efgh@sentry.example.com/sentry/project1
func NewClient(dsn string) (client *Client, err error) {
u, err := url.Parse(dsn)
if err != nil {
return nil, err
}
basePath := path.Dir(u.Path)
project := path.Base(u.Path)
if u.User == nil {
return nil, fmt.Errorf("the DSN must contain a public and secret key")
}
publicKey := u.User.Username()
secretKey, keyIsSet := u.User.Password()
if !keyIsSet {
return nil, fmt.Errorf("the DSN must contain a secret key")
}
u.Path = basePath
check := func(req *http.Request, via []*http.Request) error {
fmt.Printf("%+v", req)
return nil
}
httpClient := &http.Client{nil, check, nil}
return &Client{URL: u, PublicKey: publicKey, SecretKey: secretKey, httpClient: httpClient, Project: project}, nil
}
// CaptureMessage sends a message to the Sentry server. The resulting string is an event identifier.
func (client Client) CaptureMessage(message ...string) (result string, err error) {
ev := Event{Message: strings.Join(message, " ")}
sentryErr := client.Capture(&ev)
if sentryErr != nil {
return "", sentryErr
}
return ev.EventId, nil
}
// CaptureMessagef is similar to CaptureMessage except it is using Printf like parameters for
// formatting the message
func (client Client) CaptureMessagef(format string, a ...interface{}) (result string, err error) {
return client.CaptureMessage(fmt.Sprintf(format, a))
}
// Sends the given event to the sentry servers after encoding it into a byte slice.
func (client Client) Capture(ev *Event) error {
// Fill in defaults
ev.Project = client.Project
if ev.EventId == "" {
eventId, err := uuid4()
if err != nil {
return err
}
ev.EventId = eventId
}
if ev.Level == "" {
ev.Level = "error"
}
if ev.Logger == "" {
ev.Logger = "root"
}
if ev.Timestamp == "" {
now := time.Now().UTC()
ev.Timestamp = now.Format(iso8601)
}
// Send
timestamp, err := time.Parse(iso8601, ev.Timestamp)
if err != nil {
return err
}
buf := new(bytes.Buffer)
b64Encoder := base64.NewEncoder(base64.StdEncoding, buf)
writer := zlib.NewWriter(b64Encoder)
jsonEncoder := json.NewEncoder(writer)
if err := jsonEncoder.Encode(ev); err != nil {
return err
}
err = writer.Close()
if err != nil {
return err
}
err = b64Encoder.Close()
if err != nil {
return err
}
err = client.send(buf.Bytes(), timestamp)
if err != nil {
return err
}
return nil
}
// sends a packet to the sentry server with a given timestamp
func (client Client) send(packet []byte, timestamp time.Time) (err error) {
apiURL := *client.URL
apiURL.Path = path.Join(apiURL.Path, "/api/"+client.Project+"/store")
apiURL.Path += "/"
location := apiURL.String()
// for loop to follow redirects
for {
buf := bytes.NewBuffer(packet)
req, err := http.NewRequest("POST", location, buf)
if err != nil {
return err
}
authHeader := fmt.Sprintf(xSentryAuthTemplate, timestamp.Unix(), client.PublicKey)
req.Header.Add("X-Sentry-Auth", authHeader)
req.Header.Add("Content-Type", "application/octet-stream")
req.Header.Add("Connection", "close")
req.Header.Add("Accept-Encoding", "identity")
resp, err := client.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
switch resp.StatusCode {
case 301:
// set the location to the new one to retry on the next iteration
location = resp.Header["Location"][0]
case 200:
return nil
default:
return errors.New(resp.Status)
}
}
// should never get here
panic("send broke out of loop")
}
func uuid4() (string, error) {
//TODO: Verify this algorithm or use an external library
uuid := make([]byte, 16)
n, err := rand.Read(uuid)
if n != len(uuid) || err != nil {
return "", err
}
uuid[8] = 0x80
uuid[4] = 0x40
return hex.EncodeToString(uuid), nil
}