1 -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
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 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 )
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 )
186 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
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 )
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 )
199 -- create multiply by minus one cdef if flip is enabled
202 -- create cdef statement: source_stk = source_stk * -1
203 _tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname )
205 -- push to negative stack if overlay is disabled
206 if not source.overlay then
207 _ti( _stack_neg, source.sname )
210 -- no flipping, push to positive stack if overlay is disabled
211 elseif not source.overlay then
213 -- push to positive stack
214 _ti( _stack_pos, source.sname )
217 -- calculate total amount of data if requested
220 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
221 source.sname, source.sname, source.sname
225 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
226 source.sname, source.sname, source.sname
231 -- local helper: create cdefs required for calculating total values
232 function __cdef_totals()
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" )
240 -- local helper: create line and area statements
241 function __line(source)
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 )
256 area_color = self.colors:random()
257 line_color = self.colors:to_string( area_color )
260 -- derive area background color from line color
261 area_color = self.colors:to_string( self.colors:faded( area_color ) )
263 -- choose source_plot or source_neg variable depending on flip state
271 legend = _sf( "%-" .. _longest_name .. "s", source.title )
273 -- create area if not disabled
274 if not source.noarea then
275 _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
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 )
284 -- local helper: create gprint statements
285 function __gprint(source)
287 local numfmt = opts.number_format or "%6.1lf"
288 local totfmt = opts.totals_format or "%5.1lf%s"
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 )
295 -- always include AVERAGE
296 _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
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 )
303 -- include total count if requested else include LAST
305 _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
307 _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
313 -- find all data sources
320 data_types = { dtype }
322 data_types = opts.data.types or { }
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
330 elseif opts.data.sources then
331 for k, v in pairs(opts.data.sources) do
338 -- iterate over data types
339 for i, dtype in ipairs(data_types) do
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]
349 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
353 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
356 -- iterate over data instances
357 for i, dinst in ipairs(data_instances) do
359 -- construct combined data type / instance name
362 if dinst:len() > 0 then
363 dname = dname .. "_" .. dinst
368 local data_sources = { "value" }
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]
379 -- iterate over data sources
380 for i, dsource in ipairs(data_sources) do
382 local dsname = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
383 local altname = dtype .. "__" .. dsource
385 --assert(dtype ~= "ping", dsname .. " or " .. altname)
387 -- find datasource options
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]
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,
417 index = #_sources + 1,
418 sname = ( #_sources + 1 ) .. dtype
422 -- generate datasource title
423 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
426 -- find longest name ...
427 if _sources[#_sources].title:len() > _longest_name then
428 _longest_name = _sources[#_sources].title:len()
433 if _sources[#_sources].total then
442 -- construct diagrams
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 = { "" }
449 if opts.per_instance then
450 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
454 -- iterate over instances
455 for i, instance in ipairs(instances) do
457 -- store title and vlabel
459 _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
461 _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
464 _ti ( _args, opts.y_max )
468 _ti ( _args, opts.y_min )
470 if opts.units_exponent then
472 _ti ( _args, opts.units_exponent )
474 if opts.alt_autoscale then
477 if opts.alt_autoscale_max then
481 -- store additional rrd options
483 for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
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
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 )
504 -- create CDEF required for calculating totals
507 -- create CDEF statements for each instance in reversed order
508 for i, source in ipairs(_sources) do
509 __cdef( _sources[1 + #_sources - i] )
512 -- create LINE1, AREA and GPRINT statements for each instance
513 for i, source in ipairs(_sources) do
518 -- prepend image path to arg stack
519 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
521 -- push arg stack to definition list
533 function Graph.render( self, plugin, plugin_instance, is_index )
535 dtype_instances = dtype_instances or { "" }
538 -- check for a whole graph handler
539 local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
540 local stat, def = pcall( require, plugin_def )
542 if stat and def and type(def.rrdargs) == "function" then
544 -- temporary image matrix
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
552 -- get diagram definition instances
553 local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
555 -- render all diagrams
556 for j, def in ipairs( diagrams ) do
558 _images[i][j] = def[1]
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] )