-
Notifications
You must be signed in to change notification settings - Fork 30
/
api.lua
executable file
·363 lines (338 loc) · 10.6 KB
/
api.lua
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
---
-- SQL specific API view
--
-- Copyright Tor Hveem <thveem> 2013-2014
--
--
local setmetatable = setmetatable
local ngx = ngx
local string = string
local cjson = require "cjson"
local io = require "io"
local pg = require "resty.postgres" -- https://github.com/azurewang/lua-resty-postgres
local assert = assert
local conf
module(...)
local mt = { __index = _M }
if not conf then
local f = assert(io.open(ngx.var.document_root .. "/etc/config.json", "r"))
local c = f:read("*all")
f:close()
conf = cjson.decode(c)
end
local function dbreq(sql)
local db = pg:new()
db:set_timeout(30000)
local ok, err = db:connect(
{
host=conf.db.host,
port=5432,
database=conf.db.database,
user=conf.db.user,
password=conf.db.password,
compact=false
})
if not ok then
ngx.say(err)
end
--ngx.log(ngx.ERR, '___ SQL ___'..sql)
local res, err = db:query(sql)
if not res then
ngx.log(ngx.ERR, 'Failed SQL query:' ..sql)
res = {error=err}
end
db:set_keepalive(0,10)
return cjson.encode(res)
end
-- The function sending subreq to nginx postgresql location with rds_json on
-- returns json body to the caller
local function odbreq(sql)
--ngx.log(ngx.ERR, 'SQL: ' .. sql)
local dbreq = ngx.location.capture("/pg", { args = { sql = sql } })
local json = dbreq.body
return json
end
-- Translate front end column names to back end column names
local function column(key)
return conf.db.columns[key]
end
function max(match)
local key = ngx.req.get_uri_args()['key']
if not key then ngx.exit(403) end
-- Make sure valid request, only accept plain lowercase ascii string for key name
local keytest = ngx.re.match(key, '[a-z]+', 'oj')
if not keytest then ngx.exit(403) end
local sql = [[
SELECT
date_trunc('day', datetime) AS datetime,
MAX(]]..key..[[) AS ]]..key..[[
FROM ]]..conf.db.table..[[
WHERE date_part('year', datetime) < 2013
GROUP BY 1
]]
return dbreq(sql)
end
-- Latest record in db
function now(match)
return dbreq([[SELECT
*,
(
SELECT SUM(rain)
FROM ]]..conf.db.table..[[
WHERE datetime >= CURRENT_DATE
)
AS dayrain
FROM ]]..conf.db.table..[[
ORDER BY datetime DESC LIMIT 1]])
end
-- Last 60 samples from db
function recent(match)
return dbreq([[SELECT
*,
SUM(rain) OVER (PARTITION by datetime ORDER by datetime DESC) AS dayrain
FROM ]]..conf.db.table..[[
ORDER BY datetime DESC
LIMIT 60]])
end
-- Helper function to get a start argument and return SQL constrains
local function getDateConstrains(startarg, interval)
local where = ''
local andwhere = ''
if startarg then
local start
local endpart = "1 year"
if string.upper(startarg) == 'TODAY' then
start = "CURRENT_DATE"
endpart = "1 DAY"
elseif string.lower(startarg) == 'yesterday' then
start = "DATE 'yesterday'"
endpart = '1 days'
elseif string.upper(startarg) == '3DAY' then
start = "CURRENT_TIMESTAMP - INTERVAL '3 days'"
endpart = '3 days'
elseif string.upper(startarg) == 'WEEK' then
start = "CURRENT_DATE - INTERVAL '1 week'"
endpart = '1 week'
elseif string.upper(startarg) == '7DAYS' then
start = "CURRENT_DATE - INTERVAL '1 WEEK'"
endpart = '1 WEEK'
elseif string.upper(startarg) == 'MONTH' then
-- old used this month, new version uses last 30 days
--start = "to_date( to_char(current_date,'yyyy-MM') || '-01','yyyy-mm-dd')"
start = "CURRENT_DATE - INTERVAL '1 MONTH'"
endpart = "1 MONTH"
elseif string.upper(startarg) == 'YEAR' then
start = "date_trunc('year', current_timestamp)"
endpart = "1 year"
elseif string.upper(startarg) == 'ALL' then
start = "DATE '1900-01-01'" -- Should be old enough :-)
endpart = "200 years"
else
start = "DATE '" .. startarg .. "'"
end
-- use interval if provided, if not use the default endpart
if not interval then
interval = endpart
end
local wherepart = [[
(
datetime BETWEEN ]]..start..[[
AND
]]..start..[[ + INTERVAL ']]..endpart..[['
)
]]
where = 'WHERE ' .. wherepart
andwhere = 'AND ' .. wherepart
end
return where, andwhere
end
-- Function to return extremeties from database, min/maxes for different time intervals
function record(match)
local key = match[1]
local func = string.upper(match[2])
local where, andwhere = getDateConstrains(ngx.req.get_uri_args()['start'])
local sql
-- Special handling for rain since it needs a sum
if key == 'dayrain' and func == 'MAX' then
-- Not valid with any other value than max
sql = [[
SELECT
DISTINCT date_trunc('day', datetime) AS datetime,
SUM(rain) OVER (PARTITION BY date_trunc('day', datetime)) AS dayrain
FROM ]]..conf.db.table..[[
]]..where..[[
ORDER BY dayrain DESC
LIMIT 1
]]
elseif func == 'SUM' then
-- The SUM part doesn't need the datetime of the record since the datetime is effectively over the whole scope
sql = [[
SELECT
SUM(]]..key..[[) AS ]]..key..[[
FROM ]]..conf.db.table..[[
]]..where..[[
]]
else
sql = [[
SELECT
datetime,
date_trunc('second', age(NOW(), date_trunc('second', datetime))) AS age,
]]..key..[[
FROM ]]..conf.db.table..[[
WHERE
]]..key..[[ =
(
SELECT
]]..func..[[(]]..key..[[)
FROM ]]..conf.db.table..[[
]]..where..[[
LIMIT 1
)
]]..andwhere..[[
LIMIT 1
]]
end
return dbreq(sql)
end
--- Return weather data by hour, week, month, year, whatever..
function by_dateunit(match)
local unit = 'hour'
if match[1] then
if match[1] == 'month' then
unit = 'day'
end
elseif ngx.req.get_uri_args()['start'] == 'month' then
unit = 'day'
end
-- get the date constraints
local where, andwhere = getDateConstrains(ngx.req.get_uri_args()['start'])
local sql = dbreq([[
SELECT
date_trunc(']]..unit..[[', datetime) AS datetime,
AVG(outtemp) as outtemp,
MIN(outtemp) as tempmin,
MAX(outtemp) as tempmax,
AVG(dewpoint) as dewpoint,
AVG(rain) as rain,
MAX(b.dayrain) as dayrain,
AVG(windspeed) as windspeed,
MAX(windgust) as windgust,
AVG(winddir) as winddir,
AVG(barometer) as barometer,
AVG(outhumidity) as outhumidity,
AVG(intemp) as intemp,
AVG(inhumidity) as inhumidity,
AVG(heatindex) as heatindex,
AVG(windchill) as windchill
FROM ]]..conf.db.table..[[ as a
LEFT OUTER JOIN (
SELECT DISTINCT
date_trunc(']]..unit..[[', datetime) AS unit,
SUM(rain) OVER (PARTITION BY date_trunc('day', datetime) ORDER by datetime) AS dayrain
FROM ]]..conf.db.table..[[ ]]..where..[[
ORDER BY 1
) AS b
ON a.datetime = b.unit
]]..where..[[
GROUP BY 1
ORDER BY datetime
]])
return sql
end
function day(match)
local where, andwhere = getDateConstrains(ngx.req.get_uri_args()['start'])
local sql = dbreq([[
SELECT
*,
SUM(rain) OVER (ORDER by datetime) AS dayrain
FROM ]]..conf.db.table..[[
]]..where..[[
ORDER BY datetime
]])
return sql
end
function year(match)
-- This function generates stats into a new table
-- which is updated max once a day
-- first it checks the latest record in the stats table
-- and if latest date is older than today
-- it will recreate the table
local year = match[1]
local syear = year .. '-01-01'
local where = [[
WHERE datetime BETWEEN DATE ']]..syear..[['
AND DATE ']]..syear..[[' + INTERVAL '1 year'
]]
local needsupdate = cjson.decode(dbreq[[
SELECT
MAX(datetime) < (NOW() - INTERVAL '24 hours') AS needsupdate
FROM days
]])
if needsupdate == ngx.null or needsupdate[1] == nil or needsupdate.error ~= nil then
needsupdate = true
else
if needsupdate[1]['needsupdate'] == 't' then
needsupdate = true
else
needsupdate = false
end
end
if needsupdate then
-- Remove existing cache. This could be improved to only add missing data
dbreq('DROP TABLE days')
-- Create new cached table
local gendays = dbreq([[
CREATE TABLE days AS
SELECT
date_trunc('day', datetime) AS datetime,
AVG(outtemp) as outtemp,
MIN(outtemp) as tempmin,
MAX(outtemp) as tempmax,
AVG(dewpoint) as dewpoint,
AVG(rain) as rain,
MAX(b.dayrain) as dayrain,
AVG(windspeed) as windspeed,
MAX(windgust) as windgust,
AVG(winddir) as winddir,
AVG(barometer) as barometer,
AVG(outhumidity) as outhumidity,
AVG(intemp) as intemp,
AVG(inhumidity) as inhumidity,
AVG(heatindex) as heatindex,
AVG(windchill) as windchill
FROM ]]..conf.db.table..[[ AS a
LEFT OUTER JOIN
(
SELECT
DISTINCT date_trunc('day', datetime) AS hour,
SUM(rain) OVER (PARTITION BY date_trunc('day', datetime) ORDER by datetime) AS dayrain
FROM ]]..conf.db.table..[[ ORDER BY 1
) AS b
ON a.datetime = b.hour
GROUP BY 1
ORDER BY datetime
]])
end
local sql = [[
SELECT *
FROM days
]]..where
return dbreq(sql)
end
function windhist(match)
local where, andwhere = getDateConstrains(ngx.req.get_uri_args()['start'])
return dbreq([[
SELECT count(*), ((winddir/10)::int*10)+0 as d, avg(windspeed)*1.94384449 as avg
FROM ]]..conf.db.table..[[
]]..where..[[
GROUP BY 2
ORDER BY 2
]])
end
local class_mt = {
-- to prevent use of casual module global variables
__newindex = function (table, key, val)
ngx.log(ngx.ERR, 'attempt to write to undeclared variable "' .. key .. '"')
end
}
setmetatable(_M, class_mt)