Skip to content

Instantly share code, notes, and snippets.

@postwait
Created January 22, 2021 23:05
Show Gist options
  • Save postwait/7255f18b7b67e1be0556dcd65235d359 to your computer and use it in GitHub Desktop.
Save postwait/7255f18b7b67e1be0556dcd65235d359 to your computer and use it in GitHub Desktop.
#!/opt/circonus/bin/luamtev -L+/opt/circonus/share/lua/5.1/?.lua;/opt/circonus/share/lua/5.1/?/init.lua
module(..., package.seeall)
function calc_next(last, period)
if not last then last = mtev.timeval.now() end
local ne = last:seconds() + period
return mtev.timeval.new(math.floor(ne), math.floor((ne - math.floor(ne)) * 1000000))
end
function subs(a)
if a == "{time}" then return math.floor(mtev.timeval.now():seconds()) end
r = string.match(a, "{rand%((%d+)%)}")
if r then
return math.random(tonumber(r))
end
if a == "{rand}" then return math.random(100) end
return a
end
function main()
if arg[5] == nil then
mtev.log("error", "%s <host> <port> <Hz> <template>\n\n", arg[1])
mtev.log("error", " template can include {time} and {rand} or {rand(X)}\n\n")
mtev.log("error", "Example:\t%s 127.0.0.1 8125 2 \"agenttest.node.timetest.timing:{rand(400)}|ms|@0.05\"\n", arg[1])
os.exit(-2)
end
local host = arg[2]
local port = tonumber(arg[3])
local period = 1 / tonumber(arg[4])
local line = arg[5]
mtev.log("stdout", "Sending every %f seconds to %s:%d\n", period, host, port)
local e = mtev.socket('inet', 'udp')
local last_attempt, next_attempt
while true do
last_attempt = next_attempt
next_attempt = calc_next(last_attempt, period)
local out = string.gsub(line, "(%b{})", subs)
print(out)
e:sendto(out, host, port)
local sleep_time = (next_attempt - mtev.timeval.now()):seconds()
if sleep_time < 0 then
mtev.log("stdout", "can't send fast enough, falling behind %f seconds\n", sleep_time)
else
mtev.sleep(sleep_time)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment