This repository has been archived by the owner on Feb 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
gelf.go
274 lines (235 loc) · 6.04 KB
/
gelf.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
package gelf
import (
"encoding/json"
"errors"
"fmt"
"log"
"net"
"os"
"strconv"
"strings"
"syscall"
"time"
"github.com/gliderlabs/logspout/router"
"github.com/Graylog2/go-gelf/gelf"
)
const defaultRetryCount = 10
var (
hostname string
retryCount uint
econnResetErrStr string
)
func init() {
hostname, _ = os.Hostname()
econnResetErrStr = fmt.Sprintf("write: %s", syscall.ECONNRESET.Error())
router.AdapterFactories.Register(NewGelfAdapter, "gelf")
setRetryCount()
}
func setRetryCount() {
if count, err := strconv.Atoi(getopt("RETRY_COUNT", strconv.Itoa(defaultRetryCount))); err != nil {
retryCount = uint(defaultRetryCount)
} else {
retryCount = uint(count)
}
debug("Graylog: setting retryCount to:", retryCount)
}
func getopt(name, dfault string) string {
value := os.Getenv(name)
if value == "" {
value = dfault
}
return value
}
func debug(v ...interface{}) {
if os.Getenv("DEBUG") != "" {
log.Println(v...)
}
}
func getHostname() string {
hostname, _ = os.Hostname()
return hostname
}
// GelfAdapter is an adapter that streams UDP JSON to Graylog
type GelfAdapter struct {
conn net.Conn
route *router.Route
transport router.AdapterTransport
}
// NewGelfAdapter creates a GelfAdapter with UDP as the default transport.
func NewGelfAdapter(route *router.Route) (router.LogAdapter, error) {
transport, found := router.AdapterTransports.Lookup(route.AdapterTransport("udp"))
if !found {
return nil, errors.New("bad transport: " + route.Adapter)
}
conn, err := transport.Dial(route.Address, route.Options)
if err != nil {
return nil, err
}
hostname = getHostname()
return &GelfAdapter{
route: route,
conn: conn,
transport: transport,
}, nil
}
// Stream implements the router.LogAdapter interface.
func (a *GelfAdapter) Stream(logstream chan *router.Message) {
for m := range logstream {
extra, err := extraFields(m)
if err != nil {
log.Println("Graylog:", err)
continue
}
messageHostname := hostname
if messageHostname == "" {
// Same default as https://github.com/gliderlabs/logspout/blob/master/adapters/syslog/syslog.go
messageHostname = m.Container.Config.Hostname
}
shortMessage := m.Data
if shortMessage == "" {
continue
}
fullMessage := ""
shortMessageNewLine := strings.Index(shortMessage, "\n")
if shortMessageNewLine != -1 {
fullMessage = shortMessage
shortMessage = shortMessage[:shortMessageNewLine]
}
msg := GelfMessage{
Version: "1.1",
Host: messageHostname,
ShortMessage: shortMessage,
FullMessage: fullMessage,
Timestamp: float64(m.Time.UnixNano()/int64(time.Millisecond)) / 1000.0,
Level: gelf.LOG_INFO,
ContainerId: m.Container.ID,
ContainerName: m.Container.Name[1:], // might be better to use strings.TrimLeft() to remove the first /
ContainerCmd: strings.Join(m.Container.Config.Cmd," "),
ImageId: m.Container.Image,
ImageName: m.Container.Config.Image,
Created: m.Container.Created.Format(time.RFC3339Nano),
}
if m.Source == "stderr" {
msg.Level = gelf.LOG_ERR
}
js, err := json.Marshal(msg)
if err != nil {
log.Println("Graylog:", err)
continue
}
if len(extra) > 2 {
js = append(js[:len(js)-1], ',')
js = append(js, extra[1:]...)
}
js = append(js, 0)
_, err = a.conn.Write(js)
if err != nil {
log.Println("Graylog:", err)
switch a.conn.(type) {
case *net.UDPConn:
continue
default:
if err = a.retry(js, err); err != nil {
log.Panicf("Graylog retry err: %+v", err)
return
}
}
}
}
}
func (a *GelfAdapter) retry(buf []byte, err error) error {
if opError, ok := err.(*net.OpError); ok {
if (opError.Temporary() && opError.Err.Error() != econnResetErrStr) || opError.Timeout() {
retryErr := a.retryTemporary(buf)
if retryErr == nil {
return nil
}
}
}
if reconnErr := a.reconnect(); reconnErr != nil {
return reconnErr
}
if _, err = a.conn.Write(buf); err != nil {
log.Println("Graylog: reconnect failed")
return err
}
log.Println("Graylog: reconnect successful")
return nil
}
func (a *GelfAdapter) retryTemporary(buf []byte) error {
log.Printf("Graylog: retrying tcp up to %v times\n", retryCount)
err := retryExp(func() error {
_, err := a.conn.Write(buf)
if err == nil {
log.Println("Graylog: retry successful")
return nil
}
return err
}, retryCount)
if err != nil {
log.Println("Graylog: retry failed")
return err
}
return nil
}
func (a *GelfAdapter) reconnect() error {
log.Printf("Graylog: reconnecting up to %v times\n", retryCount)
err := retryExp(func() error {
conn, err := a.transport.Dial(a.route.Address, a.route.Options)
if err != nil {
return err
}
a.conn = conn
return nil
}, retryCount)
if err != nil {
return err
}
return nil
}
func retryExp(fun func() error, tries uint) error {
try := uint(0)
for {
err := fun()
if err == nil {
return nil
}
try++
if try > tries {
return err
}
time.Sleep((1 << try) * 10 * time.Millisecond)
}
}
type GelfMessage struct {
Version string `json:"version"`
Host string `json:"host,omitempty"`
ShortMessage string `json:"short_message"`
FullMessage string `json:"full_message,omitempty"`
Timestamp float64 `json:"timestamp,omitempty"`
Level int32 `json:"level,omitempty"`
ImageId string `json:"_image_id,omitempty"`
ImageName string `json:"_image_name,omitempty"`
ContainerId string `json:"_container_id,omitempty"`
ContainerName string `json:"_container_name,omitempty"`
ContainerCmd string `json:"_command,omitempty"`
Created string `json:"_created,omitempty"`
}
func extraFields(m *router.Message) (json.RawMessage, error) {
extra := map[string]interface{}{
}
for name, label := range m.Container.Config.Labels {
if len(name) > 5 && strings.ToLower(name[0:5]) == "gelf_" {
extra[name[4:]] = label
}
}
swarmnode := m.Container.Node
if swarmnode != nil {
extra["_swarm_node"] = swarmnode.Name
}
rawExtra, err := json.Marshal(extra)
if err != nil {
return nil, err
}
return rawExtra, nil
}