Daemon
The server is in the daemon directory, it works out of the box without any configuration.
$ kresd -v # run with defaults in verbose mode
$ kresd -h # Get help
If you're using our packages, they also provide systemd integration. To start the resolver under systemd, you can use the kresd@1.service
service. By default, the resolver only binds to local interfaces.
$ man kresd.systemd # Help for systemd integration configuration
$ systemctl start kresd@1.service
Configuration
In its simplest form the server requires just a working directory in which it can set up persistent files like cache and the process state. If you don't provide the working directory by parameter, it is going to make itself comfortable in the current working directory.
$ kresd /var/cache/knot-resolver
And you're good to go for most use cases! If you want to use modules or configure daemon behavior, read on.
There are several choices on how you can configure the daemon, a RPC interface, a CLI, and a configuration file. Fortunately all share common syntax and are transparent to each other.
Configuration example
-- interfaces
net = { '127.0.0.1', '::1' }
-- load some modules
modules = { 'policy' }
-- 10MB cache
cache.size = 10*MB
Tip
There are more configuration examples in etc/ directory for personal, ISP, company internal and resolver cluster use cases.
Configuration syntax
The configuration is kept in the config
file in the daemon working directory, and it's going to get loaded automatically.
If there isn't one, the daemon is going to start with sane defaults, listening on localhost.
The syntax for options is like follows: group.option = value
or group.action(parameters)
.
You can also comment using a --
prefix.
A simple example would be to load static hints.
modules = {
'hints' -- no configuration
}
If the module accepts configuration, you can call the module.config({...})
or provide options table.
The syntax for table is { key1 = value, key2 = value }
, and it represents the unpacked JSON-encoded string, that
the modules use as the :ref:`input configuration <mod-properties>`.
modules = {
hints = '/etc/hosts'
}
Warning
Modules specified including their configuration may not load exactly in the same order as specified.
Modules are inherently ordered by their declaration. Some modules are built-in, so it would be normally impossible to place for example hints before cache. You can enforce specific order by precedence operators > and <.
modules = {
'hints > iterate', -- Hints AFTER iterate
'policy > hints', -- Policy AFTER hints
'view < cache' -- View BEFORE cache
}
modules.list() -- Check module call order
This is useful if you're writing a module with a layer, that evaluates an answer before writing it into cache for example.
Tip
The configuration and CLI syntax is Lua language, with which you may already be familiar with. If not, you can read the Learn Lua in 15 minutes for a syntax overview. Spending just a few minutes will allow you to break from static configuration, write more efficient configuration with iteration, and leverage events and hooks. Lua is heavily used for scripting in applications ranging from embedded to game engines, but in DNS world notably in PowerDNS Recursor. Knot Resolver does not simply use Lua modules, but it is the heart of the daemon for everything from configuration, internal events and user interaction.
Dynamic configuration
Knowing that the the configuration is a Lua in disguise enables you to write dynamic rules. It also helps you to avoid repetitive templating that is unavoidable with static configuration.
if hostname() == 'hidden' then
net.listen(net.eth0, 5353)
else
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.
for name, addr_list in pairs(net.interfaces()) do
net.listen(addr_list)
end
Tip
Some users observed a considerable, close to 100%, performance gain in Docker containers when they bound the daemon to a single interface:ip address pair. One may expand the aforementioned example with browsing available addresses as:
addrpref = env.EXPECTED_ADDR_PREFIX
for k, v in pairs(addr_list["addr"]) do
if string.sub(v,1,string.len(addrpref)) == addrpref then
net.listen(v)
...
You can also use third-party packages (available for example through LuaRocks) as on this example to download cache from parent, to avoid cold-cache start.
local http = require('socket.http')
local ltn12 = require('ltn12')
local cache_size = 100*MB
local cache_path = '/var/cache/knot-resolver'
cache.open(cache_size, 'lmdb://' .. cache_path)
if cache.count() == 0 then
cache.close()
-- download cache from parent
http.request {
url = 'http://parent/data.mdb',
sink = ltn12.sink.file(io.open(cache_path .. '/data.mdb', 'w'))
}
-- reopen cache with 100M limit
cache.open(cache_size, 'lmdb://' .. cache_path)
end
Asynchronous events
Lua supports a concept called closures, this is extremely useful for scripting actions upon various events, say for example - publish statistics each minute and so on. Here's an example of an anonymous function with :func:`event.recurrent()`.
Note that each scheduled event is identified by a number valid for the duration of the event, you may use it to cancel the event at any time.
modules.load('stats')
-- log statistics every second
local stat_id = event.recurrent(1 * second, function(evid)
log(table_print(stats.list()))
end)
-- stop printing statistics after first minute
event.after(1 * minute, function(evid)
event.cancel(stat_id)
end)
If you need to persist state between events, encapsulate even handle in closure function which will provide persistent variable (called previous
):
modules.load('stats')
-- make a closure, encapsulating counter
function speed_monitor()
local previous = stats.list()
-- monitoring function
return function(evid)
local now = stats.list()
local total_increment = now['answer.total'] - previous['answer.total']
local slow_increment = now['answer.slow'] - previous['answer.slow']
if slow_increment / total_increment > 0.05 then
log('WARNING! More than 5 %% of queries was slow!')
end
previous = now -- store current value in closure
end
end
-- monitor every minute
local monitor_id = event.recurrent(1 * minute, speed_monitor())
Another type of actionable event is activity on a file descriptor. This allows you to embed other event loops or monitor open files and then fire a callback when an activity is detected. This allows you to build persistent services like HTTP servers or monitoring probes that cooperate well with the daemon internal operations. See :func:`event.socket()`
File watchers are possible with :func:`worker.coroutine()` and cqueues, see the cqueues documentation for more information.
local notify = require('cqueues.notify')
local watcher = notify.opendir('/etc')
watcher:add('hosts')
-- Watch changes to /etc/hosts
worker.coroutine(function ()
for flags, name in watcher:changes() do
for flag in notify.flags(flags) do
print(name, notify[flag])
end
end
end)
Configuration reference
This is a reference for variables and functions available to both configuration file and CLI.
Environment
Trust anchors and DNSSEC
Since version 4.0, DNSSEC validation is enabled by default. This is secure default and should not be changed unless absolutely necessary.
Options in this section are intended only for expert users and normally should not be needed.
If you really need to turn DNSSEC off and are okay with lowering security of your system by doing so, add the following snippet to your configuration file.
-- turns off DNSSEC validation
trust_anchors.remove('.')
The resolver supports DNSSEC including RFC 5011 automated DNSSEC TA updates and RFC 7646 negative trust anchors. Depending on your distribution, DNSSEC trust anchors should be either maintained in accordance with the distro-wide policy, or automatically maintained by the resolver itself.
In practice this means that you can forget about it and your favorite Linux distribution will take care of it for you.
CLI interface
The daemon features a CLI interface, type help()
to see the list of available commands.
$ kresd /var/cache/knot-resolver
[system] started in interactive mode, type 'help()'
> cache.count()
53
Verbose output
If the verbose logging is compiled in, i.e. not turned off by
verbose_log=disabled
, you can turn on verbose tracing of server operation
with the -v
option. You can also toggle it on runtime with
verbose(true|false)
command.
$ kresd -v
To run the daemon by hand, such as under nohup
, use -f 1
to start a single fork. For example:
$ nohup ./daemon/kresd -a 127.0.0.1 -f 1 -v &
Control sockets
Unless ran manually, knot-resolver is typically started in non-interactive mode.
The mode gets triggered by using the -f
command-line parameter or by passing sockets from systemd.
You can attach to the the consoles for each process; by default they are in rundir/tty/$PID
.
Note
When running kresd with systemd, you can find the location of the socket(s) using systemctl status kresd-control@*.socket
. Typically, these are in /run/knot-resolver/control@*
.
$ nc -U rundir/tty/3008 # or socat - UNIX-CONNECT:rundir/tty/3008
> cache.count()
53
The direct output of the CLI command is captured and sent over the socket, while also printed to the daemon standard outputs (for accountability). This gives you an immediate response on the outcome of your command. Error or debug logs aren't captured, but you can find them in the daemon standard outputs.
This is also a way to enumerate and test running instances, the list of files in tty
corresponds to the list
of running processes, and you can test the process for liveliness by connecting to the UNIX socket.
Utilizing multiple CPUs
The server can run in multiple independent processes, all sharing the same socket and cache. These processes can be started or stopped during runtime based on the load.
Using systemd
To run multiple daemons using systemd, use a different numeric identifier for the instance, for example:
$ systemctl start kresd@1.service
$ systemctl start kresd@2.service
$ systemctl start kresd@3.service
$ systemctl start kresd@4.service
With the use of brace expansion, the equivalent command looks like:
$ systemctl start kresd@{1..4}.service
For more details, see kresd.systemd(7)
.
Daemon only
$ kresd -f 4 rundir > kresd.log &
$ kresd -f 2 rundir > kresd_2.log & # Extra instances
$ pstree $$ -g
bash(3533)─┬─kresd(19212)─┬─kresd(19212)
│ ├─kresd(19212)
│ └─kresd(19212)
├─kresd(19399)───kresd(19399)
└─pstree(19411)
$ kill 19399 # Kill group 2, former will continue to run
bash(3533)─┬─kresd(19212)─┬─kresd(19212)
│ ├─kresd(19212)
│ └─kresd(19212)
└─pstree(19460)
Note
On recent Linux supporting SO_REUSEPORT
(since 3.9, backported to RHEL 2.6.32) it is also able to bind to the same endpoint and distribute the load between the forked processes. If your OS doesn't support it, use only one daemon process.
Cache Garbage Collector
Warning
Garbage collector is experimental and subject to change in future releases. This feature isn't currently turned on by default.
By default, kresd uses the available cache until it's full. When more space is required, the entire cache is dropped. To avoid starting over with an empty cache, a separate garbage collector daemon is available to periodically trim the cache instead.
The cache garbage collector daemon (kres_cache_gc
) monitors the cache usage
and attempts to free up space when a threshold is reached. To spawn the daemon
and configure it to run every minute, use:
$ kres_cache_gc -c /var/cache/knot-resolver -d 10000
It's also possible to run this under systemd. However, a dedicated systemd unit is not currently part of the upstream package. See message#167 on our mailing list for an example of such a unit file.
Using CLI tools
-
kresd-host.lua
- a drop-in replacement for host(1) utility
Queries the DNS for information. The hostname is looked up for IP4, IP6 and mail.
Example:
$ kresd-host.lua -f root.key -v nic.cz
nic.cz. has address 217.31.205.50 (secure)
nic.cz. has IPv6 address 2001:1488:0:3::2 (secure)
nic.cz. mail is handled by 10 mail.nic.cz. (secure)
nic.cz. mail is handled by 20 mx.nic.cz. (secure)
nic.cz. mail is handled by 30 bh.nic.cz. (secure)
-
kresd-query.lua
- run the daemon in zero-configuration mode, perform a query and execute given callback.
This is useful for executing one-shot queries and hooking into the processing of the result, for example to check if a domain is managed by a certain registrar or if it's signed.
Example:
$ kresd-query.lua www.sub.nic.cz 'assert(kres.dname2str(req:resolved().zone_cut.name) == "nic.cz.")' && echo "yes"
yes
$ kresd-query.lua -C 'trust_anchors.add_file("root.keys")' nic.cz 'assert(req:resolved().flags.DNSSEC_WANT)'
$ echo $?
0