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.rramax = opts.rramax or ( sections.collectd_rrdtool.RRAMax == "1" )
29 opts.host = opts.host or sections.collectd.Hostname or luci.sys.hostname()
30 opts.width = opts.width or sections.rrdtool.image_width or 400
31 opts.rrdpath = opts.rrdpath or sections.collectd_rrdtool.DataDir or "/tmp/rrd"
32 opts.imgpath = opts.imgpath or sections.rrdtool.image_path or "/tmp/rrdimg"
33 opts.rrdpath = opts.rrdpath:gsub("/$","")
34 opts.imgpath = opts.imgpath:gsub("/$","")
37 self.colors = luci.statistics.rrdtool.colors.Instance()
38 self.tree = luci.statistics.datatree.Instance(opts.host)
39 self.i18n = luci.statistics.i18n.Instance( self )
41 -- rrdtool default args
44 "-s", "NOW-" .. opts.timespan,
52 function Graph._mkpath( self, plugin, plugin_instance, dtype, dtype_instance )
53 local t = self.opts.host .. "/" .. plugin
54 if type(plugin_instance) == "string" and plugin_instance:len() > 0 then
55 t = t .. "-" .. plugin_instance
58 if type(dtype_instance) == "string" and dtype_instance:len() > 0 then
59 t = t .. "-" .. dtype_instance
64 function Graph.mkrrdpath( self, ... )
65 return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) )
68 function Graph.mkpngpath( self, ... )
69 return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan )
72 function Graph.strippngpath( self, path )
73 return path:sub( self.opts.imgpath:len() + 2 )
76 function Graph._forcelol( self, list )
77 if type(list[1]) ~= "table" then
83 function Graph._rrdtool( self, def, rrd )
86 local dir = def[1]:gsub("/[^/]+$","")
89 -- construct commandline
90 local cmdline = "rrdtool graph"
92 -- copy default arguments to def stack
93 for i, opt in ipairs(self.args) do
94 table.insert( def, 1 + i, opt )
97 -- construct commandline from def stack
98 for i, opt in ipairs(def) do
99 opt = opt .. "" -- force string
102 opt = opt:gsub( "{file}", rrd )
105 if opt:match("[^%w]") then
106 cmdline = cmdline .. " '" .. opt .. "'"
108 cmdline = cmdline .. " " .. opt
113 local rrdtool = io.popen( cmdline )
117 function Graph._generic( self, opts, plugin, plugin_instance, dtype, index )
119 -- generated graph defs
122 -- internal state variables
125 local _stack_neg = { }
126 local _stack_pos = { }
127 local _longest_name = 0
128 local _has_totals = false
130 -- some convenient aliases
131 local _ti = table.insert
132 local _sf = string.format
134 -- local helper: append a string.format() formatted string to given table
135 function _tif( list, fmt, ... )
136 table.insert( list, string.format( fmt, ... ) )
139 -- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg
140 function __def(source)
142 local inst = source.sname
143 local rrd = source.rrd
146 if not ds or ds:len() == 0 then ds = "value" end
148 _tif( _args, "DEF:%s_avg_raw=%s:%s:AVERAGE", inst, rrd, ds )
149 _tif( _args, "CDEF:%s_avg=%s_avg_raw,%s", inst, inst, source.transform_rpn )
151 if not self.opts.rrasingle then
152 _tif( _args, "DEF:%s_min_raw=%s:%s:MIN", inst, rrd, ds )
153 _tif( _args, "CDEF:%s_min=%s_min_raw,%s", inst, inst, source.transform_rpn )
154 _tif( _args, "DEF:%s_max_raw=%s:%s:MAX", inst, rrd, ds )
155 _tif( _args, "CDEF:%s_max=%s_max_raw,%s", inst, inst, source.transform_rpn )
158 _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
161 -- local helper: create cdefs depending on source options like flip and overlay
162 function __cdef(source)
166 -- find previous source, choose stack depending on flip state
168 prev = _stack_neg[#_stack_neg]
170 prev = _stack_pos[#_stack_pos]
173 -- is first source in stack or overlay source: source_stk = source_nnl
174 if not prev or source.overlay then
175 if self.opts.rrasingle or not self.opts.rramax then
176 -- create cdef statement for cumulative stack (no NaNs) and also
177 -- for display (preserving NaN where no points should be displayed)
178 _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
179 _tif( _args, "CDEF:%s_plot=%s_avg", source.sname, source.sname )
181 -- create cdef statement for cumulative stack (no NaNs) and also
182 -- for display (preserving NaN where no points should be displayed)
183 _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
184 _tif( _args, "CDEF:%s_plot=%s_max", source.sname, source.sname )
187 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
189 if self.opts.rrasingle or not self.opts.rramax then
190 -- create cdef statement
191 _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
192 _tif( _args, "CDEF:%s_plot=%s_avg,%s_stk,+", source.sname, source.sname, prev )
194 -- create cdef statement
195 _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
196 _tif( _args, "CDEF:%s_plot=%s_max,%s_stk,+", source.sname, source.sname, prev )
200 -- create multiply by minus one cdef if flip is enabled
203 -- create cdef statement: source_stk = source_stk * -1
204 _tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname )
206 -- push to negative stack if overlay is disabled
207 if not source.overlay then
208 _ti( _stack_neg, source.sname )
211 -- no flipping, push to positive stack if overlay is disabled
212 elseif not source.overlay then
214 -- push to positive stack
215 _ti( _stack_pos, source.sname )
218 -- calculate total amount of data if requested
221 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
222 source.sname, source.sname, source.sname
226 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
227 source.sname, source.sname, source.sname
232 -- local helper: create cdefs required for calculating total values
233 function __cdef_totals()
235 _tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname )
236 _ti( _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-" )
237 _ti( _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" )
241 -- local helper: create line and area statements
242 function __line(source)
249 -- find colors: try source, then opts.colors; fall back to random color
250 if type(source.color) == "string" then
251 line_color = source.color
252 area_color = self.colors:from_string( line_color )
253 elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then
254 line_color = opts.colors[source.name:gsub("[^%w]","_")]
255 area_color = self.colors:from_string( line_color )
257 area_color = self.colors:random()
258 line_color = self.colors:to_string( area_color )
261 -- derive area background color from line color
262 area_color = self.colors:to_string( self.colors:faded( area_color ) )
264 -- choose source_plot or source_neg variable depending on flip state
272 legend = _sf( "%-" .. _longest_name .. "s", source.title )
274 -- create area if not disabled
275 if not source.noarea then
276 _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
279 -- create line1 statement
280 _tif( _args, "LINE%d:%s_%s#%s:%s",
281 source.noarea and 2 or 1,
282 source.sname, var, line_color, legend )
285 -- local helper: create gprint statements
286 function __gprint(source)
288 local numfmt = opts.number_format or "%6.1lf"
289 local totfmt = opts.totals_format or "%5.1lf%s"
291 -- don't include MIN if rrasingle is enabled
292 if not self.opts.rrasingle then
293 _tif( _args, "GPRINT:%s_min:MIN:\tMin\\: %s", source.sname, numfmt )
296 -- always include AVERAGE
297 _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
299 -- don't include MAX if rrasingle is enabled
300 if not self.opts.rrasingle then
301 _tif( _args, "GPRINT:%s_max:MAX:\tMax\\: %s", source.sname, numfmt )
304 -- include total count if requested else include LAST
306 _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
308 _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
314 -- find all data sources
321 data_types = { dtype }
323 data_types = opts.data.types or { }
326 if not ( dtype or opts.data.types ) then
327 if opts.data.instances then
328 for k, v in pairs(opts.data.instances) do
331 elseif opts.data.sources then
332 for k, v in pairs(opts.data.sources) do
339 -- iterate over data types
340 for i, dtype in ipairs(data_types) do
346 if not opts.per_instance then
347 if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then
348 data_instances = opts.data.instances[dtype]
350 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
354 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
357 -- iterate over data instances
358 for i, dinst in ipairs(data_instances) do
360 -- construct combined data type / instance name
363 if dinst:len() > 0 then
364 dname = dname .. "_" .. dinst
369 local data_sources = { "value" }
371 if type(opts.data.sources) == "table" then
372 if type(opts.data.sources[dname]) == "table" then
373 data_sources = opts.data.sources[dname]
374 elseif type(opts.data.sources[dtype]) == "table" then
375 data_sources = opts.data.sources[dtype]
380 -- iterate over data sources
381 for i, dsource in ipairs(data_sources) do
383 local dsname = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
384 local altname = dtype .. "__" .. dsource
386 --assert(dtype ~= "ping", dsname .. " or " .. altname)
388 -- find datasource options
391 if type(opts.data.options) == "table" then
392 if type(opts.data.options[dsname]) == "table" then
393 dopts = opts.data.options[dsname]
394 elseif type(opts.data.options[altname]) == "table" then
395 dopts = opts.data.options[altname]
396 elseif type(opts.data.options[dname]) == "table" then
397 dopts = opts.data.options[dname]
398 elseif type(opts.data.options[dtype]) == "table" then
399 dopts = opts.data.options[dtype]
406 rrd = dopts.rrd or self:mkrrdpath( plugin, plugin_instance, dtype, dinst ),
407 color = dopts.color or self.colors:to_string( self.colors:random() ),
408 flip = dopts.flip or false,
409 total = dopts.total or false,
410 overlay = dopts.overlay or false,
411 transform_rpn = dopts.transform_rpn or "0,+",
412 noarea = dopts.noarea or false,
413 title = dopts.title or nil,
414 weight = dopts.weight or nil,
418 index = #_sources + 1,
419 sname = ( #_sources + 1 ) .. dtype
423 -- generate datasource title
424 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
427 -- find longest name ...
428 if _sources[#_sources].title:len() > _longest_name then
429 _longest_name = _sources[#_sources].title:len()
434 if _sources[#_sources].total then
443 -- construct diagrams
446 -- if per_instance is enabled then find all instances from the first datasource in diagram
447 -- if per_instance is disabled then use an empty pseudo instance and use model provided values
448 local instances = { "" }
450 if opts.per_instance then
451 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
455 -- iterate over instances
456 for i, instance in ipairs(instances) do
458 -- store title and vlabel
460 _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
462 _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
465 _ti ( _args, opts.y_max )
469 _ti ( _args, opts.y_min )
471 if opts.units_exponent then
473 _ti ( _args, opts.units_exponent )
475 if opts.alt_autoscale then
478 if opts.alt_autoscale_max then
482 -- store additional rrd options
484 for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
488 table.sort(_sources, function(a, b)
489 local x = a.weight or a.index or 0
490 local y = b.weight or b.index or 0
494 -- create DEF statements for each instance
495 for i, source in ipairs(_sources) do
496 -- fixup properties for per instance mode...
497 if opts.per_instance then
498 source.instance = instance
499 source.rrd = self:mkrrdpath( plugin, plugin_instance, source.type, instance )
505 -- create CDEF required for calculating totals
508 -- create CDEF statements for each instance in reversed order
509 for i, source in ipairs(_sources) do
510 __cdef( _sources[1 + #_sources - i] )
513 -- create LINE1, AREA and GPRINT statements for each instance
514 for i, source in ipairs(_sources) do
519 -- prepend image path to arg stack
520 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
522 -- push arg stack to definition list
534 function Graph.render( self, plugin, plugin_instance, is_index )
536 dtype_instances = dtype_instances or { "" }
539 -- check for a whole graph handler
540 local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
541 local stat, def = pcall( require, plugin_def )
543 if stat and def and type(def.rrdargs) == "function" then
545 -- temporary image matrix
548 -- get diagram definitions
549 for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, nil, is_index ) ) ) do
550 if not is_index or not opts.detail then
553 -- get diagram definition instances
554 local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
556 -- render all diagrams
557 for j, def in ipairs( diagrams ) do
559 _images[i][j] = def[1]
567 -- remember images - XXX: fixme (will cause probs with asymmetric data)
568 for y = 1, #_images[1] do
569 for x = 1, #_images do
570 table.insert( pngs, _images[x][y] )