-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.

--[[
Graphs the Heka memory statistics using the heka.memstat message generated by
pipeline/report.go.

Config:

- rows (uint, optional, default 1440)
    Sets the size of the sliding window i.e., 1440 rows representing 60
    seconds per row is a 24 sliding hour window with 1 minute resolution.

- sec_per_row (uint, optional, default 60)
    Sets the size of each bucket (resolution in seconds) in the sliding
    window.

- anomaly_config (string, optional)
    See :ref:`sandbox_anomaly_module`.

- preservation_version (uint, optional, default 0)
    If `preserve_data = true` is set in the SandboxFilter configuration, then
    this value should be incremented every time the `rows` or `sec_per_row`
    configuration is changed to prevent the plugin from failing to start
    during data restoration.

*Example Heka Configuration*

.. code-block:: ini

    [HekaMemstat]
    type = "SandboxFilter"
    filename = "lua_filters/heka_memstat.lua"
    ticker_interval = 60
    preserve_data = true
    message_matcher = "Type == 'heka.memstat'"

--]]
_PRESERVATION_VERSION = read_config("preservation_version") or 0

local alert      = require "alert"
local annotation = require "annotation"
local anomaly    = require "anomaly"
require "circular_buffer"
require "string"

local title          = "Stats"
local rows           = read_config("rows") or 1440
local sec_per_row    = read_config("sec_per_row") or 60
local anomaly_config = anomaly.parse_config(read_config("anomaly_config"))
annotation.set_prune(title, rows * sec_per_row * 1e9)

local fields = {"HeapSys", "HeapAlloc","HeapIdle","HeapInuse","HeapReleased","HeapObjects"}
stats = circular_buffer.new(rows, #fields, sec_per_row)

local field_keys = {}
for i,v in ipairs(fields) do
    if v == "HeapObjects" then
        stats:set_header(i, v, "count", "max")
    else
        stats:set_header(i, v, "B", "max")
    end
    field_keys[i] = string.format("Fields[%s]", v)
end
fields = nil

function process_message ()
    local ts = read_message("Timestamp")
    for i,v in ipairs(field_keys) do
        local n = read_message(v)
        if type(n) == "number" then
            stats:set(ts, i, n)
        end
    end
    return 0
end

function timer_event(ns)
    if anomaly_config then
        if not alert.throttled(ns) then
            local msg, annos = anomaly.detect(ns, title, stats, anomaly_config)
            if msg then
                annotation.concat(title, annos)
                alert.send(ns, msg)
            end
        end
        inject_payload("cbuf", title, annotation.prune(title, ns), stats)
    else
        inject_payload("cbuf", title, stats)
    end
end
