From: Marek Vavruša Date: Thu, 7 May 2015 19:41:16 +0000 (+0200) Subject: daemon/lua: syntactic sugar for ‘net’ X-Git-Tag: v1.0.0-beta1~201 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4b4bf01aa74ba873e73ed176051e4df34cac9a33;p=thirdparty%2Fknot-resolver.git daemon/lua: syntactic sugar for ‘net’ this allows list-like declaration of bound interfaces e.g. net = { ‘127.0.0.1’, net.eth0 } --- diff --git a/daemon/README.rst b/daemon/README.rst index 9fa69ce6d..16362a98a 100644 --- a/daemon/README.rst +++ b/daemon/README.rst @@ -112,16 +112,16 @@ The possible simple data types are strings, integers or floats and boolean. Dynamic configuration ^^^^^^^^^^^^^^^^^^^^^ -Knowing that the the configuration is a valid Lua script enables you to write dynamic rules, and also avoid -additional configuration templating. One example is to differentiate between internal and external -interfaces based on environment variable. +Knowing that the the configuration is a Lua in disguise enables you to write dynamic rules, and also avoid +repetition and templating. This is unavoidable with static configuration, e.g. when you want to configure +each node a little bit differently. .. code-block:: lua if hostname() == 'hidden' then - net.listen(net.eth0) + net.listen(net.eth0, 5353) else - net.listen(net.eth1.addr[1]) + net = { '127.0.0.1', net.eth1.addr[1] } end Another example would show how it is possible to bind to all interfaces, using iteration. @@ -221,6 +221,14 @@ Environment Network configuration ^^^^^^^^^^^^^^^^^^^^^ +For when listening on ``localhost`` just doesn't cut it. + +.. tip:: Use declarative interface for network. + + .. code-block:: lua + + net = { '127.0.0.1', net.eth0, net.eth1.addr[1] } + .. function:: net.listen(address, [port = 53]) :return: boolean diff --git a/daemon/lua/sandbox.lua b/daemon/lua/sandbox.lua index 6c4d13d4f..2dd2e417c 100644 --- a/daemon/lua/sandbox.lua +++ b/daemon/lua/sandbox.lua @@ -16,12 +16,19 @@ setmetatable(env, { -- Quick access to interfaces -- `net.` => `net.interfaces()[iface]` +-- `net = {addr1, ..}` => `net.listen(name, addr1)` setmetatable(net, { __index = function (t, k) local v = rawget(t, k) if v then return v else return net.interfaces()[k] end + end, + __newindex = function (t,k,v) + local iname = rawget(net.interfaces(), v) + if iname then t.listen(iname) + else t.listen(v) + end end }) @@ -29,10 +36,11 @@ setmetatable(net, { -- `modules. = ` setmetatable(modules, { __newindex = function (t,k,v) + if type(k) == 'number' then k = v end if not rawget(_G, k) then modules.load(k) local mod = rawget(_G, k) - if mod and mod['config'] then + if k ~= v and mod and mod['config'] then mod['config'](v) end