; -*- mode: clojure; -*-
; vi: filetype=clojure

(require 'aero.core)

(logging/init {:file "riemann.log"})

(let [host "127.0.0.1"]
  (tcp-server {:host host})
  (udp-server {:host host}))

(instrumentation {:enabled? false})

(periodically-expire 10)

(defn int-cores [es]
  (map
    (fn [e] (update e :cores (fn [v] (Integer/parseInt v)))) es))

(defn high-cpu-load [{:keys [cores metric]}]
  (< (* 2 cores) metric))

(def config
  (let [home (System/getProperty "user.home")]
    (aero.core/read-config (str home "/.re-ops.edn") {:profile :dev})))

(def smtp (get-in config [:shared :smtp]))

(def email (mailer smtp))

(def to (get-in config [:riemann :to]))

(def from (get-in config [:riemann :from]))

(def tell-ops (rollup 5 3600 (email to)))

(let [index (index)]
  (streams
    (default :ttl 60
       index

      (where (service "usb")
          (by :host
             (changed :result {:pairs? true}
             (fn [[e1 e2]]
               (when e1
                 (when-not (= (hash-set e1) (hash-set e2))
                   (riemann.email/email-event smtp {:to to :from from} e1)))))))

      (where (and (tagged "success") (not (expired? event)))
        (where (service "disk-usage")
           (by :host
              (where (<= 85 metric) tell-ops)))

        (where (service "entropy/available")
           (by :host
             (fixed-event-window 5
                (smap folds/mean
                   (where (<= 0 metric 1000) tell-ops)))))

        (where (service "cpu/idle")
           (by :host
             (fixed-event-window 10
                (smap folds/mean
                   (where (<= 0 metric 10) tell-ops)))))

        (where (service "load/one")
           (by :host
              (fixed-event-window 10
                (smap int-cores
                   (smap folds/mean
                     (where* high-cpu-load tell-ops))))))

        (where (service "load/five")
           (by :host
             (fixed-event-window 5
               (smap int-cores
                  (smap folds/mean
                    (where* high-cpu-load tell-ops))))))))))