-
Notifications
You must be signed in to change notification settings - Fork 2
/
shipper.go
106 lines (84 loc) · 1.92 KB
/
shipper.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/cenkalti/backoff"
"github.com/gojektech/heimdall/httpclient"
)
type Shipper struct {
Source chan []byte
SplunkURL string
SplunkKey string
}
type SplunkResponse struct {
Text string `json:"text"`
Code int `json:"code"`
}
type SplunkHTTPClient struct {
client http.Client
SplunkKey string
}
func (c *SplunkHTTPClient) Do(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", fmt.Sprintf("Splunk %s", c.SplunkKey))
req.Header.Set("Content-Type", "application/json")
return c.client.Do(req)
}
func (s *Shipper) Ship() {
log.Println("Shipper: Start")
splunkClient := httpclient.NewClient(
httpclient.WithHTTPClient(
&SplunkHTTPClient{
client: *http.DefaultClient,
SplunkKey: s.SplunkKey,
},
),
)
for {
select {
case msg := <-s.Source:
splunkMsg := fmt.Sprintf(
`{"source": "elasticsearch-to-splunk", "event": %s}`,
msg,
)
shipLog := func() error {
log.Println("Shipper: shipping log")
res, err := splunkClient.Post(
s.SplunkURL,
bytes.NewReader([]byte(splunkMsg)),
http.Header{},
)
if err != nil {
log.Printf("Shipper: errored shipping log:%s\n", err)
return err
}
if 200 <= res.StatusCode && res.StatusCode < 300 {
log.Printf("Shipper: shipped log: %s\n", splunkMsg)
return nil
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Shipper: could not read body: %s\n", err)
return err
}
log.Printf(
"Shipper: received non-200 status code %d\n%s",
res.StatusCode,
string(body),
)
return fmt.Errorf("HTTP NOT OKAY")
}
err := backoff.Retry(
shipLog,
backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 10),
)
if err != nil {
log.Fatalf(
"Shipper: Fatal err encountered after 10 retries: %s\n", err,
)
}
}
}
}