3 Luci statistics - rrdtool interface library / diagram model interpreter
4 (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
16 module("luci.statistics.rrdtool", package.seeall)
18 require("luci.statistics.datatree")
19 require("luci.statistics.rrdtool.colors")
20 require("luci.statistics.i18n")
21 require("luci.model.uci")
25 local fs = require "nixio.fs"
28 Graph = luci.util.class()
30 function Graph.__init__( self, timespan, opts )
34 local uci = luci.model.uci.cursor()
35 local sections = uci:get_all( "luci_statistics" )
38 opts.timespan = timespan or sections.rrdtool.default_timespan or 900
39 opts.rrasingle = opts.rrasingle or ( sections.collectd_rrdtool.RRASingle == "1" )
40 opts.host = opts.host or sections.collectd.Hostname or luci.sys.hostname()
41 opts.width = opts.width or sections.rrdtool.image_width or 400
42 opts.rrdpath = opts.rrdpath or sections.collectd_rrdtool.DataDir or "/tmp/rrd"
43 opts.imgpath = opts.imgpath or sections.rrdtool.image_path or "/tmp/rrdimg"
44 opts.rrdpath = opts.rrdpath:gsub("/$","")
45 opts.imgpath = opts.imgpath:gsub("/$","")
48 self.colors = luci.statistics.rrdtool.colors.Instance()
49 self.tree = luci.statistics.datatree.Instance(opts.host)
50 self.i18n = luci.statistics.i18n.Instance( self )
52 -- rrdtool default args
55 "-s", "NOW-" .. opts.timespan,
63 function Graph._mkpath( self, plugin, plugin_instance, dtype, dtype_instance )
64 local t = self.opts.host .. "/" .. plugin
65 if type(plugin_instance) == "string" and plugin_instance:len() > 0 then
66 t = t .. "-" .. plugin_instance
69 if type(dtype_instance) == "string" and dtype_instance:len() > 0 then
70 t = t .. "-" .. dtype_instance
75 function Graph.mkrrdpath( self, ... )
76 return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) )
79 function Graph.mkpngpath( self, ... )
80 return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan )
83 function Graph.strippngpath( self, path )
84 return path:sub( self.opts.imgpath:len() + 2 )
87 function Graph._forcelol( self, list )
88 if type(list[1]) ~= "table" then
94 function Graph._rrdtool( self, def, rrd )
97 local dir = def[1]:gsub("/[^/]+$","")
100 -- construct commandline
101 local cmdline = "rrdtool graph"
103 -- copy default arguments to def stack
104 for i, opt in ipairs(self.args) do
105 table.insert( def, 1 + i, opt )
108 -- construct commandline from def stack
109 for i, opt in ipairs(def) do
110 opt = opt .. "" -- force string
113 opt = opt:gsub( "{file}", rrd )
116 if opt:match("[^%w]") then
117 cmdline = cmdline .. " '" .. opt .. "'"
119 cmdline = cmdline .. " " .. opt
124 local rrdtool = io.popen( cmdline )
128 function Graph._generic( self, opts, plugin, plugin_instance, dtype, index )
130 -- generated graph defs
133 -- internal state variables
136 local _stack_neg = { }
137 local _stack_pos = { }
138 local _longest_name = 0
139 local _has_totals = false
141 -- some convenient aliases
142 local _ti = table.insert
143 local _sf = string.format
145 -- local helper: append a string.format() formatted string to given table
146 function _tif( list, fmt, ... )
147 table.insert( list, string.format( fmt, ... ) )
150 -- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg
151 function __def(source)
153 local inst = source.sname
154 local rrd = source.rrd
157 if not ds or ds:len() == 0 then ds = "value" end
159 _tif( _args, "DEF:%s_avg=%s:%s:AVERAGE", inst, rrd, ds )
161 if not self.opts.rrasingle then
162 _tif( _args, "DEF:%s_min=%s:%s:MIN", inst, rrd, ds )
163 _tif( _args, "DEF:%s_max=%s:%s:MAX", inst, rrd, ds )
166 _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
169 -- local helper: create cdefs depending on source options like flip and overlay
170 function __cdef(source)
174 -- find previous source, choose stack depending on flip state
176 prev = _stack_neg[#_stack_neg]
178 prev = _stack_pos[#_stack_pos]
181 -- is first source in stack or overlay source: source_stk = source_nnl
182 if not prev or source.overlay then
183 -- create cdef statement
184 _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
186 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
188 -- create cdef statement
189 _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
192 -- create multiply by minus one cdef if flip is enabled
195 -- create cdef statement: source_stk = source_stk * -1
196 _tif( _args, "CDEF:%s_neg=%s_stk,-1,*", source.sname, source.sname )
198 -- push to negative stack if overlay is disabled
199 if not source.overlay then
200 _ti( _stack_neg, source.sname )
203 -- no flipping, push to positive stack if overlay is disabled
204 elseif not source.overlay then
206 -- push to positive stack
207 _ti( _stack_pos, source.sname )
210 -- calculate total amount of data if requested
213 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
214 source.sname, source.sname, source.sname
218 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
219 source.sname, source.sname, source.sname
224 -- local helper: create cdefs required for calculating total values
225 function __cdef_totals()
227 _tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname )
228 _ti( _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-" )
229 _ti( _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" )
233 -- local helper: create line and area statements
234 function __line(source)
241 -- find colors: try source, then opts.colors; fall back to random color
242 if type(source.color) == "string" then
243 line_color = source.color
244 area_color = self.colors:from_string( line_color )
245 elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then
246 line_color = opts.colors[source.name:gsub("[^%w]","_")]
247 area_color = self.colors:from_string( line_color )
249 area_color = self.colors:random()
250 line_color = self.colors:to_string( area_color )
253 -- derive area background color from line color
254 area_color = self.colors:to_string( self.colors:faded( area_color ) )
256 -- choose source_stk or source_neg variable depending on flip state
264 legend = _sf( "%-" .. _longest_name .. "s", source.title )
266 -- create area if not disabled
267 if not source.noarea then
268 _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
271 -- create line1 statement
272 _tif( _args, "LINE%d:%s_%s#%s:%s",
273 source.noarea and 2 or 1,
274 source.sname, var, line_color, legend )
277 -- local helper: create gprint statements
278 function __gprint(source)
280 local numfmt = opts.number_format or "%6.1lf"
281 local totfmt = opts.totals_format or "%5.1lf%s"
283 -- don't include MIN if rrasingle is enabled
284 if not self.opts.rrasingle then
285 _tif( _args, "GPRINT:%s_min:MIN:\tMin\\: %s", source.sname, numfmt )
288 -- always include AVERAGE
289 _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
291 -- don't include MAX if rrasingle is enabled
292 if not self.opts.rrasingle then
293 _tif( _args, "GPRINT:%s_max:MAX:\tMax\\: %s", source.sname, numfmt )
296 -- include total count if requested else include LAST
298 _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
300 _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
306 -- find all data sources
313 data_types = { dtype }
315 data_types = opts.data.types or { }
318 if not ( dtype or opts.data.types ) then
319 if opts.data.instances then
320 for k, v in pairs(opts.data.instances) do
323 elseif opts.data.sources then
324 for k, v in pairs(opts.data.sources) do
331 -- iterate over data types
332 for i, dtype in ipairs(data_types) do
338 if not opts.per_instance then
339 if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then
340 data_instances = opts.data.instances[dtype]
342 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
346 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
349 -- iterate over data instances
350 for i, dinst in ipairs(data_instances) do
352 -- construct combined data type / instance name
355 if dinst:len() > 0 then
356 dname = dname .. "_" .. dinst
361 local data_sources = { "value" }
363 if type(opts.data.sources) == "table" then
364 if type(opts.data.sources[dname]) == "table" then
365 data_sources = opts.data.sources[dname]
366 elseif type(opts.data.sources[dtype]) == "table" then
367 data_sources = opts.data.sources[dtype]
372 -- iterate over data sources
373 for i, dsource in ipairs(data_sources) do
375 local dsname = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
376 local altname = dtype .. "__" .. dsource
378 --assert(dtype ~= "ping", dsname .. " or " .. altname)
380 -- find datasource options
383 if type(opts.data.options) == "table" then
384 if type(opts.data.options[dsname]) == "table" then
385 dopts = opts.data.options[dsname]
386 elseif type(opts.data.options[altname]) == "table" then
387 dopts = opts.data.options[altname]
388 elseif type(opts.data.options[dname]) == "table" then
389 dopts = opts.data.options[dname]
390 elseif type(opts.data.options[dtype]) == "table" then
391 dopts = opts.data.options[dtype]
398 rrd = dopts.rrd or self:mkrrdpath( plugin, plugin_instance, dtype, dinst ),
399 color = dopts.color or self.colors:to_string( self.colors:random() ),
400 flip = dopts.flip or false,
401 total = dopts.total or false,
402 overlay = dopts.overlay or false,
403 noarea = dopts.noarea or false,
404 title = dopts.title or nil,
408 index = #_sources + 1,
409 sname = ( #_sources + 1 ) .. dtype
413 -- generate datasource title
414 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
417 -- find longest name ...
418 if _sources[#_sources].title:len() > _longest_name then
419 _longest_name = _sources[#_sources].title:len()
424 if _sources[#_sources].total then
433 -- construct diagrams
436 -- if per_instance is enabled then find all instances from the first datasource in diagram
437 -- if per_instance is disabled then use an empty pseudo instance and use model provided values
438 local instances = { "" }
440 if opts.per_instance then
441 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
445 -- iterate over instances
446 for i, instance in ipairs(instances) do
448 -- store title and vlabel
450 _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
452 _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
454 -- store additional rrd options
456 for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
460 -- create DEF statements for each instance
461 for i, source in ipairs(_sources) do
462 -- fixup properties for per instance mode...
463 if opts.per_instance then
464 source.instance = instance
465 source.rrd = self:mkrrdpath( plugin, plugin_instance, source.type, instance )
471 -- create CDEF required for calculating totals
474 -- create CDEF statements for each instance in reversed order
475 for i, source in ipairs(_sources) do
476 __cdef( _sources[1 + #_sources - i] )
479 -- create LINE1, AREA and GPRINT statements for each instance
480 for i, source in ipairs(_sources) do
485 -- prepend image path to arg stack
486 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
488 -- push arg stack to definition list
500 function Graph.render( self, plugin, plugin_instance, is_index )
502 dtype_instances = dtype_instances or { "" }
505 -- check for a whole graph handler
506 local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
507 local stat, def = pcall( require, plugin_def )
509 if stat and def and type(def.rrdargs) == "function" then
511 -- temporary image matrix
514 -- get diagram definitions
515 for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, nil, is_index ) ) ) do
516 if not is_index or not opts.detail then
519 -- get diagram definition instances
520 local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
522 -- render all diagrams
523 for j, def in ipairs( diagrams ) do
525 _images[i][j] = def[1]
533 -- remember images - XXX: fixme (will cause probs with asymmetric data)
534 for y = 1, #_images[1] do
535 for x = 1, #_images do
536 table.insert( pngs, _images[x][y] )