Rework LuCI build system
[project/luci.git] / applications / luci-app-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_raw=%s:%s:AVERAGE", inst, rrd, ds )
160                 _tif( _args, "CDEF:%s_avg=%s_avg_raw,%s", inst, inst, source.transform_rpn )
161
162                 if not self.opts.rrasingle then
163                         _tif( _args, "DEF:%s_min_raw=%s:%s:MIN", inst, rrd, ds )
164                         _tif( _args, "CDEF:%s_min=%s_min_raw,%s", inst, inst, source.transform_rpn )
165                         _tif( _args, "DEF:%s_max_raw=%s:%s:MAX", inst, rrd, ds )
166                         _tif( _args, "CDEF:%s_max=%s_max_raw,%s", inst, inst, source.transform_rpn )
167                 end
168
169                 _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
170         end
171
172         -- local helper: create cdefs depending on source options like flip and overlay
173         function __cdef(source)
174
175                 local prev
176
177                 -- find previous source, choose stack depending on flip state
178                 if source.flip then
179                         prev = _stack_neg[#_stack_neg]
180                 else
181                         prev = _stack_pos[#_stack_pos]
182                 end
183
184                 -- is first source in stack or overlay source: source_stk = source_nnl
185                 if not prev or source.overlay then
186                         -- create cdef statement for cumulative stack (no NaNs) and also
187                         -- for display (preserving NaN where no points should be displayed)
188                         _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
189                         _tif( _args, "CDEF:%s_plot=%s_avg", source.sname, source.sname )
190
191                 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
192                 else
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_avg,%s_stk,+", source.sname, source.sname, prev )
196                 end
197
198                 -- create multiply by minus one cdef if flip is enabled
199                 if source.flip then
200
201                         -- create cdef statement: source_stk = source_stk * -1
202                         _tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname )
203
204                         -- push to negative stack if overlay is disabled
205                         if not source.overlay then
206                                 _ti( _stack_neg, source.sname )
207                         end
208
209                 -- no flipping, push to positive stack if overlay is disabled
210                 elseif not source.overlay then
211
212                         -- push to positive stack
213                         _ti( _stack_pos, source.sname )
214                 end
215
216                 -- calculate total amount of data if requested
217                 if source.total then
218                         _tif( _args,
219                                 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
220                                 source.sname, source.sname, source.sname
221                         )
222
223                         _tif( _args,
224                                 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
225                                 source.sname, source.sname, source.sname
226                         )
227                 end
228         end
229
230         -- local helper: create cdefs required for calculating total values
231         function __cdef_totals()
232                 if _has_totals then
233                         _tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname    )
234                         _ti(  _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-"             )
235                         _ti(  _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" )
236                 end
237         end
238
239         -- local helper: create line and area statements
240         function __line(source)
241
242                 local line_color
243                 local area_color
244                 local legend
245                 local var
246
247                 -- find colors: try source, then opts.colors; fall back to random color
248                 if type(source.color) == "string" then
249                         line_color = source.color
250                         area_color = self.colors:from_string( line_color )
251                 elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then
252                         line_color = opts.colors[source.name:gsub("[^%w]","_")]
253                         area_color = self.colors:from_string( line_color )
254                 else
255                         area_color = self.colors:random()
256                         line_color = self.colors:to_string( area_color )
257                 end
258
259                 -- derive area background color from line color
260                 area_color = self.colors:to_string( self.colors:faded( area_color ) )
261
262                 -- choose source_plot or source_neg variable depending on flip state
263                 if source.flip then
264                         var = "neg"
265                 else
266                         var = "plot"
267                 end
268
269                 -- create legend
270                 legend = _sf( "%-" .. _longest_name .. "s", source.title )
271
272                 -- create area if not disabled
273                 if not source.noarea then
274                         _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
275                 end
276
277                 -- create line1 statement
278                 _tif( _args, "LINE%d:%s_%s#%s:%s",
279                         source.noarea and 2 or 1,
280                         source.sname, var, line_color, legend )
281         end
282
283         -- local helper: create gprint statements
284         function __gprint(source)
285
286                 local numfmt = opts.number_format or "%6.1lf"
287                 local totfmt = opts.totals_format or "%5.1lf%s"
288
289                 -- don't include MIN if rrasingle is enabled
290                 if not self.opts.rrasingle then
291                         _tif( _args, "GPRINT:%s_min:MIN:\tMin\\: %s", source.sname, numfmt )
292                 end
293
294                 -- always include AVERAGE
295                 _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
296
297                 -- don't include MAX if rrasingle is enabled
298                 if not self.opts.rrasingle then
299                         _tif( _args, "GPRINT:%s_max:MAX:\tMax\\: %s", source.sname, numfmt )
300                 end
301
302                 -- include total count if requested else include LAST
303                 if source.total then
304                         _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
305                 else
306                         _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
307                 end
308         end
309
310
311         --
312         -- find all data sources
313         --
314
315         -- find data types
316         local data_types
317
318         if dtype then
319                 data_types = { dtype }
320         else
321                 data_types = opts.data.types or { }
322         end
323
324         if not ( dtype or opts.data.types ) then
325                 if opts.data.instances then
326                         for k, v in pairs(opts.data.instances) do
327                                 _ti( data_types, k )
328                         end
329                 elseif opts.data.sources then
330                         for k, v in pairs(opts.data.sources) do
331                                 _ti( data_types, k )
332                         end
333                 end
334         end
335
336
337         -- iterate over data types
338         for i, dtype in ipairs(data_types) do
339
340                 -- find instances
341
342                 local data_instances
343
344                 if not opts.per_instance then
345                         if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then
346                                 data_instances = opts.data.instances[dtype]
347                         else
348                                 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
349                         end
350                 end
351
352                 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
353
354
355                 -- iterate over data instances
356                 for i, dinst in ipairs(data_instances) do
357
358                         -- construct combined data type / instance name
359                         local dname = dtype
360
361                         if dinst:len() > 0 then
362                                 dname = dname .. "_" .. dinst
363                         end
364
365
366                         -- find sources
367                         local data_sources = { "value" }
368
369                         if type(opts.data.sources) == "table" then
370                                 if type(opts.data.sources[dname]) == "table" then
371                                         data_sources = opts.data.sources[dname]
372                                 elseif type(opts.data.sources[dtype]) == "table" then
373                                         data_sources = opts.data.sources[dtype]
374                                 end
375                         end
376
377
378                         -- iterate over data sources
379                         for i, dsource in ipairs(data_sources) do
380
381                                 local dsname  = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
382                                 local altname = dtype .. "__" .. dsource
383
384                                 --assert(dtype ~= "ping", dsname .. " or " .. altname)
385
386                                 -- find datasource options
387                                 local dopts = { }
388
389                                 if type(opts.data.options) == "table" then
390                                         if type(opts.data.options[dsname]) == "table" then
391                                                 dopts = opts.data.options[dsname]
392                                         elseif type(opts.data.options[altname]) == "table" then
393                                                 dopts = opts.data.options[altname]
394                                         elseif type(opts.data.options[dname]) == "table" then
395                                                 dopts = opts.data.options[dname]
396                                         elseif type(opts.data.options[dtype]) == "table" then
397                                                 dopts = opts.data.options[dtype]
398                                         end
399                                 end
400
401
402                                 -- store values
403                                 _ti( _sources, {
404                                         rrd      = dopts.rrd     or self:mkrrdpath( plugin, plugin_instance, dtype, dinst ),
405                                         color    = dopts.color   or self.colors:to_string( self.colors:random() ),
406                                         flip     = dopts.flip    or false,
407                                         total    = dopts.total   or false,
408                                         overlay  = dopts.overlay or false,
409                                         transform_rpn = dopts.transform_rpn or "0,+",
410                                         noarea   = dopts.noarea  or false,
411                                         title    = dopts.title   or nil,
412                                         ds       = dsource,
413                                         type     = dtype,
414                                         instance = dinst,
415                                         index    = #_sources + 1,
416                                         sname    = ( #_sources + 1 ) .. dtype
417                                 } )
418
419
420                                 -- generate datasource title
421                                 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
422
423
424                                 -- find longest name ...
425                                 if _sources[#_sources].title:len() > _longest_name then
426                                         _longest_name = _sources[#_sources].title:len()
427                                 end
428
429
430                                 -- has totals?
431                                 if _sources[#_sources].total then
432                                         _has_totals = true
433                                 end
434                         end
435                 end
436         end
437
438
439         --
440         -- construct diagrams
441         --
442
443         -- if per_instance is enabled then find all instances from the first datasource in diagram
444         -- if per_instance is disabled then use an empty pseudo instance and use model provided values
445         local instances = { "" }
446
447         if opts.per_instance then
448                 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
449         end
450
451
452         -- iterate over instances
453         for i, instance in ipairs(instances) do
454
455                 -- store title and vlabel
456                 _ti( _args, "-t" )
457                 _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
458                 _ti( _args, "-v" )
459                 _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
460                 if opts.y_max then
461                         _ti ( _args, "-u" )
462                         _ti ( _args, opts.y_max )
463                 end
464                 if opts.y_min then
465                         _ti ( _args, "-l" )
466                         _ti ( _args, opts.y_min )
467                 end
468                 if opts.units_exponent then
469                         _ti ( _args, "-X" )
470                         _ti ( _args, opts.units_exponent )
471                 end
472
473                 -- store additional rrd options
474                 if opts.rrdopts then
475                         for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
476                 end
477
478
479                 -- create DEF statements for each instance
480                 for i, source in ipairs(_sources) do
481                         -- fixup properties for per instance mode...
482                         if opts.per_instance then
483                                 source.instance = instance
484                                 source.rrd      = self:mkrrdpath( plugin, plugin_instance, source.type, instance )
485                         end
486
487                         __def( source )
488                 end
489
490                 -- create CDEF required for calculating totals
491                 __cdef_totals()
492
493                 -- create CDEF statements for each instance in reversed order
494                 for i, source in ipairs(_sources) do
495                         __cdef( _sources[1 + #_sources - i] )
496                 end
497
498                 -- create LINE1, AREA and GPRINT statements for each instance
499                 for i, source in ipairs(_sources) do
500                         __line( source )
501                         __gprint( source )
502                 end
503
504                 -- prepend image path to arg stack
505                 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
506
507                 -- push arg stack to definition list
508                 _ti( defs, _args )
509
510                 -- reset stacks
511                 _args         = { }
512                 _stack_pos    = { }
513                 _stack_neg    = { }
514         end
515
516         return defs
517 end
518
519 function Graph.render( self, plugin, plugin_instance, is_index )
520
521         dtype_instances = dtype_instances or { "" }
522         local pngs = { }
523
524         -- check for a whole graph handler
525         local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
526         local stat, def = pcall( require, plugin_def )
527
528         if stat and def and type(def.rrdargs) == "function" then
529
530                 -- temporary image matrix
531                 local _images = { }
532
533                 -- get diagram definitions
534                 for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, nil, is_index ) ) ) do
535                         if not is_index or not opts.detail then
536                                 _images[i] = { }
537
538                                 -- get diagram definition instances
539                                 local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
540
541                                 -- render all diagrams
542                                 for j, def in ipairs( diagrams ) do
543                                         -- remember image
544                                         _images[i][j] = def[1]
545
546                                         -- exec
547                                         self:_rrdtool( def )
548                                 end
549                         end
550                 end
551
552                 -- remember images - XXX: fixme (will cause probs with asymmetric data)
553                 for y = 1, #_images[1] do
554                         for x = 1, #_images do
555                                 table.insert( pngs, _images[x][y] )
556                         end
557                 end
558         end
559
560         return pngs
561 end