b10365579a043e75108700405be4141212d19d3d
[project/luci.git] / libs / lucid / luasrc / lucid.lua
1 --[[
2 LuCI - Lua Development Framework
3
4 Copyright 2009 Steven Barth <steven@midlink.org>
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 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"
20
21 local pairs, require, pcall, assert, type = pairs, require, pcall, assert, type
22 local ipairs, tonumber, collectgarbage = ipairs, tonumber, collectgarbage
23
24
25 module "luci.lucid"
26
27 local slaves = {}
28 local pollt = {}
29 local tickt = {}
30 local tpids = {}
31 local tcount = 0
32 local ifaddrs = nixio.getifaddrs()
33
34 cursor = uci.cursor()
35 state = uci.cursor_state()
36 UCINAME = "lucid"
37
38 local cursor = cursor
39 local state = state
40 local UCINAME = UCINAME
41 local SSTATE = "/tmp/.lucid_store"
42
43
44 --- Starts a new LuCId superprocess.
45 function start()
46 prepare()
47
48 local detach = cursor:get(UCINAME, "main", "daemonize")
49 if detach == "1" then
50 local stat, code, msg = daemonize()
51 if not stat then
52 nixio.syslog("crit", "Unable to detach process: " .. msg .. "\n")
53 ox.exit(2)
54 end
55 end
56
57 state:set(UCINAME, "main", "pid", nixio.getpid())
58 state:save(UCINAME)
59
60 run()
61 end
62
63 --- Stops any running LuCId superprocess.
64 function stop()
65 local pid = tonumber(state:get(UCINAME, "main", "pid"))
66 if pid then
67 return nixio.kill(pid, nixio.const.SIGTERM)
68 end
69 return false
70 end
71
72 --- Prepares the slaves, daemons and publishers, allocate resources.
73 function prepare()
74 local debug = tonumber((cursor:get(UCINAME, "main", "debug")))
75
76 nixio.openlog("lucid", "pid", "perror")
77 if debug ~= 1 then
78 nixio.setlogmask("warning")
79 end
80
81 cursor:foreach(UCINAME, "daemon", function(config)
82 if config.enabled ~= "1" then
83 return
84 end
85
86 local key = config[".name"]
87 if not config.slave then
88 nixio.syslog("crit", "Daemon "..key.." is missing a slave\n")
89 os.exit(1)
90 else
91 nixio.syslog("info", "Initializing daemon " .. key)
92 end
93
94 state:revert(UCINAME, key)
95
96 local daemon, code, err = prepare_daemon(config)
97 if daemon then
98 state:set(UCINAME, key, "status", "started")
99 nixio.syslog("info", "Prepared daemon " .. key)
100 else
101 state:set(UCINAME, key, "status", "error")
102 state:set(UCINAME, key, "error", err)
103 nixio.syslog("err", "Failed to initialize daemon "..key..": "..
104 err .. "\n")
105 end
106 end)
107 end
108
109 --- Run the superprocess if prepared before.
110 -- This main function of LuCId will wait for events on given file descriptors.
111 function run()
112 local pollint = tonumber((cursor:get(UCINAME, "main", "pollinterval")))
113
114 while true do
115 local stat, code = nixio.poll(pollt, pollint)
116
117 if stat and stat > 0 then
118 for _, polle in ipairs(pollt) do
119 if polle.revents ~= 0 and polle.handler then
120 polle.handler(polle)
121 end
122 end
123 elseif stat == 0 then
124 ifaddrs = nixio.getifaddrs()
125 collectgarbage("collect")
126 end
127
128 for _, cb in ipairs(tickt) do
129 cb()
130 end
131
132 local pid, stat, code = nixio.wait(-1, "nohang")
133 while pid and pid > 0 do
134 tcount = tcount - 1
135 if tpids[pid] and tpids[pid] ~= true then
136 tpids[pid](pid, stat, code)
137 end
138 pid, stat, code = nixio.wait(-1, "nohang")
139 end
140 end
141 end
142
143 --- Add a file descriptor for the main loop and associate handler functions.
144 -- @param polle Table containing: {fd = FILE DESCRIPTOR, events = POLL EVENTS,
145 -- handler = EVENT HANDLER CALLBACK}
146 -- @see unregister_pollfd
147 -- @return boolean status
148 function register_pollfd(polle)
149 pollt[#pollt+1] = polle
150 return true
151 end
152
153 --- Unregister a file desciptor and associate handler from the main loop.
154 -- @param polle Poll descriptor
155 -- @see register_pollfd
156 -- @return boolean status
157 function unregister_pollfd(polle)
158 for k, v in ipairs(pollt) do
159 if v == polle then
160 table.remove(pollt, k)
161 return true
162 end
163 end
164 return false
165 end
166
167 --- Close all registered file descriptors from main loop.
168 -- This is useful for forked child processes.
169 function close_pollfds()
170 for k, v in ipairs(pollt) do
171 if v.fd and v.fd.close then
172 v.fd:close()
173 end
174 end
175 end
176
177 --- Register a tick function that will be called at each cycle of the main loop.
178 -- @param cb Callback
179 -- @see unregister_tick
180 -- @return boolean status
181 function register_tick(cb)
182 tickt[#tickt+1] = cb
183 return true
184 end
185
186 --- Unregister a tick function from the main loop.
187 -- @param cb Callback
188 -- @see register_tick
189 -- @return boolean status
190 function unregister_tick(cb)
191 for k, v in ipairs(tickt) do
192 if v == cb then
193 table.remove(tickt, k)
194 return true
195 end
196 end
197 return false
198 end
199
200 --- Create a new child process from a Lua function and assign a destructor.
201 -- @param threadcb main function of the new process
202 -- @param waitcb destructor callback
203 -- @return process identifier or nil, error code, error message
204 function create_process(threadcb, waitcb)
205 local threadlimit = tonumber(cursor:get(UCINAME, "main", "threadlimit"))
206 if threadlimit and tcount >= threadlimit then
207 nixio.syslog("warning", "Cannot create thread: process limit reached")
208 return nil
209 end
210 local pid, code, err = nixio.fork()
211 if pid and pid ~= 0 then
212 tpids[pid] = waitcb
213 tcount = tcount + 1
214 elseif pid == 0 then
215 local code = threadcb()
216 os.exit(code)
217 else
218 nixio.syslog("err", "Unable to fork(): " .. err)
219 end
220 return pid, code, err
221 end
222
223 --- Prepare a daemon from a given configuration table.
224 -- @param config Configuration data.
225 -- @return boolean status or nil, error code, error message
226 function prepare_daemon(config)
227 nixio.syslog("info", "Preparing daemon " .. config[".name"])
228 local modname = cursor:get(UCINAME, config.slave)
229 if not modname then
230 return nil, -1, "invalid slave"
231 end
232
233 local stat, module = pcall(require, _NAME .. "." .. modname)
234 if not stat or not module.prepare_daemon then
235 return nil, -2, "slave type not supported"
236 end
237
238 config.slave = prepare_slave(config.slave)
239
240 return module.prepare_daemon(config, _M)
241 end
242
243 --- Prepare a slave.
244 -- @param name slave name
245 -- @return table containing slave module and configuration or nil, error message
246 function prepare_slave(name)
247 local slave = slaves[name]
248 if not slave then
249 local config = cursor:get_all(UCINAME, name)
250
251 local stat, module = pcall(require, config and config.entrypoint)
252 if stat then
253 slave = {module = module, config = config}
254 end
255 end
256
257 if slave then
258 return slave
259 else
260 return nil, module
261 end
262 end
263
264 --- Return a list of available network interfaces on the host.
265 -- @return table returned by nixio.getifaddrs()
266 function get_interfaces()
267 return ifaddrs
268 end
269
270 --- Revoke process privileges.
271 -- @param user new user name or uid
272 -- @param group new group name or gid
273 -- @return boolean status or nil, error code, error message
274 function revoke_privileges(user, group)
275 if nixio.getuid() == 0 then
276 return nixio.setgid(group) and nixio.setuid(user)
277 end
278 end
279
280 --- Return a secure UCI cursor.
281 -- @return UCI cursor
282 function securestate()
283 local stat = nixio.fs.stat(SSTATE) or {}
284 local uid = nixio.getuid()
285 if stat.type ~= "dir" or (stat.modedec % 100) ~= 0 or stat.uid ~= uid then
286 nixio.fs.remover(SSTATE)
287 if not nixio.fs.mkdir(SSTATE, 700) then
288 local errno = nixio.errno()
289 nixio.syslog("err", "Integrity check on secure state failed!")
290 return nil, errno, nixio.perror(errno)
291 end
292 end
293
294 return uci.cursor(nil, SSTATE)
295 end
296
297 --- Daemonize the process.
298 -- @return boolean status or nil, error code, error message
299 function daemonize()
300 if nixio.getppid() == 1 then
301 return
302 end
303
304 local pid, code, msg = nixio.fork()
305 if not pid then
306 return nil, code, msg
307 elseif pid > 0 then
308 os.exit(0)
309 end
310
311 nixio.setsid()
312 nixio.chdir("/")
313
314 local devnull = nixio.open("/dev/null", nixio.open_flags("rdwr"))
315 nixio.dup(devnull, nixio.stdin)
316 nixio.dup(devnull, nixio.stdout)
317 nixio.dup(devnull, nixio.stderr)
318
319 return true
320 end