2 LuCI - Lua Development Framework
4 Copyright 2009 Steven Barth <steven@midlink.org>
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
10 http://www.apache.org/licenses/LICENSE-2.0
15 local nixio = require "nixio"
16 local table = require "table"
17 local uci = require "luci.model.uci"
18 local os = require "os"
19 local io = require "io"
21 local pairs, require, pcall, assert, type = pairs, require, pcall, assert, type
22 local ipairs, tonumber, collectgarbage = ipairs, tonumber, collectgarbage
32 local ifaddrs = nixio.getifaddrs()
35 state = uci.cursor_state()
40 local UCINAME = UCINAME
41 local SSTATE = "/tmp/.lucid_store"
44 --- Starts a new LuCId superprocess.
46 state:revert(UCINAME, "main")
50 local detach = cursor:get(UCINAME, "main", "daemonize")
52 local stat, code, msg = daemonize()
54 nixio.syslog("crit", "Unable to detach process: " .. msg .. "\n")
59 state:set(UCINAME, "main", "pid", nixio.getpid())
65 --- Returns the PID of the currently active LuCId process.
67 local pid = tonumber(state:get(UCINAME, "main", "pid"))
68 return pid and nixio.kill(pid, 0) and pid
71 --- Stops any running LuCId superprocess.
73 local pid = tonumber(state:get(UCINAME, "main", "pid"))
75 return nixio.kill(pid, nixio.const.SIGTERM)
80 --- Prepares the slaves, daemons and publishers, allocate resources.
82 local debug = tonumber((cursor:get(UCINAME, "main", "debug")))
84 nixio.openlog("lucid", "pid", "perror")
86 nixio.setlogmask("warning")
89 cursor:foreach(UCINAME, "daemon", function(config)
90 if config.enabled ~= "1" then
94 local key = config[".name"]
95 if not config.slave then
96 nixio.syslog("crit", "Daemon "..key.." is missing a slave\n")
99 nixio.syslog("info", "Initializing daemon " .. key)
102 state:revert(UCINAME, key)
104 local daemon, code, err = prepare_daemon(config)
106 state:set(UCINAME, key, "status", "started")
107 nixio.syslog("info", "Prepared daemon " .. key)
109 state:set(UCINAME, key, "status", "error")
110 state:set(UCINAME, key, "error", err)
111 nixio.syslog("err", "Failed to initialize daemon "..key..": "..
117 --- Run the superprocess if prepared before.
118 -- This main function of LuCId will wait for events on given file descriptors.
120 local pollint = tonumber((cursor:get(UCINAME, "main", "pollinterval")))
121 local threadlimit = tonumber((cursor:get(UCINAME, "main", "threadlimit")))
124 local stat, code = nixio.poll(pollt, pollint)
126 if stat and stat > 0 then
128 for _, polle in ipairs(pollt) do
129 if polle.revents ~= 0 and polle.handler then
130 ok = ok or polle.handler(polle)
134 -- Avoid high CPU usage if thread limit is reached
135 nixio.nanosleep(0, 100000000)
137 elseif stat == 0 then
138 ifaddrs = nixio.getifaddrs()
141 for _, cb in ipairs(tickt) do
145 local pid, stat, code = nixio.wait(-1, "nohang")
146 while pid and pid > 0 do
147 nixio.syslog("info", "Buried thread: " .. pid)
150 if tpids[pid] ~= true then
151 tpids[pid](pid, stat, code)
155 pid, stat, code = nixio.wait(-1, "nohang")
160 --- Add a file descriptor for the main loop and associate handler functions.
161 -- @param polle Table containing: {fd = FILE DESCRIPTOR, events = POLL EVENTS,
162 -- handler = EVENT HANDLER CALLBACK}
163 -- @see unregister_pollfd
164 -- @return boolean status
165 function register_pollfd(polle)
166 pollt[#pollt+1] = polle
170 --- Unregister a file desciptor and associate handler from the main loop.
171 -- @param polle Poll descriptor
172 -- @see register_pollfd
173 -- @return boolean status
174 function unregister_pollfd(polle)
175 for k, v in ipairs(pollt) do
177 table.remove(pollt, k)
184 --- Close all registered file descriptors from main loop.
185 -- This is useful for forked child processes.
186 function close_pollfds()
187 for k, v in ipairs(pollt) do
188 if v.fd and v.fd.close then
194 --- Register a tick function that will be called at each cycle of the main loop.
195 -- @param cb Callback
196 -- @see unregister_tick
197 -- @return boolean status
198 function register_tick(cb)
203 --- Unregister a tick function from the main loop.
204 -- @param cb Callback
205 -- @see register_tick
206 -- @return boolean status
207 function unregister_tick(cb)
208 for k, v in ipairs(tickt) do
210 table.remove(tickt, k)
217 --- Tests whether a given number of processes can be created.
218 -- @oaram num Processes to be created
219 -- @return boolean status
220 function try_process(num)
221 local threadlimit = tonumber((cursor:get(UCINAME, "main", "threadlimit")))
222 return not threadlimit or (threadlimit - tcount) >= (num or 1)
225 --- Create a new child process from a Lua function and assign a destructor.
226 -- @param threadcb main function of the new process
227 -- @param waitcb destructor callback
228 -- @return process identifier or nil, error code, error message
229 function create_process(threadcb, waitcb)
230 local threadlimit = tonumber(cursor:get(UCINAME, "main", "threadlimit"))
231 if threadlimit and tcount >= threadlimit then
232 nixio.syslog("warning", "Cannot create thread: process limit reached")
235 collectgarbage("collect")
237 local pid, code, err = nixio.fork()
238 if pid and pid ~= 0 then
239 nixio.syslog("info", "Created thread: " .. pid)
240 tpids[pid] = waitcb or true
243 local code = threadcb()
246 nixio.syslog("err", "Unable to fork(): " .. err)
248 return pid, code, err
251 --- Prepare a daemon from a given configuration table.
252 -- @param config Configuration data.
253 -- @return boolean status or nil, error code, error message
254 function prepare_daemon(config)
255 nixio.syslog("info", "Preparing daemon " .. config[".name"])
256 local modname = cursor:get(UCINAME, config.slave)
258 return nil, -1, "invalid slave"
261 local stat, module = pcall(require, _NAME .. "." .. modname)
262 if not stat or not module.prepare_daemon then
263 return nil, -2, "slave type not supported"
266 config.slave = prepare_slave(config.slave)
268 return module.prepare_daemon(config, _M)
272 -- @param name slave name
273 -- @return table containing slave module and configuration or nil, error message
274 function prepare_slave(name)
275 local slave = slaves[name]
277 local config = cursor:get_all(UCINAME, name)
279 local stat, module = pcall(require, config and config.entrypoint)
281 slave = {module = module, config = config}
292 --- Return a list of available network interfaces on the host.
293 -- @return table returned by nixio.getifaddrs()
294 function get_interfaces()
298 --- Revoke process privileges.
299 -- @param user new user name or uid
300 -- @param group new group name or gid
301 -- @return boolean status or nil, error code, error message
302 function revoke_privileges(user, group)
303 if nixio.getuid() == 0 then
304 return nixio.setgid(group) and nixio.setuid(user)
308 --- Return a secure UCI cursor.
309 -- @return UCI cursor
310 function securestate()
311 local stat = nixio.fs.stat(SSTATE) or {}
312 local uid = nixio.getuid()
313 if stat.type ~= "dir" or (stat.modedec % 100) ~= 0 or stat.uid ~= uid then
314 nixio.fs.remover(SSTATE)
315 if not nixio.fs.mkdir(SSTATE, 700) then
316 local errno = nixio.errno()
317 nixio.syslog("err", "Integrity check on secure state failed!")
318 return nil, errno, nixio.perror(errno)
322 return uci.cursor(nil, SSTATE)
325 --- Daemonize the process.
326 -- @return boolean status or nil, error code, error message
328 if nixio.getppid() == 1 then
332 local pid, code, msg = nixio.fork()
334 return nil, code, msg
342 local devnull = nixio.open("/dev/null", nixio.open_flags("rdwr"))
343 nixio.dup(devnull, nixio.stdin)
344 nixio.dup(devnull, nixio.stdout)
345 nixio.dup(devnull, nixio.stderr)