Skip to content

Commit

Permalink
(where predicate ... (else ...))
Browse files Browse the repository at this point in the history
(where used to work like (when), passing events which matched predicate
to each child and doing nothing when events did not match. Now, children
inside one (or more) expressions wrapped in (else) receive events which
*do not* match predicate. For instance:

(where (metric < 500)
  (with :state "ok" index)
  (else
    (with :state "warning" index)
    (email "ops@foo.org")))
  • Loading branch information
aphyr committed Nov 10, 2012
1 parent c2d649f commit e198347
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
36 changes: 28 additions & 8 deletions src/riemann/streams.clj
Expand Up @@ -958,6 +958,17 @@
(list (keyword expr) 'event)
expr))))

(defn where-partition-clauses
"Given expressions like (a (else b) c (else d)), returns [[a c] [b d]]"
[exprs]
(map vec
((juxt remove
(comp (partial mapcat rest) filter))
(fn [expr]
(when (list? expr)
(= 'else (first expr))))
exprs)))

(defmacro where-event
"Passes on events where expr is true, binding the provided symbol
to the event during evaluation.
Expand All @@ -977,19 +988,28 @@
; Match any event where metric is either 1, 2, 3, or 4.
(where (metric 1 2 3 4) ...)
; Match a event where the metric is negative AND the state is ok.
(where (and (> 0 metric)
(state \"ok\")) ...)
(state \"ok\")) ...)
; Match a event where the host begins with web
(where (host #\"^web\") ...)"
(where (host #\"^web\") ...)
If a child begins with (else ...), the else's body is executed when expr is
false. For instance:
(where (service \"www\")
(notify-www-team)
(else
(notify-misc-team)))"
[expr & children]
(let [p (where-rewrite expr)]
`(let [kids# [~@children]]
(fn [event#]
(when (let [~'event event#] ~p)
(call-rescue event# kids#))))))
(let [p (where-rewrite expr)
[true-kids else-kids] (where-partition-clauses children)]
`(fn [event#]
(if (let [~'event event#] ~p)
(call-rescue event# ~true-kids)
(call-rescue event# ~else-kids)))))

(defn update-index
"Updates the given index with all events received."
Expand Down
15 changes: 15 additions & 0 deletions test/riemann/test/streams.clj
Expand Up @@ -212,6 +212,21 @@
(is (= (deref r)
[{:tags ["foo"]} {:tags ["foo" "bar"]}]))))

(deftest where-else
; Where should take an else clause.
(let [a (atom [])
b (atom [])]
(run-stream
(where (service #"a")
#(swap! a conj (:service %))
(else #(swap! b conj (:service %))))
[{:service "cat"}
{:service "dog"}
{:service nil}
{:service "badger"}])
(is (= @a ["cat" "badger"]))
(is (= @b ["dog" nil]))))

(deftest default-kv
(let [r (ref nil)
s (default :service "foo" (register r))]
Expand Down

0 comments on commit e198347

Please sign in to comment.