Debian Codegraph @

client.go

raw ◀ ▶
1 Debian patch touch this file
1 // Package raven implements a client for the Sentry error logging service.
2 package raven
3
4 import (
5 "bytes"
6 "compress/zlib"
7 "crypto/rand"
8 "crypto/tls"
•9 "crypto/x509"
10 "encoding/base64"
11 "encoding/hex"
12 "encoding/json"
13 "errors"
14 "fmt"
15 "io"
16 "io/ioutil"
17 "log"
18 mrand "math/rand"
19 "net/http"
20 "net/url"
21 "os"
22 "regexp"
23 "runtime"
24 "strings"
25 "sync"
26 "time"
27
28 pkgErrors "github.com/pkg/errors"
29 )
30
31 const (
32 userAgent = "raven-go/1.0"
33 timestampFormat = `"2006-01-02T15:04:05.00"`
34 )
35
36 var (
37 ErrPacketDropped = errors.New("raven: packet dropped")
38 ErrUnableToUnmarshalJSON = errors.New("raven: unable to unmarshal JSON")
39 ErrMissingUser = errors.New("raven: dsn missing public key and/or password")
40 ErrMissingProjectID = errors.New("raven: dsn missing project id")
41 ErrInvalidSampleRate = errors.New("raven: sample rate should be between 0 and 1")
42 )
43
44 type Severity string
45
46 // http://docs.python.org/2/howto/logging.html#logging-levels
47 const (
48 DEBUG = Severity("debug")
49 INFO = Severity("info")
50 WARNING = Severity("warning")
51 ERROR = Severity("error")
52 FATAL = Severity("fatal")
53 )
54
55 type Timestamp time.Time
56
57 func (t Timestamp) MarshalJSON() ([]byte, error) {
58 return []byte(time.Time(t).UTC().Format(timestampFormat)), nil
59 }
60
61 func (timestamp *Timestamp) UnmarshalJSON(data []byte) error {
62 t, err := time.Parse(timestampFormat, string(data))
63 if err != nil {
64 return err
65 }
66
67 *timestamp = Timestamp(t)
68 return nil
69 }
70
71 func (timestamp Timestamp) Format(format string) string {
72 t := time.Time(timestamp)
73 return t.Format(format)
74 }
75
76 // An Interface is a Sentry interface that will be serialized as JSON.
77 // It must implement json.Marshaler or use json struct tags.
78 type Interface interface {
79 // The Sentry class name. Example: sentry.interfaces.Stacktrace
80 Class() string
81 }
82
83 type Culpriter interface {
84 Culprit() string
85 }
86
87 type Transport interface {
88 Send(url, authHeader string, packet *Packet) error
89 }
90
91 type Extra map[string]interface{}
92
93 type outgoingPacket struct {
94 packet *Packet
95 ch chan error
96 }
97
98 type Tag struct {
99 Key string
100 Value string
101 }
102
103 type Tags []Tag
104
105 func (tag *Tag) MarshalJSON() ([]byte, error) {
106 return json.Marshal([2]string{tag.Key, tag.Value})
107 }
108
109 func (t *Tag) UnmarshalJSON(data []byte) error {
110 var tag [2]string
111 if err := json.Unmarshal(data, &tag); err != nil {
112 return err
113 }
114 *t = Tag{tag[0], tag[1]}
115 return nil
116 }
117
118 func (t *Tags) UnmarshalJSON(data []byte) error {
119 var tags []Tag
120
121 switch data[0] {
122 case '[':
123 // Unmarshal into []Tag
124 if err := json.Unmarshal(data, &tags); err != nil {
125 return err
126 }
127 case '{':
128 // Unmarshal into map[string]string
129 tagMap := make(map[string]string)
130 if err := json.Unmarshal(data, &tagMap); err != nil {
131 return err
132 }
133
134 // Convert to []Tag
135 for k, v := range tagMap {
136 tags = append(tags, Tag{k, v})
137 }
138 default:
139 return ErrUnableToUnmarshalJSON
140 }
141
142 *t = tags
143 return nil
144 }
145
146 // https://docs.getsentry.com/hosted/clientdev/#building-the-json-packet
147 type Packet struct {
148 // Required
149 Message string `json:"message"`
150
151 // Required, set automatically by Client.Send/Report via Packet.Init if blank
152 EventID string `json:"event_id"`
153 Project string `json:"project"`
154 Timestamp Timestamp `json:"timestamp"`
155 Level Severity `json:"level"`
156 Logger string `json:"logger"`
157
158 // Optional
159 Platform string `json:"platform,omitempty"`
160 Culprit string `json:"culprit,omitempty"`
161 ServerName string `json:"server_name,omitempty"`
162 Release string `json:"release,omitempty"`
163 Environment string `json:"environment,omitempty"`
164 Tags Tags `json:"tags,omitempty"`
165 Modules map[string]string `json:"modules,omitempty"`
166 Fingerprint []string `json:"fingerprint,omitempty"`
167 Extra Extra `json:"extra,omitempty"`
168
169 Interfaces []Interface `json:"-"`
170 }
171
172 // NewPacket constructs a packet with the specified message and interfaces.
173 func NewPacket(message string, interfaces ...Interface) *Packet {
174 extra := Extra{}
175 setExtraDefaults(extra)
176 return &Packet{
177 Message: message,
178 Interfaces: interfaces,
179 Extra: extra,
180 }
181 }
182
183 // NewPacketWithExtra constructs a packet with the specified message, extra information, and interfaces.
184 func NewPacketWithExtra(message string, extra Extra, interfaces ...Interface) *Packet {
185 if extra == nil {
186 extra = Extra{}
187 }
188 setExtraDefaults(extra)
189
190 return &Packet{
191 Message: message,
192 Interfaces: interfaces,
193 Extra: extra,
194 }
195 }
196
197 func setExtraDefaults(extra Extra) Extra {
198 extra["runtime.Version"] = runtime.Version()
199 extra["runtime.NumCPU"] = runtime.NumCPU()
200 extra["runtime.GOMAXPROCS"] = runtime.GOMAXPROCS(0) // 0 just returns the current value
201 extra["runtime.NumGoroutine"] = runtime.NumGoroutine()
202 return extra
203 }
204
205 // Init initializes required fields in a packet. It is typically called by
206 // Client.Send/Report automatically.
207 func (packet *Packet) Init(project string) error {
208 if packet.Project == "" {
209 packet.Project = project
210 }
211 if packet.EventID == "" {
212 var err error
213 packet.EventID, err = uuid()
214 if err != nil {
215 return err
216 }
217 }
218 if time.Time(packet.Timestamp).IsZero() {
219 packet.Timestamp = Timestamp(time.Now())
220 }
221 if packet.Level == "" {
222 packet.Level = ERROR
223 }
224 if packet.Logger == "" {
225 packet.Logger = "root"
226 }
227 if packet.ServerName == "" {
228 packet.ServerName = hostname
229 }
230 if packet.Platform == "" {
231 packet.Platform = "go"
232 }
233
234 if packet.Culprit == "" {
235 for _, inter := range packet.Interfaces {
236 if c, ok := inter.(Culpriter); ok {
237 packet.Culprit = c.Culprit()
238 if packet.Culprit != "" {
239 break
240 }
241 }
242 }
243 }
244
245 return nil
246 }
247
248 func (packet *Packet) AddTags(tags map[string]string) {
249 for k, v := range tags {
250 packet.Tags = append(packet.Tags, Tag{k, v})
251 }
252 }
253
254 func uuid() (string, error) {
255 id := make([]byte, 16)
256 _, err := io.ReadFull(rand.Reader, id)
257 if err != nil {
258 return "", err
259 }
260 id[6] &= 0x0F // clear version
261 id[6] |= 0x40 // set version to 4 (random uuid)
262 id[8] &= 0x3F // clear variant
263 id[8] |= 0x80 // set to IETF variant
264 return hex.EncodeToString(id), nil
265 }
266
267 func (packet *Packet) JSON() ([]byte, error) {
268 packetJSON, err := json.Marshal(packet)
269 if err != nil {
270 return nil, err
271 }
272
273 interfaces := make(map[string]Interface, len(packet.Interfaces))
274 for _, inter := range packet.Interfaces {
275 if inter != nil {
276 interfaces[inter.Class()] = inter
277 }
278 }
279
280 if len(interfaces) > 0 {
281 interfaceJSON, err := json.Marshal(interfaces)
282 if err != nil {
283 return nil, err
284 }
285 packetJSON[len(packetJSON)-1] = ','
286 packetJSON = append(packetJSON, interfaceJSON[1:]...)
287 }
288
289 return packetJSON, nil
290 }
291
292 type context struct {
293 user *User
294 http *Http
295 tags map[string]string
296 }
297
298 func (c *context) setUser(u *User) { c.user = u }
299 func (c *context) setHttp(h *Http) { c.http = h }
300 func (c *context) setTags(t map[string]string) {
301 if c.tags == nil {
302 c.tags = make(map[string]string)
303 }
304 for k, v := range t {
305 c.tags[k] = v
306 }
307 }
308 func (c *context) clear() {
309 c.user = nil
310 c.http = nil
311 c.tags = nil
312 }
313
314 // Return a list of interfaces to be used in appending with the rest
315 func (c *context) interfaces() []Interface {
316 len, i := 0, 0
317 if c.user != nil {
318 len++
319 }
320 if c.http != nil {
321 len++
322 }
323 interfaces := make([]Interface, len)
324 if c.user != nil {
325 interfaces[i] = c.user
326 i++
327 }
328 if c.http != nil {
329 interfaces[i] = c.http
330 i++
331 }
332 return interfaces
333 }
334
335 // The maximum number of packets that will be buffered waiting to be delivered.
336 // Packets will be dropped if the buffer is full. Used by NewClient.
337 var MaxQueueBuffer = 100
338
339 func newTransport() Transport {
340 t := &HTTPTransport{}
•341 rootCAs, err := x509.SystemCertPool()
342 if err != nil {
343 log.Println("raven: failed to load root TLS certificates:", err)
344 } else {
345 t.Client = &http.Client{
346 Transport: &http.Transport{
347 Proxy: http.ProxyFromEnvironment,
348 TLSClientConfig: &tls.Config{RootCAs: rootCAs},
349 },
350 }
351 }
352 return t
353 }
354
355 func newClient(tags map[string]string) *Client {
356 client := &Client{
357 Transport: newTransport(),
358 Tags: tags,
359 context: &context{},
360 sampleRate: 1.0,
361 queue: make(chan *outgoingPacket, MaxQueueBuffer),
362 }
363 client.SetDSN(os.Getenv("SENTRY_DSN"))
364 client.SetRelease(os.Getenv("SENTRY_RELEASE"))
365 client.SetEnvironment(os.Getenv("SENTRY_ENVIRONMENT"))
366 return client
367 }
368
369 // New constructs a new Sentry client instance
370 func New(dsn string) (*Client, error) {
371 client := newClient(nil)
372 return client, client.SetDSN(dsn)
373 }
374
375 // NewWithTags constructs a new Sentry client instance with default tags.
376 func NewWithTags(dsn string, tags map[string]string) (*Client, error) {
377 client := newClient(tags)
378 return client, client.SetDSN(dsn)
379 }
380
381 // NewClient constructs a Sentry client and spawns a background goroutine to
382 // handle packets sent by Client.Report.
383 //
384 // Deprecated: use New and NewWithTags instead
385 func NewClient(dsn string, tags map[string]string) (*Client, error) {
386 client := newClient(tags)
387 return client, client.SetDSN(dsn)
388 }
389
390 // Client encapsulates a connection to a Sentry server. It must be initialized
391 // by calling NewClient. Modification of fields concurrently with Send or after
392 // calling Report for the first time is not thread-safe.
393 type Client struct {
394 Tags map[string]string
395
396 Transport Transport
397
398 // DropHandler is called when a packet is dropped because the buffer is full.
399 DropHandler func(*Packet)
400
401 // Context that will get appending to all packets
402 context *context
403
404 mu sync.RWMutex
405 url string
406 projectID string
407 authHeader string
408 release string
409 environment string
410 sampleRate float32
411
412 // default logger name (leave empty for 'root')
413 defaultLoggerName string
414
415 includePaths []string
416 ignoreErrorsRegexp *regexp.Regexp
417 queue chan *outgoingPacket
418
419 // A WaitGroup to keep track of all currently in-progress captures
420 // This is intended to be used with Client.Wait() to assure that
421 // all messages have been transported before exiting the process.
422 wg sync.WaitGroup
423
424 // A Once to track only starting up the background worker once
425 start sync.Once
426 }
427
428 // Initialize a default *Client instance
429 var DefaultClient = newClient(nil)
430
431 func (c *Client) SetIgnoreErrors(errs []string) error {
432 joinedRegexp := strings.Join(errs, "|")
433 r, err := regexp.Compile(joinedRegexp)
434 if err != nil {
435 return fmt.Errorf("failed to compile regexp %q for %q: %v", joinedRegexp, errs, err)
436 }
437
438 c.mu.Lock()
439 c.ignoreErrorsRegexp = r
440 c.mu.Unlock()
441 return nil
442 }
443
444 func (c *Client) shouldExcludeErr(errStr string) bool {
445 c.mu.RLock()
446 defer c.mu.RUnlock()
447 return c.ignoreErrorsRegexp != nil && c.ignoreErrorsRegexp.MatchString(errStr)
448 }
449
450 func SetIgnoreErrors(errs ...string) error {
451 return DefaultClient.SetIgnoreErrors(errs)
452 }
453
454 // SetDSN updates a client with a new DSN. It safe to call after and
455 // concurrently with calls to Report and Send.
456 func (client *Client) SetDSN(dsn string) error {
457 if dsn == "" {
458 return nil
459 }
460
461 client.mu.Lock()
462 defer client.mu.Unlock()
463
464 uri, err := url.Parse(dsn)
465 if err != nil {
466 return err
467 }
468
469 if uri.User == nil {
470 return ErrMissingUser
471 }
472 publicKey := uri.User.Username()
473 secretKey, hasSecretKey := uri.User.Password()
474 uri.User = nil
475
476 if idx := strings.LastIndex(uri.Path, "/"); idx != -1 {
477 client.projectID = uri.Path[idx+1:]
478 uri.Path = uri.Path[:idx+1] + "api/" + client.projectID + "/store/"
479 }
480 if client.projectID == "" {
481 return ErrMissingProjectID
482 }
483
484 client.url = uri.String()
485
486 if hasSecretKey {
487 client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s, sentry_secret=%s", publicKey, secretKey)
488 } else {
489 client.authHeader = fmt.Sprintf("Sentry sentry_version=4, sentry_key=%s", publicKey)
490 }
491
492 return nil
493 }
494
495 // Sets the DSN for the default *Client instance
496 func SetDSN(dsn string) error { return DefaultClient.SetDSN(dsn) }
497
498 // SetRelease sets the "release" tag.
499 func (client *Client) SetRelease(release string) {
500 client.mu.Lock()
501 defer client.mu.Unlock()
502 client.release = release
503 }
504
505 // SetEnvironment sets the "environment" tag.
506 func (client *Client) SetEnvironment(environment string) {
507 client.mu.Lock()
508 defer client.mu.Unlock()
509 client.environment = environment
510 }
511
512 // SetDefaultLoggerName sets the default logger name.
513 func (client *Client) SetDefaultLoggerName(name string) {
514 client.mu.Lock()
515 defer client.mu.Unlock()
516 client.defaultLoggerName = name
517 }
518
519 // SetSampleRate sets how much sampling we want on client side
520 func (client *Client) SetSampleRate(rate float32) error {
521 client.mu.Lock()
522 defer client.mu.Unlock()
523
524 if rate < 0 || rate > 1 {
525 return ErrInvalidSampleRate
526 }
527 client.sampleRate = rate
528 return nil
529 }
530
531 // SetRelease sets the "release" tag on the default *Client
532 func SetRelease(release string) { DefaultClient.SetRelease(release) }
533
534 // SetEnvironment sets the "environment" tag on the default *Client
535 func SetEnvironment(environment string) { DefaultClient.SetEnvironment(environment) }
536
537 // SetDefaultLoggerName sets the "defaultLoggerName" on the default *Client
538 func SetDefaultLoggerName(name string) {
539 DefaultClient.SetDefaultLoggerName(name)
540 }
541
542 // SetSampleRate sets the "sample rate" on the degault *Client
543 func SetSampleRate(rate float32) error { return DefaultClient.SetSampleRate(rate) }
544
545 func (client *Client) worker() {
546 for outgoingPacket := range client.queue {
547
548 client.mu.RLock()
549 url, authHeader := client.url, client.authHeader
550 client.mu.RUnlock()
551
552 outgoingPacket.ch <- client.Transport.Send(url, authHeader, outgoingPacket.packet)
553 client.wg.Done()
554 }
555 }
556
557 // Capture asynchronously delivers a packet to the Sentry server. It is a no-op
558 // when client is nil. A channel is provided if it is important to check for a
559 // send's success.
560 func (client *Client) Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error) {
561 ch = make(chan error, 1)
562
563 if client == nil {
564 // return a chan that always returns nil when the caller receives from it
565 close(ch)
566 return
567 }
568
569 if client.sampleRate < 1.0 && mrand.Float32() > client.sampleRate {
570 return
571 }
572
573 if packet == nil {
574 close(ch)
575 return
576 }
577
578 if client.shouldExcludeErr(packet.Message) {
579 return
580 }
581
582 // Keep track of all running Captures so that we can wait for them all to finish
583 // *Must* call client.wg.Done() on any path that indicates that an event was
584 // finished being acted upon, whether success or failure
585 client.wg.Add(1)
586
587 // Merge capture tags and client tags
588 packet.AddTags(captureTags)
589 packet.AddTags(client.Tags)
590
591 // Initialize any required packet fields
592 client.mu.RLock()
593 packet.AddTags(client.context.tags)
594 projectID := client.projectID
595 release := client.release
596 environment := client.environment
597 defaultLoggerName := client.defaultLoggerName
598 client.mu.RUnlock()
599
600 // set the global logger name on the packet if we must
601 if packet.Logger == "" && defaultLoggerName != "" {
602 packet.Logger = defaultLoggerName
603 }
604
605 err := packet.Init(projectID)
606 if err != nil {
607 ch <- err
608 client.wg.Done()
609 return
610 }
611
612 if packet.Release == "" {
613 packet.Release = release
614 }
615
616 if packet.Environment == "" {
617 packet.Environment = environment
618 }
619
620 outgoingPacket := &outgoingPacket{packet, ch}
621
622 // Lazily start background worker until we
623 // do our first write into the queue.
624 client.start.Do(func() {
625 go client.worker()
626 })
627
628 select {
629 case client.queue <- outgoingPacket:
630 default:
631 // Send would block, drop the packet
632 if client.DropHandler != nil {
633 client.DropHandler(packet)
634 }
635 ch <- ErrPacketDropped
636 client.wg.Done()
637 }
638
639 return packet.EventID, ch
640 }
641
642 // Capture asynchronously delivers a packet to the Sentry server with the default *Client.
643 // It is a no-op when client is nil. A channel is provided if it is important to check for a
644 // send's success.
645 func Capture(packet *Packet, captureTags map[string]string) (eventID string, ch chan error) {
646 return DefaultClient.Capture(packet, captureTags)
647 }
648
649 // CaptureMessage formats and delivers a string message to the Sentry server.
650 func (client *Client) CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string {
651 if client == nil {
652 return ""
653 }
654
655 if client.shouldExcludeErr(message) {
656 return ""
657 }
658
659 packet := NewPacket(message, append(append(interfaces, client.context.interfaces()...), &Message{message, nil})...)
660 eventID, _ := client.Capture(packet, tags)
661
662 return eventID
663 }
664
665 // CaptureMessage formats and delivers a string message to the Sentry server with the default *Client
666 func CaptureMessage(message string, tags map[string]string, interfaces ...Interface) string {
667 return DefaultClient.CaptureMessage(message, tags, interfaces...)
668 }
669
670 // CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent.
671 func (client *Client) CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string {
672 if client == nil {
673 return ""
674 }
675
676 if client.shouldExcludeErr(message) {
677 return ""
678 }
679
680 packet := NewPacket(message, append(append(interfaces, client.context.interfaces()...), &Message{message, nil})...)
681 eventID, ch := client.Capture(packet, tags)
682 if eventID != "" {
683 <-ch
684 }
685
686 return eventID
687 }
688
689 // CaptureMessageAndWait is identical to CaptureMessage except it blocks and waits for the message to be sent.
690 func CaptureMessageAndWait(message string, tags map[string]string, interfaces ...Interface) string {
691 return DefaultClient.CaptureMessageAndWait(message, tags, interfaces...)
692 }
693
694 // CaptureErrors formats and delivers an error to the Sentry server.
695 // Adds a stacktrace to the packet, excluding the call to this method.
696 func (client *Client) CaptureError(err error, tags map[string]string, interfaces ...Interface) string {
697 if client == nil {
698 return ""
699 }
700
701 if err == nil {
702 return ""
703 }
704
705 if client.shouldExcludeErr(err.Error()) {
706 return ""
707 }
708
709 extra := extractExtra(err)
710 cause := pkgErrors.Cause(err)
711
712 packet := NewPacketWithExtra(err.Error(), extra, append(append(interfaces, client.context.interfaces()...), NewException(cause, GetOrNewStacktrace(cause, 1, 3, client.includePaths)))...)
713 eventID, _ := client.Capture(packet, tags)
714
715 return eventID
716 }
717
718 // CaptureErrors formats and delivers an error to the Sentry server using the default *Client.
719 // Adds a stacktrace to the packet, excluding the call to this method.
720 func CaptureError(err error, tags map[string]string, interfaces ...Interface) string {
721 return DefaultClient.CaptureError(err, tags, interfaces...)
722 }
723
724 // CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent
725 func (client *Client) CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string {
726 if client == nil {
727 return ""
728 }
729
730 if client.shouldExcludeErr(err.Error()) {
731 return ""
732 }
733
734 extra := extractExtra(err)
735 cause := pkgErrors.Cause(err)
736
737 packet := NewPacketWithExtra(err.Error(), extra, append(append(interfaces, client.context.interfaces()...), NewException(cause, GetOrNewStacktrace(cause, 1, 3, client.includePaths)))...)
738 eventID, ch := client.Capture(packet, tags)
739 if eventID != "" {
740 <-ch
741 }
742
743 return eventID
744 }
745
746 // CaptureErrorAndWait is identical to CaptureError, except it blocks and assures that the event was sent
747 func CaptureErrorAndWait(err error, tags map[string]string, interfaces ...Interface) string {
748 return DefaultClient.CaptureErrorAndWait(err, tags, interfaces...)
749 }
750
751 // CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs.
752 // If an error is captured, both the error and the reported Sentry error ID are returned.
753 func (client *Client) CapturePanic(f func(), tags map[string]string, interfaces ...Interface) (err interface{}, errorID string) {
754 // Note: This doesn't need to check for client, because we still want to go through the defer/recover path
755 // Down the line, Capture will be noop'd, so while this does a _tiny_ bit of overhead constructing the
756 // *Packet just to be thrown away, this should not be the normal case. Could be refactored to
757 // be completely noop though if we cared.
758 defer func() {
759 var packet *Packet
760 err = recover()
761 switch rval := err.(type) {
762 case nil:
763 return
764 case error:
765 if client.shouldExcludeErr(rval.Error()) {
766 return
767 }
768 packet = NewPacket(rval.Error(), append(append(interfaces, client.context.interfaces()...), NewException(rval, NewStacktrace(2, 3, client.includePaths)))...)
769 default:
770 rvalStr := fmt.Sprint(rval)
771 if client.shouldExcludeErr(rvalStr) {
772 return
773 }
774 packet = NewPacket(rvalStr, append(append(interfaces, client.context.interfaces()...), NewException(errors.New(rvalStr), NewStacktrace(2, 3, client.includePaths)))...)
775 }
776
777 errorID, _ = client.Capture(packet, tags)
778 }()
779
780 f()
781 return
782 }
783
784 // CapturePanic calls f and then recovers and reports a panic to the Sentry server if it occurs.
785 // If an error is captured, both the error and the reported Sentry error ID are returned.
786 func CapturePanic(f func(), tags map[string]string, interfaces ...Interface) (interface{}, string) {
787 return DefaultClient.CapturePanic(f, tags, interfaces...)
788 }
789
790 // CapturePanicAndWait is identical to CaptureError, except it blocks and assures that the event was sent
791 func (client *Client) CapturePanicAndWait(f func(), tags map[string]string, interfaces ...Interface) (err interface{}, errorID string) {
792 // Note: This doesn't need to check for client, because we still want to go through the defer/recover path
793 // Down the line, Capture will be noop'd, so while this does a _tiny_ bit of overhead constructing the
794 // *Packet just to be thrown away, this should not be the normal case. Could be refactored to
795 // be completely noop though if we cared.
796 defer func() {
797 var packet *Packet
798 err = recover()
799 switch rval := err.(type) {
800 case nil:
801 return
802 case error:
803 if client.shouldExcludeErr(rval.Error()) {
804 return
805 }
806 packet = NewPacket(rval.Error(), append(append(interfaces, client.context.interfaces()...), NewException(rval, NewStacktrace(2, 3, client.includePaths)))...)
807 default:
808 rvalStr := fmt.Sprint(rval)
809 if client.shouldExcludeErr(rvalStr) {
810 return
811 }
812 packet = NewPacket(rvalStr, append(append(interfaces, client.context.interfaces()...), NewException(errors.New(rvalStr), NewStacktrace(2, 3, client.includePaths)))...)
813 }
814
815 var ch chan error
816 errorID, ch = client.Capture(packet, tags)
817 if errorID != "" {
818 <-ch
819 }
820 }()
821
822 f()
823 return
824 }
825
826 // CapturePanicAndWait is identical to CaptureError, except it blocks and assures that the event was sent
827 func CapturePanicAndWait(f func(), tags map[string]string, interfaces ...Interface) (interface{}, string) {
828 return DefaultClient.CapturePanicAndWait(f, tags, interfaces...)
829 }
830
831 func (client *Client) Close() {
832 close(client.queue)
833 }
834
835 func Close() { DefaultClient.Close() }
836
837 // Wait blocks and waits for all events to finish being sent to Sentry server
838 func (client *Client) Wait() {
839 client.wg.Wait()
840 }
841
842 // Wait blocks and waits for all events to finish being sent to Sentry server
843 func Wait() { DefaultClient.Wait() }
844
845 func (client *Client) URL() string {
846 client.mu.RLock()
847 defer client.mu.RUnlock()
848
849 return client.url
850 }
851
852 func URL() string { return DefaultClient.URL() }
853
854 func (client *Client) ProjectID() string {
855 client.mu.RLock()
856 defer client.mu.RUnlock()
857
858 return client.projectID
859 }
860
861 func ProjectID() string { return DefaultClient.ProjectID() }
862
863 func (client *Client) Release() string {
864 client.mu.RLock()
865 defer client.mu.RUnlock()
866
867 return client.release
868 }
869
870 func Release() string { return DefaultClient.Release() }
871
872 func IncludePaths() []string { return DefaultClient.IncludePaths() }
873
874 func (client *Client) IncludePaths() []string {
875 client.mu.RLock()
876 defer client.mu.RUnlock()
877
878 return client.includePaths
879 }
880
881 func SetIncludePaths(p []string) { DefaultClient.SetIncludePaths(p) }
882
883 func (client *Client) SetIncludePaths(p []string) {
884 client.mu.Lock()
885 defer client.mu.Unlock()
886
887 client.includePaths = p
888 }
889
890 func (c *Client) SetUserContext(u *User) {
891 c.mu.Lock()
892 defer c.mu.Unlock()
893 c.context.setUser(u)
894 }
895
896 func (c *Client) SetHttpContext(h *Http) {
897 c.mu.Lock()
898 defer c.mu.Unlock()
899 c.context.setHttp(h)
900 }
901
902 func (c *Client) SetTagsContext(t map[string]string) {
903 c.mu.Lock()
904 defer c.mu.Unlock()
905 c.context.setTags(t)
906 }
907
908 func (c *Client) ClearContext() {
909 c.mu.Lock()
910 defer c.mu.Unlock()
911 c.context.clear()
912 }
913
914 func SetUserContext(u *User) { DefaultClient.SetUserContext(u) }
915 func SetHttpContext(h *Http) { DefaultClient.SetHttpContext(h) }
916 func SetTagsContext(t map[string]string) { DefaultClient.SetTagsContext(t) }
917 func ClearContext() { DefaultClient.ClearContext() }
918
919 // HTTPTransport is the default transport, delivering packets to Sentry via the
920 // HTTP API.
921 type HTTPTransport struct {
922 *http.Client
923 }
924
925 func (t *HTTPTransport) Send(url, authHeader string, packet *Packet) error {
926 if url == "" {
927 return nil
928 }
929
930 body, contentType, err := serializedPacket(packet)
931 if err != nil {
932 return fmt.Errorf("error serializing packet: %v", err)
933 }
934 req, err := http.NewRequest("POST", url, body)
935 if err != nil {
936 return fmt.Errorf("can't create new request: %v", err)
937 }
938 req.Header.Set("X-Sentry-Auth", authHeader)
939 req.Header.Set("User-Agent", userAgent)
940 req.Header.Set("Content-Type", contentType)
941 res, err := t.Do(req)
942 if err != nil {
943 return err
944 }
945 io.Copy(ioutil.Discard, res.Body)
946 res.Body.Close()
947 if res.StatusCode != 200 {
948 return fmt.Errorf("raven: got http status %d - x-sentry-error: %s", res.StatusCode, res.Header.Get("X-Sentry-Error"))
949 }
950 return nil
951 }
952
953 func serializedPacket(packet *Packet) (io.Reader, string, error) {
954 packetJSON, err := packet.JSON()
955 if err != nil {
956 return nil, "", fmt.Errorf("error marshaling packet %+v to JSON: %v", packet, err)
957 }
958
959 // Only deflate/base64 the packet if it is bigger than 1KB, as there is
960 // overhead.
961 if len(packetJSON) > 1000 {
962 buf := &bytes.Buffer{}
963 b64 := base64.NewEncoder(base64.StdEncoding, buf)
964 deflate, _ := zlib.NewWriterLevel(b64, zlib.BestCompression)
965 deflate.Write(packetJSON)
966 deflate.Close()
967 b64.Close()
968 return buf, "application/octet-stream", nil
969 }
970 return bytes.NewReader(packetJSON), "application/json", nil
971 }
972
973 var hostname string
974
975 func init() {
976 hostname, _ = os.Hostname()
977 }