1 -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
2 -- Licensed to the public under the Apache License 2.0.
4 module("luci.statistics.rrdtool", package.seeall)
6 require("luci.statistics.datatree")
7 require("luci.statistics.rrdtool.colors")
8 require("luci.statistics.i18n")
9 require("luci.model.uci")
13 local fs = require "nixio.fs"
16 Graph = luci.util.class()
18 function Graph.__init__( self, timespan, opts )
22 local uci = luci.model.uci.cursor()
23 local sections = uci:get_all( "luci_statistics" )
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("/$","")
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 )
40 -- rrdtool default args
43 "-s", "NOW-" .. opts.timespan,
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
57 if type(dtype_instance) == "string" and dtype_instance:len() > 0 then
58 t = t .. "-" .. dtype_instance
63 function Graph.mkrrdpath( self, ... )
64 return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) )
67 function Graph.mkpngpath( self, ... )
68 return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan )
71 function Graph.strippngpath( self, path )
72 return path:sub( self.opts.imgpath:len() + 2 )
75 function Graph._forcelol( self, list )
76 if type(list[1]) ~= "table" then
82 function Graph._rrdtool( self, def, rrd )
85 local dir = def[1]:gsub("/[^/]+$","")
88 -- construct commandline
89 local cmdline = "rrdtool graph"
91 -- copy default arguments to def stack
92 for i, opt in ipairs(self.args) do
93 table.insert( def, 1 + i, opt )
96 -- construct commandline from def stack
97 for i, opt in ipairs(def) do
98 opt = opt .. "" -- force string
101 opt = opt:gsub( "{file}", rrd )
104 if opt:match("[^%w]") then
105 cmdline = cmdline .. " '" .. opt .. "'"
107 cmdline = cmdline .. " " .. opt
112 local rrdtool = io.popen( cmdline )
116 function Graph._generic( self, opts, plugin, plugin_instance, dtype, index )
118 -- generated graph defs
121 -- internal state variables
124 local _stack_neg = { }
125 local _stack_pos = { }
126 local _longest_name = 0
127 local _has_totals = false
129 -- some convenient aliases
130 local _ti = table.insert
131 local _sf = string.format
133 -- local helper: append a string.format() formatted string to given table
134 function _tif( list, fmt, ... )
135 table.insert( list, string.format( fmt, ... ) )
138 -- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg
139 function __def(source)
141 local inst = source.sname
142 local rrd = source.rrd
145 if not ds or ds:len() == 0 then ds = "value" end
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 )
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 )
157 _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
160 -- local helper: create cdefs depending on source options like flip and overlay
161 function __cdef(source)
165 -- find previous source, choose stack depending on flip state
167 prev = _stack_neg[#_stack_neg]
169 prev = _stack_pos[#_stack_pos]
172 -- is first source in stack or overlay source: source_stk = source_nnl
173 if not prev or source.overlay then
174 -- create cdef statement for cumulative stack (no NaNs) and also
175 -- for display (preserving NaN where no points should be displayed)
176 _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
177 _tif( _args, "CDEF:%s_plot=%s_avg", source.sname, source.sname )
179 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
181 -- create cdef statement
182 _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
183 _tif( _args, "CDEF:%s_plot=%s_avg,%s_stk,+", source.sname, source.sname, prev )
186 -- create multiply by minus one cdef if flip is enabled
189 -- create cdef statement: source_stk = source_stk * -1
190 _tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname )
192 -- push to negative stack if overlay is disabled
193 if not source.overlay then
194 _ti( _stack_neg, source.sname )
197 -- no flipping, push to positive stack if overlay is disabled
198 elseif not source.overlay then
200 -- push to positive stack
201 _ti( _stack_pos, source.sname )
204 -- calculate total amount of data if requested
207 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
208 source.sname, source.sname, source.sname
212 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
213 source.sname, source.sname, source.sname
218 -- local helper: create cdefs required for calculating total values
219 function __cdef_totals()
221 _tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname )
222 _ti( _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-" )
223 _ti( _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" )
227 -- local helper: create line and area statements
228 function __line(source)
235 -- find colors: try source, then opts.colors; fall back to random color
236 if type(source.color) == "string" then
237 line_color = source.color
238 area_color = self.colors:from_string( line_color )
239 elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then
240 line_color = opts.colors[source.name:gsub("[^%w]","_")]
241 area_color = self.colors:from_string( line_color )
243 area_color = self.colors:random()
244 line_color = self.colors:to_string( area_color )
247 -- derive area background color from line color
248 area_color = self.colors:to_string( self.colors:faded( area_color ) )
250 -- choose source_plot or source_neg variable depending on flip state
258 legend = _sf( "%-" .. _longest_name .. "s", source.title )
260 -- create area if not disabled
261 if not source.noarea then
262 _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
265 -- create line1 statement
266 _tif( _args, "LINE%d:%s_%s#%s:%s",
267 source.noarea and 2 or 1,
268 source.sname, var, line_color, legend )
271 -- local helper: create gprint statements
272 function __gprint(source)
274 local numfmt = opts.number_format or "%6.1lf"
275 local totfmt = opts.totals_format or "%5.1lf%s"
277 -- don't include MIN if rrasingle is enabled
278 if not self.opts.rrasingle then
279 _tif( _args, "GPRINT:%s_min:MIN:\tMin\\: %s", source.sname, numfmt )
282 -- always include AVERAGE
283 _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
285 -- don't include MAX if rrasingle is enabled
286 if not self.opts.rrasingle then
287 _tif( _args, "GPRINT:%s_max:MAX:\tMax\\: %s", source.sname, numfmt )
290 -- include total count if requested else include LAST
292 _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
294 _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
300 -- find all data sources
307 data_types = { dtype }
309 data_types = opts.data.types or { }
312 if not ( dtype or opts.data.types ) then
313 if opts.data.instances then
314 for k, v in pairs(opts.data.instances) do
317 elseif opts.data.sources then
318 for k, v in pairs(opts.data.sources) do
325 -- iterate over data types
326 for i, dtype in ipairs(data_types) do
332 if not opts.per_instance then
333 if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then
334 data_instances = opts.data.instances[dtype]
336 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
340 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
343 -- iterate over data instances
344 for i, dinst in ipairs(data_instances) do
346 -- construct combined data type / instance name
349 if dinst:len() > 0 then
350 dname = dname .. "_" .. dinst
355 local data_sources = { "value" }
357 if type(opts.data.sources) == "table" then
358 if type(opts.data.sources[dname]) == "table" then
359 data_sources = opts.data.sources[dname]
360 elseif type(opts.data.sources[dtype]) == "table" then
361 data_sources = opts.data.sources[dtype]
366 -- iterate over data sources
367 for i, dsource in ipairs(data_sources) do
369 local dsname = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
370 local altname = dtype .. "__" .. dsource
372 --assert(dtype ~= "ping", dsname .. " or " .. altname)
374 -- find datasource options
377 if type(opts.data.options) == "table" then
378 if type(opts.data.options[dsname]) == "table" then
379 dopts = opts.data.options[dsname]
380 elseif type(opts.data.options[altname]) == "table" then
381 dopts = opts.data.options[altname]
382 elseif type(opts.data.options[dname]) == "table" then
383 dopts = opts.data.options[dname]
384 elseif type(opts.data.options[dtype]) == "table" then
385 dopts = opts.data.options[dtype]
392 rrd = dopts.rrd or self:mkrrdpath( plugin, plugin_instance, dtype, dinst ),
393 color = dopts.color or self.colors:to_string( self.colors:random() ),
394 flip = dopts.flip or false,
395 total = dopts.total or false,
396 overlay = dopts.overlay or false,
397 transform_rpn = dopts.transform_rpn or "0,+",
398 noarea = dopts.noarea or false,
399 title = dopts.title or nil,
403 index = #_sources + 1,
404 sname = ( #_sources + 1 ) .. dtype
408 -- generate datasource title
409 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
412 -- find longest name ...
413 if _sources[#_sources].title:len() > _longest_name then
414 _longest_name = _sources[#_sources].title:len()
419 if _sources[#_sources].total then
428 -- construct diagrams
431 -- if per_instance is enabled then find all instances from the first datasource in diagram
432 -- if per_instance is disabled then use an empty pseudo instance and use model provided values
433 local instances = { "" }
435 if opts.per_instance then
436 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
440 -- iterate over instances
441 for i, instance in ipairs(instances) do
443 -- store title and vlabel
445 _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
447 _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
450 _ti ( _args, opts.y_max )
454 _ti ( _args, opts.y_min )
456 if opts.units_exponent then
458 _ti ( _args, opts.units_exponent )
461 -- store additional rrd options
463 for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
467 -- create DEF statements for each instance
468 for i, source in ipairs(_sources) do
469 -- fixup properties for per instance mode...
470 if opts.per_instance then
471 source.instance = instance
472 source.rrd = self:mkrrdpath( plugin, plugin_instance, source.type, instance )
478 -- create CDEF required for calculating totals
481 -- create CDEF statements for each instance in reversed order
482 for i, source in ipairs(_sources) do
483 __cdef( _sources[1 + #_sources - i] )
486 -- create LINE1, AREA and GPRINT statements for each instance
487 for i, source in ipairs(_sources) do
492 -- prepend image path to arg stack
493 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
495 -- push arg stack to definition list
507 function Graph.render( self, plugin, plugin_instance, is_index )
509 dtype_instances = dtype_instances or { "" }
512 -- check for a whole graph handler
513 local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
514 local stat, def = pcall( require, plugin_def )
516 if stat and def and type(def.rrdargs) == "function" then
518 -- temporary image matrix
521 -- get diagram definitions
522 for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, nil, is_index ) ) ) do
523 if not is_index or not opts.detail then
526 -- get diagram definition instances
527 local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
529 -- render all diagrams
530 for j, def in ipairs( diagrams ) do
532 _images[i][j] = def[1]
540 -- remember images - XXX: fixme (will cause probs with asymmetric data)
541 for y = 1, #_images[1] do
542 for x = 1, #_images do
543 table.insert( pngs, _images[x][y] )