* luci/libs: uvl - cleanup round #1
[project/luci.git] / libs / uvl / luasrc / uvl.lua
1 --[[
2
3 UCI Validation Layer - Main Library
4 (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
5 (c) 2008 Steven Barth <steven@midlink.org>
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12
13 $Id$
14
15 ]]--
16
17 module( "luci.uvl", package.seeall )
18
19 require("luci.fs")
20 require("luci.util")
21 require("luci.model.uci")
22 require("luci.uvl.datatypes")
23 --require("luci.uvl.validation")
24 require("luci.uvl.dependencies")
25
26 TYPE_SECTION  = 0x01
27 TYPE_VARIABLE = 0x02
28 TYPE_ENUM     = 0x03
29
30 STRICT_UNKNOWN_SECTIONS = true
31 STRICT_UNKNOWN_OPTIONS  = true
32
33
34 local default_schemedir = "/etc/scheme"
35
36 local function _assert( condition, fmt, ... )
37         if not condition then
38                 return assert( nil, string.format( fmt, ... ) )
39         else
40                 return condition
41         end
42 end
43
44 UVL = luci.util.class()
45
46 function UVL.__init__( self, schemedir )
47         self.schemedir  = schemedir or default_schemedir
48         self.packages   = { }
49         self.beenthere  = { }
50         self.uci                = luci.model.uci
51         self.datatypes  = luci.uvl.datatypes
52 end
53
54
55 function UVL._scheme_section( self, uci, c, s )
56         if self.packages[c] and uci[s] then
57                 return self.packages[c].sections[uci[s][".type"]]
58         end
59 end
60
61 function UVL._scheme_option( self, uci, c, s, o )
62         if self.packages[c] and uci[s] and uci[s][o] then
63                 return self.packages[c].variables[uci[s][".type"]][o]
64         elseif self.packages[c] and self.packages[c].variables[s] then
65                 return self.packages[c].variables[s][o]
66         end
67 end
68
69 function UVL._keys( self, tbl )
70         local keys = { }
71         if tbl then
72                 for k, _ in luci.util.kspairs(tbl) do
73                         table.insert( keys, k )
74                 end
75         end
76         return keys
77 end
78
79
80 --- Validate given configuration.
81 -- @param config        Name of the configuration to validate
82 -- @param scheme        Scheme to validate against (optional)
83 -- @return                      Boolean indicating weather the given config validates
84 -- @return                      String containing the reason for errors (if any)
85 function UVL.validate( self, config )
86
87         self.uci.set_confdir( self.uci.confdir_default )
88         self.uci.load( config )
89
90         local co = self.uci.get_all( config )
91
92         local function _uci_foreach( type, func )
93                 local ok, err
94                 for k, v in pairs(co) do
95                         if co[k]['.type'] == type then
96                                 ok, err = func( k, v )
97                                 if not ok then break end
98                         end
99                 end
100                 return ok, err
101         end
102
103         for k, v in pairs( self.packages[config].sections ) do
104                 local ok, err = _uci_foreach( k,
105                         function(s)
106                                 local sect = luci.uvl.section( self, co, k, config, s )
107                                 return self:_validate_section( sect )
108                         end
109                 )
110                 if not ok then return false, err end
111         end
112
113         if STRICT_UNKNOWN_SECTIONS then
114                 for k, v in pairs(co) do
115                         if not self.beenthere[config..'.'..k] then
116                                 return false, "Section '" .. config .. '.' .. co[k]['.type'] ..
117                                         "' not found in scheme"
118                         end
119                 end
120         end
121
122         return true, nil
123 end
124
125 --- Validate given section of given configuration.
126 -- @param config        Name of the configuration to validate
127 -- @param section       Key of the section to validate
128 -- @param scheme        Scheme to validate against
129 -- @return                      Boolean indicating weather the given config validates
130 -- @return                      String containing the reason for errors (if any)
131 function UVL._validate_section( self, section )
132
133         if section:values() then
134
135                 for _, v in ipairs(section:variables()) do
136                         local ok, err = self:_validate_option( v )
137
138                         if not ok then
139                                 return ok, err
140                         end
141                 end
142
143                 local ok, err = luci.uvl.dependencies.check( self, section )
144
145                 if not ok then
146                         return false, "All possible dependencies failed"
147                 end
148         else
149                 print( "Error, scheme section '" .. section:sid() .. "' not found in data" )
150         end
151
152         if STRICT_UNKNOWN_OPTIONS and not section:section().dynamic then
153                 for k, v in pairs(section:values()) do
154                         if k:sub(1,1) ~= "." and not self.beenthere[
155                                 section:cid() .. '.' .. k
156                         ] then
157                                 return false, "Option '" .. section:sid() .. '.' .. k ..
158                                         "' not found in scheme"
159                         end
160                 end
161         end
162
163         return true, nil
164 end
165
166 --- Validate given option within section of given configuration.
167 -- @param config        Name of the configuration to validate
168 -- @param section       Key of the section to validate
169 -- @param option        Name of the option to validate
170 -- @param scheme        Scheme to validate against
171 -- @return                      Boolean indicating weather the given config validates
172 -- @return                      String containing the reason for errors (if any)
173 function UVL._validate_option( self, option, nodeps )
174
175         if not option:option() then
176                 return false, "Requested option '" .. option:sid() ..
177                         "' not found in scheme"
178         end
179
180         if option:option().required and not option:value() then
181                 return false, "Mandatory variable '" .. option:cid() ..
182                         "' doesn't have a value"
183         end
184
185         if option:option().type == "enum" and option:value() then
186                 if not option:option().values or
187                    not option:option().values[option:value()]
188                 then
189                         return false, "Value '" .. ( option:value() or '<nil>' ) ..
190                                 "' of given option '" .. option:cid() ..
191                                 "' is not defined in enum { " ..
192                                 table.concat(self:_keys(option:option().values),", ") ..
193                                 " }"
194                 end
195         end
196
197         if option:option().datatype and option:value() then
198                 if self.datatypes[option:option().datatype] then
199                         if not self.datatypes[option:option().datatype](option:value()) then
200                                 return false, "Value '" .. ( option:value() or '<nil>' ) ..
201                                         "' of given option '" .. option:cid() ..
202                                         "' doesn't validate as datatype '" ..
203                                         option:option().datatype .. "'"
204                         end
205                 else
206                         return false, "Unknown datatype '" ..
207                                 option:option().datatype .. "' encountered"
208                 end
209         end
210
211         if not nodeps then
212                 return luci.uvl.dependencies.check( self, option )
213         end
214
215         return true, nil
216 end
217
218 --- Find all parts of given scheme and construct validation tree
219 -- @param scheme        Name of the scheme to parse
220 -- @return                      Parsed scheme
221 function UVL.read_scheme( self, scheme )
222         local schemes = { }
223
224         for i, file in ipairs( luci.fs.glob(self.schemedir .. '/*/' .. scheme) ) do
225                 _assert( luci.fs.access(file), "Can't access file '%s'", file )
226
227                 self.uci.set_confdir( luci.fs.dirname(file) )
228                 self.uci.load( luci.fs.basename(file) )
229
230                 table.insert( schemes, self.uci.get_all( luci.fs.basename(file) ) )
231         end
232
233         return self:_read_scheme_parts( scheme, schemes )
234 end
235
236 -- Process all given parts and construct validation tree
237 function UVL._read_scheme_parts( self, scheme, schemes )
238
239         -- helper function to construct identifiers for given elements
240         local function _id( c, t )
241                 if c == TYPE_SECTION then
242                         return string.format(
243                                 "section '%s.%s'",
244                                         scheme, t.name or '?' )
245                 elseif c == TYPE_VARIABLE then
246                         return string.format(
247                                 "variable '%s.%s.%s'",
248                                         scheme, t.section or '?.?', t.name or '?' )
249                 elseif c == TYPE_ENUM then
250                         return string.format(
251                                 "enum '%s.%s.%s'",
252                                         scheme, t.variable or '?.?.?', t.value or '?' )
253                 end
254         end
255
256         -- helper function to check for required fields
257         local function _req( c, t, r )
258                 for i, v in ipairs(r) do
259                         _assert( t[v], "Missing required field '%s' in %s", v, _id(c, t) )
260                 end
261         end
262
263         -- helper function to validate references
264         local function _ref( c, t )
265                 local k
266                 if c == TYPE_SECTION then
267                         k = "package"
268                 elseif c == TYPE_VARIABLE then
269                         k = "section"
270                 elseif c == TYPE_ENUM then
271                         k = "variable"
272                 end
273
274                 local r = luci.util.split( t[k], "." )
275                 r[1] = ( #r[1] > 0 and r[1] or scheme )
276
277                 _assert( #r == c, "Malformed %s reference in %s", k, _id(c, t) )
278
279                 return r
280         end
281
282         -- Step 1: get all sections
283         for i, conf in ipairs( schemes ) do
284                 for k, v in pairs( conf ) do
285                         if v['.type'] == 'section' then
286
287                                 _req( TYPE_SECTION, v, { "name", "package" } )
288
289                                 local r = _ref( TYPE_SECTION, v )
290
291                                 self.packages[r[1]] =
292                                         self.packages[r[1]] or {
293                                                 ["sections"]  = { };
294                                                 ["variables"] = { };
295                                         }
296
297                                 local p = self.packages[r[1]]
298                                           p.sections[v.name]  = p.sections[v.name]  or { }
299                                           p.variables[v.name] = p.variables[v.name] or { }
300
301                                 local s = p.sections[v.name]
302
303                                 for k, v2 in pairs(v) do
304                                         if k ~= "name" and k ~= "package" and k:sub(1,1) ~= "." then
305                                                 if k:match("^depends") then
306                                                         s["depends"] = _assert(
307                                                                 self:_read_dependency( v2, s["depends"] ),
308                                                                 "Section '%s' in scheme '%s' has malformed " ..
309                                                                 "dependency specification in '%s'",
310                                                                 v.name or '<nil>', scheme or '<nil>', k
311                                                         )
312                                                 else
313                                                         s[k] = v2
314                                                 end
315                                         end
316                                 end
317                         end
318                 end
319         end
320
321         -- Step 2: get all variables
322         for i, conf in ipairs( schemes ) do
323                 for k, v in pairs( conf ) do
324                         if v['.type'] == "variable" then
325
326                                 _req( TYPE_VARIABLE, v, { "name", "section" } )
327
328                                 local r = _ref( TYPE_VARIABLE, v )
329
330                                 local p = _assert( self.packages[r[1]],
331                                         "Variable '%s' in scheme '%s' references unknown package '%s'",
332                                         v.name, scheme, r[1] )
333
334                                 local s = _assert( p.variables[r[2]],
335                                         "Variable '%s' in scheme '%s' references unknown section '%s'",
336                                         v.name, scheme, r[2] )
337
338                                 s[v.name] = s[v.name] or { }
339
340                                 local t = s[v.name]
341
342                                 for k, v in pairs(v) do
343                                         if k ~= "name" and k ~= "section" and k:sub(1,1) ~= "." then
344                                                 if k:match("^depends") then
345                                                         t["depends"] = _assert(
346                                                                 self:_read_dependency( v, t["depends"] ),
347                                                                 "Variable '%s' in scheme '%s' has malformed " ..
348                                                                 "dependency specification in '%s'",
349                                                                 v.name, scheme, k
350                                                         )
351                                                 elseif k:match("^validator") then
352                                                         t["validators"] = _assert(
353                                                                 self:_read_validator( v, t["validators"] ),
354                                                                 "Variable '%s' in scheme '%s' has malformed " ..
355                                                                 "validator specification in '%s'",
356                                                                 v.name, scheme, k
357                                                         )
358                                                 else
359                                                         t[k] = v
360                                                 end
361                                         end
362                                 end
363                         end
364                 end
365         end
366
367         -- Step 3: get all enums
368         for i, conf in ipairs( schemes ) do
369                 for k, v in pairs( conf ) do
370                         if v['.type'] == "enum" then
371
372                                 _req( TYPE_ENUM, v, { "value", "variable" } )
373
374                                 local r = _ref( TYPE_ENUM, v )
375
376                                 local p = _assert( self.packages[r[1]],
377                                         "Enum '%s' in scheme '%s' references unknown package '%s'",
378                                         v.value, scheme, r[1] )
379
380                                 local s = _assert( p.variables[r[2]],
381                                         "Enum '%s' in scheme '%s' references unknown section '%s'",
382                                         v.value, scheme, r[2] )
383
384                                 local t = _assert( s[r[3]],
385                                         "Enum '%s' in scheme '%s', section '%s' references " ..
386                                         "unknown variable '%s'",
387                                         v.value, scheme, r[2], r[3] )
388
389                                 _assert( t.type == "enum",
390                                         "Enum '%s' in scheme '%s', section '%s' references " ..
391                                         "variable '%s' with non enum type '%s'",
392                                         v.value, scheme, r[2], r[3], t.type )
393
394                                 if not t.values then
395                                         t.values = { [v.value] = v.title or v.value }
396                                 else
397                                         t.values[v.value] = v.title or v.value
398                                 end
399
400                                 if v.default then
401                                         _assert( not t.default,
402                                                 "Enum '%s' in scheme '%s', section '%s' redeclares " ..
403                                                 "the default value of variable '%s'",
404                                                 v.value, scheme, r[2], v.variable )
405
406                                         t.default = v.value
407                                 end
408                         end
409                 end
410         end
411
412         return self
413 end
414
415 -- Read a dependency specification
416 function UVL._read_dependency( self, value, deps )
417         local parts     = luci.util.split( value, "%s*,%s*", nil, true )
418         local condition = { }
419
420         for i, val in ipairs(parts) do
421                 local k, v = unpack(luci.util.split( val, "%s*=%s*", nil, true ))
422
423                 if k and (
424                         k:match("^%$?[a-zA-Z0-9_]+%.%$?[a-zA-Z0-9_]+%.%$?[a-zA-Z0-9_]+$") or
425                         k:match("^%$?[a-zA-Z0-9_]+%.%$?[a-zA-Z0-9_]+$") or
426                         k:match("^%$?[a-zA-Z0-9_]+$")
427                 ) then
428                         condition[k] = v or true
429                 else
430                         return nil
431                 end
432         end
433
434         if not deps then
435                 deps = { condition }
436         else
437                 table.insert( deps, condition )
438         end
439
440         return deps
441 end
442
443 -- Read a validator specification
444 function UVL._read_validator( self, value, validators )
445         local validator
446
447         if value and value:match("/") and self.datatypes.file(value) then
448                 validator = value
449         else
450                 validator = self:_resolve_function( value )
451         end
452
453         if validator then
454                 if not validators then
455                         validators = { validator }
456                 else
457                         table.insert( validators, validator )
458                 end
459
460                 return validators
461         end
462 end
463
464 -- Resolve given path
465 function UVL._resolve_function( self, value )
466         local path = luci.util.split(value, ".")
467
468         for i=1, #path-1 do
469                 local stat, mod = pcall(require, table.concat(path, ".", 1, i))
470                 if stat and mod then
471                         for j=i+1, #path-1 do
472                                 if not type(mod) == "table" then
473                                         break
474                                 end
475                                 mod = mod[path[j]]
476                                 if not mod then
477                                         break
478                                 end
479                         end
480                         mod = type(mod) == "table" and mod[path[#path]] or nil
481                         if type(mod) == "function" then
482                                 return mod
483                         end
484                 end
485         end
486 end
487
488
489 section = luci.util.class()
490
491 function section.__init__(self, scheme, co, st, c, s)
492         self.csection = co[s]
493         self.ssection = scheme.packages[c].sections[st]
494         self.cref     = { c, s }
495         self.sref     = { c, st }
496         self.scheme   = scheme
497         self.config   = co
498         self.type     = luci.uvl.TYPE_SECTION
499 end
500
501 function section.cid(self)
502         return ( self.cref[1] or '?' ) .. '.' .. ( self.cref[2] or '?' )
503 end
504
505 function section.sid(self)
506         return ( self.sref[1] or '?' ) .. '.' .. ( self.sref[2] or '?' )
507 end
508
509 function section.values(self)
510         return self.csection
511 end
512
513 function section.section(self)
514         return self.ssection
515 end
516
517 function section.variables(self)
518         local v = { }
519         if self.scheme.packages[self.sref[1]].variables[self.sref[2]] then
520                 for o, _ in pairs(
521                         self.scheme.packages[self.sref[1]].variables[self.sref[2]]
522                 ) do
523                         table.insert( v, luci.uvl.option(
524                                 self.scheme, self.config, self.sref[2],
525                                 self.cref[1], self.cref[2], o
526                         ) )
527                 end
528         end
529         return v
530 end
531
532
533 option = luci.util.class()
534
535 function option.__init__(self, scheme, co, st, c, s, o)
536         self.coption = co[s] and co[s][o] or nil
537         self.soption = scheme.packages[c].variables[st][o]
538         self.cref    = { c, s, o }
539         self.sref    = { c, st, o }
540         self.scheme  = scheme
541         self.config  = co
542         self.type    = luci.uvl.TYPE_OPTION
543 end
544
545 function option.cid(self)
546         return ( self.cref[1] or '?' ) .. '.' ..
547                    ( self.cref[2] or '?' ) .. '.' ..
548                    ( self.cref[3] or '?' )
549 end
550
551 function option.sid(self)
552         return ( self.sref[1] or '?' ) .. '.' ..
553                    ( self.sref[2] or '?' ) .. '.' ..
554                    ( self.sref[3] or '?' )
555 end
556
557 function option.value(self)
558         return self.coption
559 end
560
561 function option.option(self)
562         return self.soption
563 end