Graph the max value rather than avg if rrdsingle disabled
[project/luci.git] / applications / luci-app-statistics / luasrc / statistics / rrdtool.lua
1 -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 module("luci.statistics.rrdtool", package.seeall)
5
6 require("luci.statistics.datatree")
7 require("luci.statistics.rrdtool.colors")
8 require("luci.statistics.i18n")
9 require("luci.model.uci")
10 require("luci.util")
11 require("luci.sys")
12
13 local fs = require "nixio.fs"
14
15
16 Graph = luci.util.class()
17
18 function Graph.__init__( self, timespan, opts )
19
20 opts = opts or { }
21
22 local uci = luci.model.uci.cursor()
23 local sections = uci:get_all( "luci_statistics" )
24
25 -- options
26 opts.timespan = timespan or sections.rrdtool.default_timespan or 900
27 opts.rrasingle = opts.rrasingle or ( sections.collectd_rrdtool.RRASingle == "1" )
28 opts.host = opts.host or sections.collectd.Hostname or luci.sys.hostname()
29 opts.width = opts.width or sections.rrdtool.image_width or 400
30 opts.rrdpath = opts.rrdpath or sections.collectd_rrdtool.DataDir or "/tmp/rrd"
31 opts.imgpath = opts.imgpath or sections.rrdtool.image_path or "/tmp/rrdimg"
32 opts.rrdpath = opts.rrdpath:gsub("/$","")
33 opts.imgpath = opts.imgpath:gsub("/$","")
34
35 -- helper classes
36 self.colors = luci.statistics.rrdtool.colors.Instance()
37 self.tree = luci.statistics.datatree.Instance(opts.host)
38 self.i18n = luci.statistics.i18n.Instance( self )
39
40 -- rrdtool default args
41 self.args = {
42 "-a", "PNG",
43 "-s", "NOW-" .. opts.timespan,
44 "-w", opts.width
45 }
46
47 -- store options
48 self.opts = opts
49 end
50
51 function Graph._mkpath( self, plugin, plugin_instance, dtype, dtype_instance )
52 local t = self.opts.host .. "/" .. plugin
53 if type(plugin_instance) == "string" and plugin_instance:len() > 0 then
54 t = t .. "-" .. plugin_instance
55 end
56 t = t .. "/" .. dtype
57 if type(dtype_instance) == "string" and dtype_instance:len() > 0 then
58 t = t .. "-" .. dtype_instance
59 end
60 return t
61 end
62
63 function Graph.mkrrdpath( self, ... )
64 return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) )
65 end
66
67 function Graph.mkpngpath( self, ... )
68 return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan )
69 end
70
71 function Graph.strippngpath( self, path )
72 return path:sub( self.opts.imgpath:len() + 2 )
73 end
74
75 function Graph._forcelol( self, list )
76 if type(list[1]) ~= "table" then
77 return( { list } )
78 end
79 return( list )
80 end
81
82 function Graph._rrdtool( self, def, rrd )
83
84 -- prepare directory
85 local dir = def[1]:gsub("/[^/]+$","")
86 fs.mkdirr( dir )
87
88 -- construct commandline
89 local cmdline = "rrdtool graph"
90
91 -- copy default arguments to def stack
92 for i, opt in ipairs(self.args) do
93 table.insert( def, 1 + i, opt )
94 end
95
96 -- construct commandline from def stack
97 for i, opt in ipairs(def) do
98 opt = opt .. "" -- force string
99
100 if rrd then
101 opt = opt:gsub( "{file}", rrd )
102 end
103
104 if opt:match("[^%w]") then
105 cmdline = cmdline .. " '" .. opt .. "'"
106 else
107 cmdline = cmdline .. " " .. opt
108 end
109 end
110
111 -- execute rrdtool
112 local rrdtool = io.popen( cmdline )
113 rrdtool:close()
114 end
115
116 function Graph._generic( self, opts, plugin, plugin_instance, dtype, index )
117
118 -- generated graph defs
119 local defs = { }
120
121 -- internal state variables
122 local _args = { }
123 local _sources = { }
124 local _stack_neg = { }
125 local _stack_pos = { }
126 local _longest_name = 0
127 local _has_totals = false
128
129 -- some convenient aliases
130 local _ti = table.insert
131 local _sf = string.format
132
133 -- local helper: append a string.format() formatted string to given table
134 function _tif( list, fmt, ... )
135 table.insert( list, string.format( fmt, ... ) )
136 end
137
138 -- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg
139 function __def(source)
140
141 local inst = source.sname
142 local rrd = source.rrd
143 local ds = source.ds
144
145 if not ds or ds:len() == 0 then ds = "value" end
146
147 _tif( _args, "DEF:%s_avg_raw=%s:%s:AVERAGE", inst, rrd, ds )
148 _tif( _args, "CDEF:%s_avg=%s_avg_raw,%s", inst, inst, source.transform_rpn )
149
150 if not self.opts.rrasingle then
151 _tif( _args, "DEF:%s_min_raw=%s:%s:MIN", inst, rrd, ds )
152 _tif( _args, "CDEF:%s_min=%s_min_raw,%s", inst, inst, source.transform_rpn )
153 _tif( _args, "DEF:%s_max_raw=%s:%s:MAX", inst, rrd, ds )
154 _tif( _args, "CDEF:%s_max=%s_max_raw,%s", inst, inst, source.transform_rpn )
155 end
156
157 _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
158 end
159
160 -- local helper: create cdefs depending on source options like flip and overlay
161 function __cdef(source)
162
163 local prev
164
165 -- find previous source, choose stack depending on flip state
166 if source.flip then
167 prev = _stack_neg[#_stack_neg]
168 else
169 prev = _stack_pos[#_stack_pos]
170 end
171
172 -- is first source in stack or overlay source: source_stk = source_nnl
173 if not prev or source.overlay then
174 if self.opts.rrasingle then
175 -- create cdef statement for cumulative stack (no NaNs) and also
176 -- for display (preserving NaN where no points should be displayed)
177 _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
178 _tif( _args, "CDEF:%s_plot=%s_avg", source.sname, source.sname )
179 else
180 -- create cdef statement for cumulative stack (no NaNs) and also
181 -- for display (preserving NaN where no points should be displayed)
182 _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
183 _tif( _args, "CDEF:%s_plot=%s_max", source.sname, source.sname )
184 end
185
186 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
187 else
188 if self.opts.rrasingle then
189 -- create cdef statement
190 _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
191 _tif( _args, "CDEF:%s_plot=%s_avg,%s_stk,+", source.sname, source.sname, prev )
192 else
193 -- create cdef statement
194 _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
195 _tif( _args, "CDEF:%s_plot=%s_max,%s_stk,+", source.sname, source.sname, prev )
196 end
197 end
198
199 -- create multiply by minus one cdef if flip is enabled
200 if source.flip then
201
202 -- create cdef statement: source_stk = source_stk * -1
203 _tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname )
204
205 -- push to negative stack if overlay is disabled
206 if not source.overlay then
207 _ti( _stack_neg, source.sname )
208 end
209
210 -- no flipping, push to positive stack if overlay is disabled
211 elseif not source.overlay then
212
213 -- push to positive stack
214 _ti( _stack_pos, source.sname )
215 end
216
217 -- calculate total amount of data if requested
218 if source.total then
219 _tif( _args,
220 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
221 source.sname, source.sname, source.sname
222 )
223
224 _tif( _args,
225 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
226 source.sname, source.sname, source.sname
227 )
228 end
229 end
230
231 -- local helper: create cdefs required for calculating total values
232 function __cdef_totals()
233 if _has_totals then
234 _tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname )
235 _ti( _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-" )
236 _ti( _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" )
237 end
238 end
239
240 -- local helper: create line and area statements
241 function __line(source)
242
243 local line_color
244 local area_color
245 local legend
246 local var
247
248 -- find colors: try source, then opts.colors; fall back to random color
249 if type(source.color) == "string" then
250 line_color = source.color
251 area_color = self.colors:from_string( line_color )
252 elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then
253 line_color = opts.colors[source.name:gsub("[^%w]","_")]
254 area_color = self.colors:from_string( line_color )
255 else
256 area_color = self.colors:random()
257 line_color = self.colors:to_string( area_color )
258 end
259
260 -- derive area background color from line color
261 area_color = self.colors:to_string( self.colors:faded( area_color ) )
262
263 -- choose source_plot or source_neg variable depending on flip state
264 if source.flip then
265 var = "neg"
266 else
267 var = "plot"
268 end
269
270 -- create legend
271 legend = _sf( "%-" .. _longest_name .. "s", source.title )
272
273 -- create area if not disabled
274 if not source.noarea then
275 _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
276 end
277
278 -- create line1 statement
279 _tif( _args, "LINE%d:%s_%s#%s:%s",
280 source.noarea and 2 or 1,
281 source.sname, var, line_color, legend )
282 end
283
284 -- local helper: create gprint statements
285 function __gprint(source)
286
287 local numfmt = opts.number_format or "%6.1lf"
288 local totfmt = opts.totals_format or "%5.1lf%s"
289
290 -- don't include MIN if rrasingle is enabled
291 if not self.opts.rrasingle then
292 _tif( _args, "GPRINT:%s_min:MIN:\tMin\\: %s", source.sname, numfmt )
293 end
294
295 -- always include AVERAGE
296 _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
297
298 -- don't include MAX if rrasingle is enabled
299 if not self.opts.rrasingle then
300 _tif( _args, "GPRINT:%s_max:MAX:\tMax\\: %s", source.sname, numfmt )
301 end
302
303 -- include total count if requested else include LAST
304 if source.total then
305 _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
306 else
307 _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
308 end
309 end
310
311
312 --
313 -- find all data sources
314 --
315
316 -- find data types
317 local data_types
318
319 if dtype then
320 data_types = { dtype }
321 else
322 data_types = opts.data.types or { }
323 end
324
325 if not ( dtype or opts.data.types ) then
326 if opts.data.instances then
327 for k, v in pairs(opts.data.instances) do
328 _ti( data_types, k )
329 end
330 elseif opts.data.sources then
331 for k, v in pairs(opts.data.sources) do
332 _ti( data_types, k )
333 end
334 end
335 end
336
337
338 -- iterate over data types
339 for i, dtype in ipairs(data_types) do
340
341 -- find instances
342
343 local data_instances
344
345 if not opts.per_instance then
346 if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then
347 data_instances = opts.data.instances[dtype]
348 else
349 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
350 end
351 end
352
353 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
354
355
356 -- iterate over data instances
357 for i, dinst in ipairs(data_instances) do
358
359 -- construct combined data type / instance name
360 local dname = dtype
361
362 if dinst:len() > 0 then
363 dname = dname .. "_" .. dinst
364 end
365
366
367 -- find sources
368 local data_sources = { "value" }
369
370 if type(opts.data.sources) == "table" then
371 if type(opts.data.sources[dname]) == "table" then
372 data_sources = opts.data.sources[dname]
373 elseif type(opts.data.sources[dtype]) == "table" then
374 data_sources = opts.data.sources[dtype]
375 end
376 end
377
378
379 -- iterate over data sources
380 for i, dsource in ipairs(data_sources) do
381
382 local dsname = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
383 local altname = dtype .. "__" .. dsource
384
385 --assert(dtype ~= "ping", dsname .. " or " .. altname)
386
387 -- find datasource options
388 local dopts = { }
389
390 if type(opts.data.options) == "table" then
391 if type(opts.data.options[dsname]) == "table" then
392 dopts = opts.data.options[dsname]
393 elseif type(opts.data.options[altname]) == "table" then
394 dopts = opts.data.options[altname]
395 elseif type(opts.data.options[dname]) == "table" then
396 dopts = opts.data.options[dname]
397 elseif type(opts.data.options[dtype]) == "table" then
398 dopts = opts.data.options[dtype]
399 end
400 end
401
402
403 -- store values
404 _ti( _sources, {
405 rrd = dopts.rrd or self:mkrrdpath( plugin, plugin_instance, dtype, dinst ),
406 color = dopts.color or self.colors:to_string( self.colors:random() ),
407 flip = dopts.flip or false,
408 total = dopts.total or false,
409 overlay = dopts.overlay or false,
410 transform_rpn = dopts.transform_rpn or "0,+",
411 noarea = dopts.noarea or false,
412 title = dopts.title or nil,
413 weight = dopts.weight or nil,
414 ds = dsource,
415 type = dtype,
416 instance = dinst,
417 index = #_sources + 1,
418 sname = ( #_sources + 1 ) .. dtype
419 } )
420
421
422 -- generate datasource title
423 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
424
425
426 -- find longest name ...
427 if _sources[#_sources].title:len() > _longest_name then
428 _longest_name = _sources[#_sources].title:len()
429 end
430
431
432 -- has totals?
433 if _sources[#_sources].total then
434 _has_totals = true
435 end
436 end
437 end
438 end
439
440
441 --
442 -- construct diagrams
443 --
444
445 -- if per_instance is enabled then find all instances from the first datasource in diagram
446 -- if per_instance is disabled then use an empty pseudo instance and use model provided values
447 local instances = { "" }
448
449 if opts.per_instance then
450 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
451 end
452
453
454 -- iterate over instances
455 for i, instance in ipairs(instances) do
456
457 -- store title and vlabel
458 _ti( _args, "-t" )
459 _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
460 _ti( _args, "-v" )
461 _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
462 if opts.y_max then
463 _ti ( _args, "-u" )
464 _ti ( _args, opts.y_max )
465 end
466 if opts.y_min then
467 _ti ( _args, "-l" )
468 _ti ( _args, opts.y_min )
469 end
470 if opts.units_exponent then
471 _ti ( _args, "-X" )
472 _ti ( _args, opts.units_exponent )
473 end
474 if opts.alt_autoscale then
475 _ti ( _args, "-A" )
476 end
477 if opts.alt_autoscale_max then
478 _ti ( _args, "-M" )
479 end
480
481 -- store additional rrd options
482 if opts.rrdopts then
483 for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
484 end
485
486 -- sort sources
487 table.sort(_sources, function(a, b)
488 local x = a.weight or a.index or 0
489 local y = b.weight or b.index or 0
490 return x < y
491 end)
492
493 -- create DEF statements for each instance
494 for i, source in ipairs(_sources) do
495 -- fixup properties for per instance mode...
496 if opts.per_instance then
497 source.instance = instance
498 source.rrd = self:mkrrdpath( plugin, plugin_instance, source.type, instance )
499 end
500
501 __def( source )
502 end
503
504 -- create CDEF required for calculating totals
505 __cdef_totals()
506
507 -- create CDEF statements for each instance in reversed order
508 for i, source in ipairs(_sources) do
509 __cdef( _sources[1 + #_sources - i] )
510 end
511
512 -- create LINE1, AREA and GPRINT statements for each instance
513 for i, source in ipairs(_sources) do
514 __line( source )
515 __gprint( source )
516 end
517
518 -- prepend image path to arg stack
519 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
520
521 -- push arg stack to definition list
522 _ti( defs, _args )
523
524 -- reset stacks
525 _args = { }
526 _stack_pos = { }
527 _stack_neg = { }
528 end
529
530 return defs
531 end
532
533 function Graph.render( self, plugin, plugin_instance, is_index )
534
535 dtype_instances = dtype_instances or { "" }
536 local pngs = { }
537
538 -- check for a whole graph handler
539 local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
540 local stat, def = pcall( require, plugin_def )
541
542 if stat and def and type(def.rrdargs) == "function" then
543
544 -- temporary image matrix
545 local _images = { }
546
547 -- get diagram definitions
548 for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, nil, is_index ) ) ) do
549 if not is_index or not opts.detail then
550 _images[i] = { }
551
552 -- get diagram definition instances
553 local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
554
555 -- render all diagrams
556 for j, def in ipairs( diagrams ) do
557 -- remember image
558 _images[i][j] = def[1]
559
560 -- exec
561 self:_rrdtool( def )
562 end
563 end
564 end
565
566 -- remember images - XXX: fixme (will cause probs with asymmetric data)
567 for y = 1, #_images[1] do
568 for x = 1, #_images do
569 table.insert( pngs, _images[x][y] )
570 end
571 end
572 end
573
574 return pngs
575 end