summaryrefslogtreecommitdiff
path: root/src/Logstat/Eval.hs
blob: c9453b54046b380964aa5e7b3dbc85d0576b9678 (plain)
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
{-# LANGUAGE OverloadedStrings, FlexibleContexts, FlexibleInstances #-}
module Logstat.Eval where

import Data.Fixed (mod')
import Data.Foldable (foldl',toList)
import qualified Data.ByteString as B
import qualified Data.Heap       as Heap
import qualified Data.Map.Strict as Map

import Logstat.Types
import Logstat.Value
import Logstat.Regex


data State
  = StNone
  | StSortAscNum  !(Heap.Heap (SortItem AscNum ))
  | StSortAscBS   !(Heap.Heap (SortItem AscBS  ))
  | StSortDescNum !(Heap.Heap (SortItem DescNum))
  | StSortDescBS  !(Heap.Heap (SortItem DescBS ))
  | StGroup       !(Map.Map [Val] ()) -- TODO: Should add more state than '()'
  deriving Show

data SortItem a = SortItem !a !Event deriving Show

newtype AscNum  = AscNum  Double       deriving (Show,Eq)
newtype AscBS   = AscBS   B.ByteString deriving (Show,Eq)
newtype DescNum = DescNum Double       deriving (Show,Eq,Ord)
newtype DescBS  = DescBS  B.ByteString deriving (Show,Eq,Ord)

instance Ord AscNum where (AscNum a) <= (AscNum b) = a >= b
instance Ord AscBS  where (AscBS  a) <= (AscBS  b) = a >= b

instance Eq a  => Eq  (SortItem a) where (SortItem a _) == (SortItem b _) = a == b
instance Ord a => Ord (SortItem a) where (SortItem a _) <= (SortItem b _) = a <= b


newState :: [Stmt] -> [State]
newState = map st
  where
  st s = case s of
    SSort _ _ SortAscNum  -> StSortAscNum  mempty
    SSort _ _ SortAscBS   -> StSortAscBS   mempty
    SSort _ _ SortDescNum -> StSortDescNum mempty
    SSort _ _ SortDescBS  -> StSortDescBS  mempty
    SGroup _              -> StGroup       mempty
    _                     -> StNone


getField :: Event -> Field -> Either EvalError Val
getField st n = maybe (Left (UnknownField n)) return $ Map.lookup n st


evalExpr :: Expr -> Event -> Either EvalError Val
evalExpr expr ev = case expr of
  ELit e   -> Right e
  EField f -> getField ev f
  ENot e   -> bool . not . asBool <$> evalExpr e ev
  EIf e t f-> evalExpr e ev >>= \b -> evalExpr (if asBool b then t else f) ev

  ENeg e -> do
    v <- evalExpr e ev >>= asNum
    return $ num (- v)

  EMatch r e -> do
    v <- evalExpr e ev
    return $ bool $ reMatch r (asBS v)

  EExtract e r -> do
    v <- asBS <$> evalExpr e ev
    ma <- maybe (Left (NoExtract v)) return $ match r v
    return $ bs $ ma !! 1

  EReplace e r n ->
    -- TODO: Support subpattern substitution
    bs . gsub r (const n) . asBS <$> evalExpr e ev

  EOp op a' b' ->
    case op of
      OEq     -> bcmp (==)
      ONeq    -> bcmp (/=)
      OLt     -> bcmp (<)
      OGt     -> bcmp (>)
      OLe     -> bcmp (<=)
      OGe     -> bcmp (>=)
      OIEq    -> icmp (==)
      OINeq   -> icmp (/=)
      OILt    -> icmp (<)
      OIGt    -> icmp (>)
      OILe    -> icmp (<=)
      OIGe    -> icmp (>=)
      OConcat -> withab (return . asBS) $ \a b -> return $ bs $ B.append a b
      OPlus   -> iop (+)
      OMinus  -> iop (-)
      OMul    -> iop (*)
      ODiv    -> idiv (/)
      OMod    -> idiv mod'
      OPow    -> iop (**)
      OOr     -> with a' return $ \a -> if asBool a then return a else with b' return return
      OAnd    -> with a' return $ \a -> if asBool a then with b' return return else return a
    where
      with v f p = evalExpr v ev >>= f >>= p
      withab f p = with a' f $ \a -> with b' f $ \b -> p a b
      -- ByteString comparison
      bcmp f = withab (return . asBS) $ \a b -> return $ bool $ f a b
      -- Numeric comparison
      icmp f = withab asNum $ \a b -> return $ bool $ f a b
      -- Numeric operations
      iop f  = withab asNum $ \a b -> return $ num $ f a b
      -- Division with zero-check
      idiv f = withab asNum $ \a b ->
        if b == 0
          then Left DivByZero
          else return $ num $ f a b


-- The behavior of each statement is implemented in two functions:
--
-- step:
--   Process a single event. This function can update some internal state of
--   the statement and/or immediately return a (modified) event, to be
--   processed by the next statement in the chain.
--
-- final:
--   Return a list of aggregated/sorted events stored in the internal state of
--   the statement.


-- The sorting algorithm is optimized for the scenario where there are many
-- logs as input and we're only interested in the top n (100 or so) logs. This
-- isn't the most efficient algorithm for other scenarios, alternative
-- strategies could be added later.
-- The current algorithm uses a fixed size min-heap to efficiently filter out
-- all logs that would not make it to the top n. This heap is then sorted in
-- the final step.

step :: Stmt -> State -> Event -> (State, Either EvalError Event)
step stmt st ev = case stmt of
  SShow _     -> undefined -- Should be handled by extractShow
  SSet f e    -> (,) st $ evalExpr e ev >>= \v -> return $ Map.insert f v ev
  SFilter e   -> (,) st $ evalExpr e ev >>= \v -> if asBool v then return ev else Left Filtered

  SRegex f r p -> (,) st $ do
    val <- asBS <$> getField ev f
    ma <- maybe (Left (NoMatch f val)) return $ match r val
    return $ foldl' ins ev $ zip ma p
    where
      ins s (_, Nothing) = s
      ins s (v, Just n)  = Map.insert n (bs v) s

  SSort n e _ ->
    case st of
      StSortAscNum  hp -> run StSortAscNum  hp (\v -> AscNum <$> asNum v)
      StSortAscBS   hp -> run StSortAscBS   hp (return . AscBS . asBS)
      StSortDescNum hp -> run StSortDescNum hp (\v -> DescNum <$> asNum v)
      StSortDescBS  hp -> run StSortDescBS  hp (return . DescBS . asBS)
      _                -> error "Invalid state for sort"
    where
    run wrap hp f =
      case evalExpr e ev >>= f of
        Left err -> (st, Left err)
        Right val -> (wrap (ins hp val), Left Filtered)
    ins hp val =
      let si = SortItem val ev in
      if Heap.size hp < n
        then Heap.insert si hp
        else if Heap.minimum hp < si
          then Heap.insert si $ Heap.deleteMin hp
          else hp

  SGroup f ->
    let StGroup m = st in
    case mapM (getField ev) f of
      Left err -> (st, Left err)
      Right v -> (StGroup $ Map.insert v () m, Left Filtered)


final :: Stmt -> State -> [Event]
final stmt st = case stmt of
  SSort _ _ _ ->
    case st of
      StSortAscNum  hp -> f hp
      StSortAscBS   hp -> f hp
      StSortDescNum hp -> f hp
      StSortDescBS  hp -> f hp
      _                -> error "Invalid state for sort"
    where
    f hp = map (\(SortItem _ ev) -> ev) $ reverse $ toList hp

  SGroup f ->
    let StGroup m = st in
    map (\(k,_) -> Map.fromList $ zip f k) $ Map.toList m

  _ -> []


type Step = [State] -> Event -> ([State], Either EvalError Event)

stepL :: [Stmt] -> Step
stepL stmts =
  -- "materialize" the statements into a list of (State -> Event -> ..)
  -- functions. This hopefully causes the pattern matching on the Stmt value to
  -- be performed only once, thus speeding up evaluation. But I obviously need
  -- to measure the effect of this optimization to see if it even works at all.
  let fs = map step stmts in loop fs
  where
  loop (f:fns) (st:sts) ev =
    case f st ev of
      (st', Left err) -> (st':sts, Left err)
      (st', Right e) -> let (sts', e') = loop fns sts e in (st':sts', e')
  loop _ _ ev = ([], Right ev)


finalL :: [Stmt] -> [State] -> [Either EvalError Event]
finalL stmts =
  -- Same thing as in stepL
  let fns = zip (stepL' stmts) (map final stmts) in loop fns
  where
  stepL' :: [Stmt] -> [Step]
  stepL' [] = []
  stepL' (_:xs) = stepL xs : stepL' xs

  loop (f:fns) (st:sts) =
    let (sts', l1) = steps (fst f) sts (snd f st)
        l2 = loop fns sts'
    in l1 ++ l2
  loop _ _ = []

  steps :: Step -> [State] -> [Event] -> ([State], [Either EvalError Event])
  steps _ st [] = (st, [])
  steps f st (ev:evs) =
    let (st', r) = f st ev
        (st'', evs') = steps f st' evs
    in (,) st'' $ case r of
      Left Filtered -> evs'
      _             -> r : evs'