aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/Graylog/Types.hs
blob: 5ec779bb1e46db9d4d5be0d8ea5e64e932ca9696 (plain) (blame)
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
{-# LANGUAGE LambdaCase      #-}
{-# LANGUAGE RecordWildCards #-}

module Graylog.Types
   ( Graylog
   , _graylogHost
   , _graylogPort
   , _graylogAddress
   , _graylogSocket
   , _graylogHostName
   , _graylogChunkSize
   , ChunkSize

   , defaultChunkSize
   , openGraylog
   , closeGraylog
   ) where

import           Data.List
import           Data.Text      (Text)
import qualified Data.Text      as T
import           Network.BSD
import           Network.Socket

-- | The maximum size of each datagram when using UDP transit methods.
type ChunkSize = Word

-- | Handle for a socket connected to Graylog. In some cases this socket
-- is UDP and will not have a maintained session.
data Graylog
   = Graylog
      { _graylogHost      :: String
      , _graylogPort      :: String
      , _graylogAddress   :: AddrInfo
      , _graylogSocket    :: Socket
      , _graylogHostName  :: Text
      , _graylogChunkSize :: ChunkSize
      }

defaultChunkSize :: ChunkSize
defaultChunkSize = 8192

openGraylog
   :: HostName          -- ^ The host on which graylog is running.
   -> ServiceName       -- ^ The port on which graylog is running.
   -> ChunkSize         -- ^ The maximum size of each UDP datagram.
   -> IO (Either String Graylog)
openGraylog h p cksize
   | cksize < 1024 = return $ Left "ChunkSize must be at least 1024."
   | otherwise     = getAddrInfo Nothing (Just h) (Just p) >>= \case
   []     -> return $ Left "No address info found."
   infos ->
      case find (\i -> addrSocketType i == Datagram) infos of
         Nothing -> return $ Left "No datagram info found for address."
         Just  i -> do
            sock <- socket (addrFamily i) Datagram defaultProtocol
            connect sock (addrAddress i)
            hostname <- getHostName
            return $ Right $ Graylog h p i sock (T.pack hostname) cksize

closeGraylog :: Graylog -> IO ()
closeGraylog Graylog{..} = close _graylogSocket