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