Merge pull request #821 from andrewshadura/luci-route-types
[project/luci.git] / applications / luci-app-statistics / luasrc / statistics / rrdtool.lua
1 -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 module("luci.statistics.rrdtool", package.seeall)
5
6 require("luci.statistics.datatree")
7 require("luci.statistics.rrdtool.colors")
8 require("luci.statistics.i18n")
9 require("luci.model.uci")
10 require("luci.util")
11 require("luci.sys")
12
13 local fs = require "nixio.fs"
14
15
16 Graph = luci.util.class()
17
18 function Graph.__init__( self, timespan, opts )
19
20         opts = opts or { }
21
22         local uci = luci.model.uci.cursor()
23         local sections = uci:get_all( "luci_statistics" )
24
25         -- options
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("/$","")
35
36         -- helper classes
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 )
40
41         -- rrdtool default args
42         self.args = {
43                 "-a", "PNG",
44                 "-s", "NOW-" .. opts.timespan,
45                 "-w", opts.width
46         }
47
48         -- store options
49         self.opts = opts
50 end
51
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
56         end
57         t = t .. "/" .. dtype
58         if type(dtype_instance) == "string" and dtype_instance:len() > 0 then
59                 t = t .. "-" .. dtype_instance
60         end
61         return t
62 end
63
64 function Graph.mkrrdpath( self, ... )
65         return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) )
66 end
67
68 function Graph.mkpngpath( self, ... )
69         return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan )
70 end
71
72 function Graph.strippngpath( self, path )
73         return path:sub( self.opts.imgpath:len() + 2 )
74 end
75
76 function Graph._forcelol( self, list )
77         if type(list[1]) ~= "table" then
78                 return( { list } )
79         end
80         return( list )
81 end
82
83 function Graph._rrdtool( self, def, rrd )
84
85         -- prepare directory
86         local dir = def[1]:gsub("/[^/]+$","")
87         fs.mkdirr( dir )
88
89         -- construct commandline
90         local cmdline = "rrdtool graph"
91
92         -- copy default arguments to def stack
93         for i, opt in ipairs(self.args) do
94                 table.insert( def, 1 + i, opt )
95         end
96
97         -- construct commandline from def stack
98         for i, opt in ipairs(def) do
99                 opt = opt .. ""    -- force string
100
101                 if rrd then
102                         opt = opt:gsub( "{file}", rrd )
103                 end
104
105                 if opt:match("[^%w]") then
106                         cmdline = cmdline .. " '" .. opt .. "'"
107                 else
108                         cmdline = cmdline .. " " .. opt
109                 end
110         end
111
112         -- execute rrdtool
113         local rrdtool = io.popen( cmdline )
114         rrdtool:close()
115 end
116
117 function Graph._generic( self, opts, plugin, plugin_instance, dtype, index )
118
119         -- generated graph defs
120         local defs = { }
121
122         -- internal state variables
123         local _args         = { }
124         local _sources      = { }
125         local _stack_neg    = { }
126         local _stack_pos    = { }
127         local _longest_name = 0
128         local _has_totals   = false
129
130         -- some convenient aliases
131         local _ti           = table.insert
132         local _sf           = string.format
133
134         -- local helper: append a string.format() formatted string to given table
135         function _tif( list, fmt, ... )
136                 table.insert( list, string.format( fmt, ... ) )
137         end
138
139         -- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg
140         function __def(source)
141
142                 local inst = source.sname
143                 local rrd  = source.rrd
144                 local ds   = source.ds
145
146                 if not ds or ds:len() == 0 then ds = "value" end
147
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 )
150
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 )
156                 end
157
158                 _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
159         end
160
161         -- local helper: create cdefs depending on source options like flip and overlay
162         function __cdef(source)
163
164                 local prev
165
166                 -- find previous source, choose stack depending on flip state
167                 if source.flip then
168                         prev = _stack_neg[#_stack_neg]
169                 else
170                         prev = _stack_pos[#_stack_pos]
171                 end
172
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 )
180                      else
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 )
185                      end
186
187                 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
188                 else
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 )
193                      else
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 )
197                      end
198                 end
199
200                 -- create multiply by minus one cdef if flip is enabled
201                 if source.flip then
202
203                         -- create cdef statement: source_stk = source_stk * -1
204                         _tif( _args, "CDEF:%s_neg=%s_plot,-1,*", source.sname, source.sname )
205
206                         -- push to negative stack if overlay is disabled
207                         if not source.overlay then
208                                 _ti( _stack_neg, source.sname )
209                         end
210
211                 -- no flipping, push to positive stack if overlay is disabled
212                 elseif not source.overlay then
213
214                         -- push to positive stack
215                         _ti( _stack_pos, source.sname )
216                 end
217
218                 -- calculate total amount of data if requested
219                 if source.total then
220                         _tif( _args,
221                                 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
222                                 source.sname, source.sname, source.sname
223                         )
224
225                         _tif( _args,
226                                 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
227                                 source.sname, source.sname, source.sname
228                         )
229                 end
230         end
231
232         -- local helper: create cdefs required for calculating total values
233         function __cdef_totals()
234                 if _has_totals then
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" )
238                 end
239         end
240
241         -- local helper: create line and area statements
242         function __line(source)
243
244                 local line_color
245                 local area_color
246                 local legend
247                 local var
248
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 )
256                 else
257                         area_color = self.colors:random()
258                         line_color = self.colors:to_string( area_color )
259                 end
260
261                 -- derive area background color from line color
262                 area_color = self.colors:to_string( self.colors:faded( area_color ) )
263
264                 -- choose source_plot or source_neg variable depending on flip state
265                 if source.flip then
266                         var = "neg"
267                 else
268                         var = "plot"
269                 end
270
271                 -- create legend
272                 legend = _sf( "%-" .. _longest_name .. "s", source.title )
273
274                 -- create area if not disabled
275                 if not source.noarea then
276                         _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
277                 end
278
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 )
283         end
284
285         -- local helper: create gprint statements
286         function __gprint(source)
287
288                 local numfmt = opts.number_format or "%6.1lf"
289                 local totfmt = opts.totals_format or "%5.1lf%s"
290
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 )
294                 end
295
296                 -- always include AVERAGE
297                 _tif( _args, "GPRINT:%s_avg:AVERAGE:\tAvg\\: %s", source.sname, numfmt )
298
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 )
302                 end
303
304                 -- include total count if requested else include LAST
305                 if source.total then
306                         _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
307                 else
308                         _tif( _args, "GPRINT:%s_avg:LAST:\tLast\\: %s\\l", source.sname, numfmt )
309                 end
310         end
311
312
313         --
314         -- find all data sources
315         --
316
317         -- find data types
318         local data_types
319
320         if dtype then
321                 data_types = { dtype }
322         else
323                 data_types = opts.data.types or { }
324         end
325
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
329                                 _ti( data_types, k )
330                         end
331                 elseif opts.data.sources then
332                         for k, v in pairs(opts.data.sources) do
333                                 _ti( data_types, k )
334                         end
335                 end
336         end
337
338
339         -- iterate over data types
340         for i, dtype in ipairs(data_types) do
341
342                 -- find instances
343
344                 local data_instances
345
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]
349                         else
350                                 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
351                         end
352                 end
353
354                 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
355
356
357                 -- iterate over data instances
358                 for i, dinst in ipairs(data_instances) do
359
360                         -- construct combined data type / instance name
361                         local dname = dtype
362
363                         if dinst:len() > 0 then
364                                 dname = dname .. "_" .. dinst
365                         end
366
367
368                         -- find sources
369                         local data_sources = { "value" }
370
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]
376                                 end
377                         end
378
379
380                         -- iterate over data sources
381                         for i, dsource in ipairs(data_sources) do
382
383                                 local dsname  = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
384                                 local altname = dtype .. "__" .. dsource
385
386                                 --assert(dtype ~= "ping", dsname .. " or " .. altname)
387
388                                 -- find datasource options
389                                 local dopts = { }
390
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]
400                                         end
401                                 end
402
403
404                                 -- store values
405                                 _ti( _sources, {
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,
415                                         ds       = dsource,
416                                         type     = dtype,
417                                         instance = dinst,
418                                         index    = #_sources + 1,
419                                         sname    = ( #_sources + 1 ) .. dtype
420                                 } )
421
422
423                                 -- generate datasource title
424                                 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
425
426
427                                 -- find longest name ...
428                                 if _sources[#_sources].title:len() > _longest_name then
429                                         _longest_name = _sources[#_sources].title:len()
430                                 end
431
432
433                                 -- has totals?
434                                 if _sources[#_sources].total then
435                                         _has_totals = true
436                                 end
437                         end
438                 end
439         end
440
441
442         --
443         -- construct diagrams
444         --
445
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 = { "" }
449
450         if opts.per_instance then
451                 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
452         end
453
454
455         -- iterate over instances
456         for i, instance in ipairs(instances) do
457
458                 -- store title and vlabel
459                 _ti( _args, "-t" )
460                 _ti( _args, self.i18n:title( plugin, plugin_instance, _sources[1].type, instance, opts.title ) )
461                 _ti( _args, "-v" )
462                 _ti( _args, self.i18n:label( plugin, plugin_instance, _sources[1].type, instance, opts.vlabel ) )
463                 if opts.y_max then
464                         _ti ( _args, "-u" )
465                         _ti ( _args, opts.y_max )
466                 end
467                 if opts.y_min then
468                         _ti ( _args, "-l" )
469                         _ti ( _args, opts.y_min )
470                 end
471                 if opts.units_exponent then
472                         _ti ( _args, "-X" )
473                         _ti ( _args, opts.units_exponent )
474                 end
475                 if opts.alt_autoscale then
476                         _ti ( _args, "-A" )
477                 end
478                 if opts.alt_autoscale_max then
479                         _ti ( _args, "-M" )
480                 end
481
482                 -- store additional rrd options
483                 if opts.rrdopts then
484                         for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
485                 end
486
487                 -- sort sources
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
491                         return x < y
492                 end)
493
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 )
500                         end
501
502                         __def( source )
503                 end
504
505                 -- create CDEF required for calculating totals
506                 __cdef_totals()
507
508                 -- create CDEF statements for each instance in reversed order
509                 for i, source in ipairs(_sources) do
510                         __cdef( _sources[1 + #_sources - i] )
511                 end
512
513                 -- create LINE1, AREA and GPRINT statements for each instance
514                 for i, source in ipairs(_sources) do
515                         __line( source )
516                         __gprint( source )
517                 end
518
519                 -- prepend image path to arg stack
520                 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
521
522                 -- push arg stack to definition list
523                 _ti( defs, _args )
524
525                 -- reset stacks
526                 _args         = { }
527                 _stack_pos    = { }
528                 _stack_neg    = { }
529         end
530
531         return defs
532 end
533
534 function Graph.render( self, plugin, plugin_instance, is_index )
535
536         dtype_instances = dtype_instances or { "" }
537         local pngs = { }
538
539         -- check for a whole graph handler
540         local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
541         local stat, def = pcall( require, plugin_def )
542
543         if stat and def and type(def.rrdargs) == "function" then
544
545                 -- temporary image matrix
546                 local _images = { }
547
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
551                                 _images[i] = { }
552
553                                 -- get diagram definition instances
554                                 local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
555
556                                 -- render all diagrams
557                                 for j, def in ipairs( diagrams ) do
558                                         -- remember image
559                                         _images[i][j] = def[1]
560
561                                         -- exec
562                                         self:_rrdtool( def )
563                                 end
564                         end
565                 end
566
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] )
571                         end
572                 end
573         end
574
575         return pngs
576 end