]> git.immae.eu Git - github/fretlink/haskell-graylog.git/blob - src/Graylog/UDP.hs
cd7fe5a1450fc1cb9f0b48649b9487c084e3f0ab
[github/fretlink/haskell-graylog.git] / src / Graylog / UDP.hs
1 module Graylog.UDP
2 ( sendLog
3
4 , module Export
5 ) where
6
7 import Data.Aeson
8 import Data.ByteString.Builder
9 import qualified Data.ByteString.Lazy as LBS
10 import Data.Monoid
11 import Data.Word
12 import Network.Socket.ByteString.Lazy
13 import System.Random
14
15 import Graylog.Gelf as Export
16 import Graylog.Types as Export
17
18 sendLog :: Graylog -> GELF -> IO ()
19 sendLog glog msg = do
20 cks <- chunky glog raw
21 mapM_ (send $ _graylogSocket glog) cks
22 where
23 raw = encode msg
24
25 chunky :: Graylog -> LBS.ByteString -> IO [LBS.ByteString]
26 chunky glog raw = do
27 groupId <- randomIO
28 let groups = divide totalNum raw
29 return $ append groupId groups seqNums
30 where
31 magic = word8 0x1e <> word8 0x0f
32 seqNums = [0..] :: [Word8]
33 totalNum = if excess > 0 then count + 1 else count
34 (count, excess) = quotRem (LBS.length raw) gsize
35 hlen = 12
36 gsize = (fromIntegral (_graylogChunkSize glog)) - hlen
37
38 divide 0 dat = [dat]
39 divide num dat = let (pre, post) = LBS.splitAt gsize dat
40 in pre : divide (num - 1) post
41
42 append _ [] _ = []
43 append _ _ [] = error "the impossible has happened."
44 append gid (g:gs) (s:ss) = (toLazyByteString
45 $ magic
46 <> word64BE gid
47 <> word8 s
48 <> word8 (fromIntegral totalNum)
49 <> lazyByteString g) : append gid gs ss