* luc/statistics: add file/license headers
[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.rrdtool.definitions")
21 require("luci.statistics.i18n")
22 require("luci.model.uci")
23 require("luci.util")
24 require("luci.sys")
25 require("luci.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.Session()
35         local sections = uci:sections( "luci_statistics" )
36
37         -- helper classes
38         self.colors = luci.statistics.rrdtool.colors.Instance()
39         self.defs   = luci.statistics.rrdtool.definitions.Instance()
40         self.tree   = luci.statistics.datatree.Instance()
41         self.i18n   = luci.statistics.i18n.Instance( self )
42
43         -- options
44         opts.timespan  = timespan       or sections.rrdtool.default_timespan or 900
45         opts.rrasingle = opts.rrasingle or ( sections.collectd_rrdtool.RRASingle ~= "0" )
46         opts.host      = opts.host      or sections.collectd.Hostname        or luci.sys.hostname()
47         opts.width     = opts.width     or sections.rrdtool.image_width      or 400
48         opts.rrdpath   = opts.rrdpath   or sections.collectd_rrdtool.DataDir or "/tmp/rrd"
49         opts.imgpath   = opts.imgpath   or sections.rrdtool.image_path       or "/tmp/rrdimg"
50         opts.rrdpath   = opts.rrdpath:gsub("/$","")
51         opts.imgpath   = opts.imgpath:gsub("/$","")
52
53         -- rrdtool default args
54         self.args = {
55                 "-a", "PNG",
56                 "-s", "NOW-" .. opts.timespan,
57                 "-w", opts.width
58         }
59
60         -- store options
61         self.opts = opts
62 end
63
64 function Graph._mkpath( self, plugin, plugin_instance, dtype, dtype_instance )
65         local t = self.opts.host .. "/" .. plugin
66         if type(plugin_instance) == "string" and plugin_instance:len() > 0 then
67                 t = t .. "-" .. plugin_instance
68         end
69         t = t .. "/" .. dtype
70         if type(dtype_instance) == "string" and dtype_instance:len() > 0 then
71                 t = t .. "-" .. dtype_instance
72         end
73         return t
74 end
75
76 function Graph.mkrrdpath( self, ... )
77         return string.format( "%s/%s.rrd", self.opts.rrdpath, self:_mkpath( ... ) )
78 end
79
80 function Graph.mkpngpath( self, ... )
81         return string.format( "%s/%s.%i.png", self.opts.imgpath, self:_mkpath( ... ), self.opts.timespan )
82 end
83
84 function Graph.strippngpath( self, path )
85         return path:sub( self.opts.imgpath:len() + 2 )
86 end
87
88 function Graph.mktitle( self, plugin, plugin_instance, dtype, dtype_instance )
89
90         -- try various strings to retrieve a diagram title from the langfile
91         return "XXX"
92 end
93
94 function Graph._forcelol( self, list )
95         if type(list[1]) ~= "table" then
96                 return( { list } )
97         end
98         return( list )
99 end
100
101 function Graph._rrdtool( self, def, rrd )
102
103         -- prepare directory
104         local dir = def[1]:gsub("/[^/]+$","")
105         luci.fs.mkdir( dir, true )
106
107         -- construct commandline
108         local cmdline = "rrdtool graph"
109
110         -- copy default arguments to def stack
111         for i, opt in ipairs(self.args) do
112                 table.insert( def, 1 + i, opt )
113         end
114
115         -- construct commandline from def stack
116         for i, opt in ipairs(def) do
117                 opt = opt .. ""    -- force string
118
119                 if rrd then
120                         opt = opt:gsub( "{file}", rrd )
121                 end
122
123                 if opt:match("[^%w]") then
124                         cmdline = cmdline .. " '" .. opt .. "'"
125                 else
126                         cmdline = cmdline .. " " .. opt
127                 end
128         end
129
130         -- execute rrdtool
131         local rrdtool = io.popen( cmdline )
132         rrdtool:close()
133 end
134
135 function Graph._generic( self, opts, plugin, plugin_instance, dtype, index )
136
137         -- generated graph defs
138         local defs = { }
139
140         -- internal state variables
141         local _args         = { }
142         local _sources      = { }
143         local _stack_neg    = { }
144         local _stack_pos    = { }
145         local _longest_name = 0
146         local _has_totals   = false
147
148         -- some convenient aliases
149         local _ti           = table.insert
150         local _sf           = string.format
151
152         -- local helper: append a string.format() formatted string to given table
153         function _tif( list, fmt, ... )
154                 table.insert( list, string.format( fmt, ... ) )
155         end
156
157         -- local helper: create definitions for min, max, avg and create *_nnl (not null) variable from avg
158         function __def(source)
159
160                 local inst = source.sname
161                 local rrd  = source.rrd
162                 local ds   = source.ds
163
164                 if not ds or ds:len() == 0 then ds = "value" end
165
166                 _tif( _args, "DEF:%s_avg=%s:%s:AVERAGE", inst, rrd, ds )
167
168                 if not self.opts.rrasingle then
169                         _tif( _args, "DEF:%s_min=%s:%s:MIN", inst, rrd, ds )
170                         _tif( _args, "DEF:%s_max=%s:%s:MAX", inst, rrd, ds )
171                 end
172
173                 _tif( _args, "CDEF:%s_nnl=%s_avg,UN,0,%s_avg,IF", inst, inst, inst )
174         end
175
176         -- local helper: create cdefs depending on source options like flip and overlay
177         function __cdef(source)
178
179                 local prev
180
181                 -- find previous source, choose stack depending on flip state
182                 if source.flip then
183                         prev = _stack_neg[#_stack_neg]
184                 else
185                         prev = _stack_pos[#_stack_pos]
186                 end
187
188                 -- is first source in stack or overlay source: source_stk = source_nnl
189                 if not prev or source.overlay then
190                         -- create cdef statement
191                         _tif( _args, "CDEF:%s_stk=%s_nnl", source.sname, source.sname )
192
193                 -- is subsequent source without overlay: source_stk = source_nnl + previous_stk
194                 else
195                         -- create cdef statement
196                         _tif( _args, "CDEF:%s_stk=%s_nnl,%s_stk,+", source.sname, source.sname, prev )
197                 end
198
199                 -- create multiply by minus one cdef if flip is enabled
200                 if source.flip then
201
202                         -- create cdef statement: source_stk = source_stk * -1
203                         _tif( _args, "CDEF:%s_neg=%s_stk,-1,*", source.sname, source.sname )
204
205                         -- push to negative stack if overlay is disabled
206                         if not source.overlay then
207                                 _ti( _stack_neg, source.sname )
208                         end
209
210                 -- no flipping, push to positive stack if overlay is disabled
211                 elseif not source.overlay then
212
213                         -- push to positive stack
214                         _ti( _stack_pos, source.sname )
215                 end
216
217                 -- calculate total amount of data if requested
218                 if source.total then
219                         _tif( _args,
220                                 "CDEF:%s_avg_sample=%s_avg,UN,0,%s_avg,IF,sample_len,*",
221                                 source.sname, source.sname, source.sname
222                         )
223
224                         _tif( _args,
225                                 "CDEF:%s_avg_sum=PREV,UN,0,PREV,IF,%s_avg_sample,+",
226                                 source.sname, source.sname, source.sname
227                         )
228                 end
229         end
230
231         -- local helper: create cdefs required for calculating total values
232         function __cdef_totals()
233                 if _has_totals then
234                         _tif( _args, "CDEF:mytime=%s_avg,TIME,TIME,IF", _sources[1].sname    )
235                         _ti(  _args, "CDEF:sample_len_raw=mytime,PREV(mytime),-"             )
236                         _ti(  _args, "CDEF:sample_len=sample_len_raw,UN,0,sample_len_raw,IF" )
237                 end
238         end
239
240         -- local helper: create line and area statements
241         function __line(source)
242
243                 local line_color
244                 local area_color
245                 local legend
246                 local var
247
248                 -- find colors: try source, then opts.colors; fall back to random color
249                 if type(source.color) == "string" then
250                         line_color = source.color
251                         area_color = self.colors:from_string( line_color )
252                 elseif type(opts.colors[source.name:gsub("[^%w]","_")]) == "string" then
253                         line_color = opts.colors[source.name:gsub("[^%w]","_")]
254                         area_color = self.colors:from_string( line_color )
255                 else
256                         area_color = self.colors:random()
257                         line_color = self.colors:to_string( area_color )
258                 end
259
260                 -- derive area background color from line color
261                 area_color = self.colors:to_string( self.colors:faded( area_color ) )
262
263                 -- choose source_stk or source_neg variable depending on flip state
264                 if source.flip then
265                         var = "neg"
266                 else
267                         var = "stk"
268                 end
269
270                 -- create legend
271                 legend = _sf( "%-" .. _longest_name .. "s", source.title )
272
273                 -- create area if not disabled
274                 if not source.noarea then
275                         _tif( _args, "AREA:%s_%s#%s", source.sname, var, area_color )
276                 end
277
278                 -- create line1 statement
279                 _tif( _args, "LINE1:%s_%s#%s:%s", source.sname, var, line_color, legend )
280         end
281
282         -- local helper: create gprint statements
283         function __gprint(source)
284
285                 local numfmt = opts.number_format or "%6.1lf"
286                 local totfmt = opts.totals_format or "%5.1lf%s"
287
288                 -- don't include MIN if rrasingle is enabled
289                 if not self.opts.rrasingle then
290                         _tif( _args, "GPRINT:%s_min:MIN:%s Min", source.sname, numfmt )
291                 end
292
293                 -- always include AVERAGE
294                 _tif( _args, "GPRINT:%s_avg:AVERAGE:%s Avg", source.sname, numfmt )
295
296                 -- don't include MAX if rrasingle is enabled
297                 if not self.opts.rrasingle then
298                         _tif( _args, "GPRINT:%s_max:MAX:%s Max", source.sname, numfmt )
299                 end
300
301                 -- include total count if requested else include LAST
302                 if source.total then
303                         _tif( _args, "GPRINT:%s_avg_sum:LAST:(ca. %s Total)\\l", source.sname, totfmt )
304                 else
305                         _tif( _args, "GPRINT:%s_avg:LAST:%s Last\\l", source.sname, numfmt )
306                 end
307         end
308
309
310         --
311         -- find all data sources
312         --
313
314         -- find data types
315         local data_types
316
317         if dtype then
318                 data_types = { dtype }
319         else
320                 data_types = opts.data.types or { }
321         end
322
323         if not ( dtype or opts.data.types ) then
324                 if opts.data.instances then
325                         for k, v in pairs(opts.data.instances) do
326                                 _ti( data_types, k )
327                         end
328                 elseif opts.data.sources then
329                         for k, v in pairs(opts.data.sources) do
330                                 _ti( data_types, k )
331                         end
332                 end
333         end
334
335
336         -- iterate over data types
337         for i, dtype in ipairs(data_types) do
338
339                 -- find instances
340
341                 local data_instances
342
343                 if not opts.per_instance then
344                         if type(opts.data.instances) == "table" and type(opts.data.instances[dtype]) == "table" then
345                                 data_instances = opts.data.instances[dtype]
346                         else
347                                 data_instances = self.tree:data_instances( plugin, plugin_instance, dtype )
348                         end
349                 end
350
351                 if type(data_instances) ~= "table" or #data_instances == 0 then data_instances = { "" } end
352
353
354                 -- iterate over data instances
355                 for i, dinst in ipairs(data_instances) do
356
357                         -- construct combined data type / instance name
358                         local dname = dtype
359
360                         if dinst:len() > 0 then
361                                 dname = dname .. "_" .. dinst
362                         end
363
364
365                         -- find sources
366                         local data_sources = { "value" }
367
368                         if type(opts.data.sources) == "table" then
369                                 if type(opts.data.sources[dname]) == "table" then
370                                         data_sources = opts.data.sources[dname]
371                                 elseif type(opts.data.sources[dtype]) == "table" then
372                                         data_sources = opts.data.sources[dtype]
373                                 end
374                         end
375
376
377                         -- iterate over data sources
378                         for i, dsource in ipairs(data_sources) do
379
380                                 local dsname  = dtype .. "_" .. dinst:gsub("[^%w]","_") .. "_" .. dsource
381                                 local altname = dtype .. "__" .. dsource
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                                         ds       = dsource,
408                                         type     = dtype,
409                                         instance = dinst,
410                                         index    = #_sources + 1,
411                                         sname    = ( #_sources + 1 ) .. dtype
412                                 } )
413
414
415                                 -- generate datasource title
416                                 _sources[#_sources].title = self.i18n:ds( _sources[#_sources] )
417
418
419                                 -- find longest name ...
420                                 if _sources[#_sources].title:len() > _longest_name then
421                                         _longest_name = _sources[#_sources].title:len()
422                                 end
423
424
425                                 -- has totals?
426                                 if _sources[#_sources].total then
427                                         _has_totals = true
428                                 end
429                         end
430                 end
431         end
432
433
434         --
435         -- construct diagrams
436         --
437
438         -- if per_instance is enabled then find all instances from the first datasource in diagram
439         -- if per_instance is disabled then use an empty pseudo instance and use model provided values
440         local instances = { "" }
441
442         if opts.per_instance then
443                 instances = self.tree:data_instances( plugin, plugin_instance, _sources[1].type )
444         end
445
446
447         -- iterate over instances
448         for i, instance in ipairs(instances) do
449
450                 -- store title and vlabel
451                 _ti( _args, "-t" )
452                 _ti( _args, opts.title  or self.i18n:title( plugin, plugin_instance, _sources[1].type, instance ) )
453                 _ti( _args, "-v" )
454                 _ti( _args, opts.vlabel or self.i18n:label( plugin, plugin_instance, _sources[1].type, instance ) )
455
456                 -- store additional rrd options
457                 if opts.rrdopts then
458                         for i, o in ipairs(opts.rrdopts) do _ti( _args, o ) end
459                 end
460
461
462                 -- create DEF statements for each instance
463                 for i, source in ipairs(_sources) do
464                         -- fixup properties for per instance mode...
465                         if opts.per_instance then
466                                 source.instance = instance
467                                 source.rrd      = self:mkrrdpath( plugin, plugin_instance, source.type, instance )
468                         end
469
470                         __def( source )
471                 end
472
473                 -- create CDEF required for calculating totals
474                 __cdef_totals()
475
476                 -- create CDEF statements for each instance in reversed order
477                 for i, source in ipairs(_sources) do
478                         __cdef( _sources[1 + #_sources - i] )
479                 end
480
481                 -- create LINE1, AREA and GPRINT statements for each instance
482                 for i, source in ipairs(_sources) do
483                         __line( source )
484                         __gprint( source )
485                 end
486
487                 -- prepend image path to arg stack
488                 _ti( _args, 1, self:mkpngpath( plugin, plugin_instance, index .. instance ) )
489
490                 -- push arg stack to definition list
491                 _ti( defs, _args )
492
493                 -- reset stacks
494                 _args         = { }
495                 _stack_pos    = { }
496                 _stack_neg    = { }
497         end
498
499         return defs
500 end
501
502 function Graph.render( self, plugin, plugin_instance )
503
504         dtype_instances = dtype_instances or { "" }
505         local pngs = { }
506
507         -- check for a whole graph handler
508         local plugin_def = "luci.statistics.rrdtool.definitions." .. plugin
509         local stat, def = pcall( require, plugin_def )
510
511         if stat and def and type(def.rrdargs) == "function" then
512
513                 -- temporary image matrix
514                 local _images = { }
515
516                 -- get diagram definitions
517                 for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance ) ) ) do
518
519                         _images[i] = { }
520
521                         -- get diagram definition instances
522                         local diagrams = self:_generic( opts, plugin, plugin_instance, nil, i )
523
524                         -- render all diagrams
525                         for j, def in ipairs( diagrams ) do
526
527                                 -- remember image
528                                 _images[i][j] = def[1]
529
530                                 -- exec
531                                 self:_rrdtool( def )
532                         end
533                 end
534
535                 -- remember images - XXX: fixme (will cause probs with asymmetric data)
536                 for y = 1, #_images[1] do
537                         for x = 1, #_images do
538                                 table.insert( pngs, _images[x][y] )
539                         end
540                 end
541         else
542
543                 -- no graph handler, iterate over data types
544                 for i, dtype in ipairs( self.tree:data_types( plugin, plugin_instance ) ) do
545
546                         -- check for data type handler
547                         local dtype_def = plugin_def .. "." .. dtype
548                         local stat, def = pcall( require, dtype_def )
549
550                         if stat and def and type(def.rrdargs) == "function" then
551
552                                 -- temporary image matrix
553                                 local _images = { }
554
555                                 -- get diagram definitions
556                                 for i, opts in ipairs( self:_forcelol( def.rrdargs( self, plugin, plugin_instance, dtype ) ) ) do
557
558                                         _images[i] = { }
559
560                                         -- get diagram definition instances
561                                         local diagrams = self:_generic( opts, plugin, plugin_instance, dtype, i )
562
563                                         -- render all diagrams
564                                         for j, def in ipairs( diagrams ) do
565
566                                                 -- remember image
567                                                 _images[i][j] = def[1]
568
569                                                 -- exec
570                                                 self:_rrdtool( def )
571                                         end
572                                 end
573
574                                 -- remember images - XXX: fixme (will cause probs with asymmetric data)
575                                 for y = 1, #_images[1] do
576                                         for x = 1, #_images do
577                                                 table.insert( pngs, _images[x][y] )
578                                         end
579                                 end
580                         else
581
582                                 -- no data type handler, fall back to builtin definition
583                                 if type(self.defs.definitions[dtype]) == "table" then
584
585                                         -- iterate over data type instances
586                                         for i, inst in ipairs( self.tree:data_instances( plugin, plugin_instance, dtype ) ) do
587
588                                                 local title = self:mktitle( plugin, plugin_instance, dtype, inst )
589                                                 local png   = self:mkpngpath( plugin, plugin_instance, dtype, inst )
590                                                 local rrd   = self:mkrrdpath( plugin, plugin_instance, dtype, inst )
591                                                 local args  = { png, "-t", title }
592
593                                                 for i, o in ipairs(self.defs.definitions[dtype]) do
594                                                         table.insert( args, o )
595                                                 end
596
597                                                 -- remember image
598                                                 table.insert( pngs, png )
599
600                                                 -- exec
601                                                 self:_rrdtool( args, rrd )
602                                         end
603                                 end
604                         end
605                 end
606         end
607
608         return pngs
609 end