Debian Codegraph @

gelf/udpwriter.go

raw symbols SCIP
1 // Copyright 2012 SocialCode. All rights reserved.
2 // Use of this source code is governed by the MIT
3 // license that can be found in the LICENSE file.
4
5 package gelf
6
7 import (
8 "bytes"
9 "compress/flate"
10 "compress/gzip"
11 "compress/zlib"
12 "crypto/rand"
13 "fmt"
14 "io"
15 "net"
16 "os"
17 "path"
18 "sync"
19 )
20
21 type UDPWriter struct {
22 GelfWriter
23 CompressionLevel int // one of the consts from compress/flate
24 CompressionType CompressType
25 }
26
27 // What compression type the writer should use when sending messages
28 // to the graylog2 server
29 type CompressType int
30
31 const (
32 CompressGzip CompressType = iota
33 CompressZlib
34 CompressNone
35 )
36
37 // Used to control GELF chunking. Should be less than (MTU - len(UDP
38 // header)).
39 //
40 // TODO: generate dynamically using Path MTU Discovery?
41 const (
42 ChunkSize = 1420
43 chunkedHeaderLen = 12
44 chunkedDataLen = ChunkSize - chunkedHeaderLen
45 )
46
47 var (
48 magicChunked = []byte{0x1e, 0x0f}
49 magicZlib = []byte{0x78}
50 magicGzip = []byte{0x1f, 0x8b}
51 )
52
53 // numChunks returns the number of GELF chunks necessary to transmit
54 // the given compressed buffer.
55 func numChunks(b []byte) int {
56 lenB := len(b)
57 if lenB <= ChunkSize {
58 return 1
59 }
60 return len(b)/chunkedDataLen + 1
61 }
62
63 // New returns a new GELF Writer. This writer can be used to send the
64 // output of the standard Go log functions to a central GELF server by
65 // passing it to log.SetOutput()
66 func NewUDPWriter(addr string) (*UDPWriter, error) {
67 var err error
68 w := new(UDPWriter)
69 w.CompressionLevel = flate.BestSpeed
70
71 if w.conn, err = net.Dial("udp", addr); err != nil {
72 return nil, err
73 }
74 if w.hostname, err = os.Hostname(); err != nil {
75 return nil, err
76 }
77
78 w.Facility = path.Base(os.Args[0])
79
80 return w, nil
81 }
82
83 // writes the gzip compressed byte array to the connection as a series
84 // of GELF chunked messages. The format is documented at
85 // http://docs.graylog.org/en/2.1/pages/gelf.html as:
86 //
87 // 2-byte magic (0x1e 0x0f), 8 byte id, 1 byte sequence id, 1 byte
88 // total, chunk-data
89 func (w *GelfWriter) writeChunked(zBytes []byte) (err error) {
90 b := make([]byte, 0, ChunkSize)
91 buf := bytes.NewBuffer(b)
92 nChunksI := numChunks(zBytes)
93 if nChunksI > 128 {
94 return fmt.Errorf("msg too large, would need %d chunks", nChunksI)
95 }
96 nChunks := uint8(nChunksI)
97 // use urandom to get a unique message id
98 msgId := make([]byte, 8)
99 n, err := io.ReadFull(rand.Reader, msgId)
100 if err != nil || n != 8 {
101 return fmt.Errorf("rand.Reader: %d/%s", n, err)
102 }
103
104 bytesLeft := len(zBytes)
105 for i := uint8(0); i < nChunks; i++ {
106 buf.Reset()
107 // manually write header. Don't care about
108 // host/network byte order, because the spec only
109 // deals in individual bytes.
110 buf.Write(magicChunked) //magic
111 buf.Write(msgId)
112 buf.WriteByte(i)
113 buf.WriteByte(nChunks)
114 // slice out our chunk from zBytes
115 chunkLen := chunkedDataLen
116 if chunkLen > bytesLeft {
117 chunkLen = bytesLeft
118 }
119 off := int(i) * chunkedDataLen
120 chunk := zBytes[off : off+chunkLen]
121 buf.Write(chunk)
122
123 // write this chunk, and make sure the write was good
124 n, err := w.conn.Write(buf.Bytes())
125 if err != nil {
126 return fmt.Errorf("Write (chunk %d/%d): %s", i,
127 nChunks, err)
128 }
129 if n != len(buf.Bytes()) {
130 return fmt.Errorf("Write len: (chunk %d/%d) (%d/%d)",
131 i, nChunks, n, len(buf.Bytes()))
132 }
133
134 bytesLeft -= chunkLen
135 }
136
137 if bytesLeft != 0 {
138 return fmt.Errorf("error: %d bytes left after sending", bytesLeft)
139 }
140 return nil
141 }
142
143 // 1k bytes buffer by default
144 var bufPool = sync.Pool{
145 New: func() interface{} {
146 return bytes.NewBuffer(make([]byte, 0, 1024))
147 },
148 }
149
150 func newBuffer() *bytes.Buffer {
151 b := bufPool.Get().(*bytes.Buffer)
152 if b != nil {
153 b.Reset()
154 return b
155 }
156 return bytes.NewBuffer(nil)
157 }
158
159 // WriteMessage sends the specified message to the GELF server
160 // specified in the call to New(). It assumes all the fields are
161 // filled out appropriately. In general, clients will want to use
162 // Write, rather than WriteMessage.
163 func (w *UDPWriter) WriteMessage(m *Message) (err error) {
164 mBuf := newBuffer()
165 defer bufPool.Put(mBuf)
166 if err = m.MarshalJSONBuf(mBuf); err != nil {
167 return err
168 }
169 mBytes := mBuf.Bytes()
170
171 var (
172 zBuf *bytes.Buffer
173 zBytes []byte
174 )
175
176 var zw io.WriteCloser
177 switch w.CompressionType {
178 case CompressGzip:
179 zBuf = newBuffer()
180 defer bufPool.Put(zBuf)
181 zw, err = gzip.NewWriterLevel(zBuf, w.CompressionLevel)
182 case CompressZlib:
183 zBuf = newBuffer()
184 defer bufPool.Put(zBuf)
185 zw, err = zlib.NewWriterLevel(zBuf, w.CompressionLevel)
186 case CompressNone:
187 zBytes = mBytes
188 default:
189 panic(fmt.Sprintf("unknown compression type %d",
190 w.CompressionType))
191 }
192 if zw != nil {
193 if err != nil {
194 return
195 }
196 if _, err = zw.Write(mBytes); err != nil {
197 zw.Close()
198 return
199 }
200 zw.Close()
201 zBytes = zBuf.Bytes()
202 }
203
204 if numChunks(zBytes) > 1 {
205 return w.writeChunked(zBytes)
206 }
207 n, err := w.conn.Write(zBytes)
208 if err != nil {
209 return
210 }
211 if n != len(zBytes) {
212 return fmt.Errorf("bad write (%d/%d)", n, len(zBytes))
213 }
214
215 return nil
216 }
217
218 // Write encodes the given string in a GELF message and sends it to
219 // the server specified in New().
220 func (w *UDPWriter) Write(p []byte) (n int, err error) {
221 // 1 for the function that called us.
222 file, line := getCallerIgnoringLogMulti(1)
223
224 m := constructMessage(p, w.hostname, w.Facility, file, line)
225
226 if err = w.WriteMessage(m); err != nil {
227 return 0, err
228 }
229
230 return len(p), nil
231 }