webmcp

view framework/bin/mcp.lua @ 208:2c2bcde0df79

Pre/postfork initializers and finalizers via coroutines
author jbe
date Sat Jan 10 00:11:52 2015 +0100 (2015-01-10)
parents 77c4774e8342
children 2cb27106aa73
line source
1 #!/usr/bin/env moonbridge
3 WEBMCP_VERSION = "2.0.0_devel"
5 -- check if interactive mode
6 if listen then -- defined by moonbridge
7 WEBMCP_MODE = "listen"
8 else
9 WEBMCP_MODE = "interactive"
10 end
12 -- configuration names are provided as 4th, 5th, etc. argument
13 WEBMCP_CONFIG_NAMES = {select(4, ...)}
15 -- determine framework and bath path from command line arguments
16 -- or print usage synopsis (if applicable)
17 do
18 local arg1, arg2, arg3 = ...
19 local helpout
20 if
21 arg1 == "-h" or arg1 == "--help" or
22 arg2 == "-h" or arg2 == "--help" -- if first arg is provided by wrapper
23 then
24 helpout = io.stdout
25 elseif
26 #config_args < 1 or
27 (WEBMCP_MODE == "interactive") ~= (arg3 == "INTERACTIVE")
28 then
29 helpout = io.stderr
30 end
31 helpout:write("Usage: moonbridge -- <framework path>/bin/mcp.lua <framework path> <app base path> <app name> <config name> [<config name> ...]\n")
32 helpout:write(" or: lua -i <framework path>/bin/mcp.lua <framework path> <app base path> INTERACTIVE <config name> [<config name> ...]\n")
33 if helpout then
34 if helpout == io.stderr then
35 return 1
36 else
37 return 0
38 end
39 end
40 local function append_trailing_slash(str)
41 return string.sub(str, "([^/])$", function(last) return last .. "/" end)
42 end
43 WEBMCP_FRAMEWORK_PATH = append_trailing_slash(arg1)
44 WEBMCP_BASE_PATH = append_trailing_slash(arg2)
45 if WEBMCP_MODE == "listen" then
46 WEBMCP_APP_NAME = arg3
47 end
48 end
50 -- setup search paths for libraries
51 do
52 package.path = WEBMCP_FRAMEWORK_PATH .. "lib/?.lua;" .. package.path
53 -- find out which file name extension shared libraries have
54 local slib_exts = {}
55 for ext in string.gmatch(package.cpath, "%?%.([A-Za-z0-9_-]+)") do
56 slib_exts[ext] = true
57 end
58 local paths = {}
59 for ext in pairs(slib_exts) do
60 paths[#paths+1] = WEBMCP_FRAMEWORK_PATH .. "accelerator/?." .. ext
61 end
62 for ext in pairs(slib_exts) do
63 paths[#paths+1] = WEBMCP_FRAMEWORK_PATH .. "lib/?." .. ext
64 end
65 paths[#paths+1] = package.cpath
66 package.cpath = table.concat(paths, ";")
67 end
69 -- autoloader system for WebMCP environment "$WEBMCP_FRAMEWORK_PATH/env/",
70 -- application environment extensions "$WEBMCP_BASE_PATH/env/"
71 -- and models "$WEBMCP_BASE_PATH/model/"
72 do
73 local weakkey_mt = { __mode = "k" }
74 local autoloader_category = setmetatable({}, weakkey_mt)
75 local autoloader_path = setmetatable({}, weakkey_mt)
76 local autoloader_mt = {}
77 local function install_autoloader(self, category, path)
78 autoloader_category[self] = category
79 autoloader_path[self] = path
80 setmetatable(self, autoloader_mt)
81 end
82 local function try_exec(filename)
83 local file = io.open(filename, "r")
84 if file then
85 local filedata = file:read("*a")
86 io.close(file)
87 local func, errmsg = load(filedata, "=" .. filename)
88 if func then
89 func()
90 return true
91 else
92 error(errmsg, 0)
93 end
94 else
95 return false
96 end
97 end
98 local function compose_path_string(base, path, key)
99 if #path == 0 then
100 return base .. "/" .. key
101 else
102 return base .. table.concat(path, "/") .. "/" .. key
103 end
104 end
105 function autoloader_mt.__index(self, key)
106 local category, base_path, merge_base_path, file_key
107 local merge = false
108 if
109 string.find(key, "^[a-z_][A-Za-z0-9_]*$") and
110 not string.find(key, "^__")
111 then
112 category = "env"
113 base_path = WEBMCP_FRAMEWORK_PATH .. "env/"
114 merge = true
115 merge_base_path = WEBMCP_BASE_PATH .. "env/"
116 file_key = key
117 elseif string.find(key, "^[A-Z][A-Za-z0-9]*$") then
118 category = "model"
119 base_path = WEBMCP_BASE_PATH .. "model/"
120 local first = true
121 file_key = string.gsub(key, "[A-Z]",
122 function(c)
123 if first then
124 first = false
125 return string.lower(c)
126 else
127 return "_" .. string.lower(c)
128 end
129 end
130 )
131 else
132 return
133 end
134 local required_category = autoloader_category[self]
135 if required_category and required_category ~= category then return end
136 local path = autoloader_path[self]
137 local path_string = compose_path_string(base_path, path, file_key)
138 local merge_path_string
139 if merge then
140 merge_path_string = compose_path_string(
141 merge_base_path, path, file_key
142 )
143 end
144 local function try_dir(dirname)
145 local dir = io.open(dirname)
146 if dir then
147 io.close(dir)
148 local obj = {}
149 local sub_path = {}
150 for i = 1, #path do sub_path[i] = path[i] end
151 sub_path[#path+1] = file_key
152 install_autoloader(obj, category, sub_path)
153 rawset(self, key, obj)
154 try_exec(path_string .. "/__init.lua")
155 if merge then try_exec(merge_path_string .. "/__init.lua") end
156 return true
157 else
158 return false
159 end
160 end
161 if merge and try_exec(merge_path_string .. ".lua") then
162 elseif merge and try_dir(merge_path_string .. "/") then
163 elseif try_exec(path_string .. ".lua") then
164 elseif try_dir(path_string .. "/") then
165 else end
166 return rawget(self, key)
167 end
168 install_autoloader(_G, nil, {})
169 try_exec(WEBMCP_FRAMEWORK_PATH .. "env/__init.lua")
170 try_exec(WEBMCP_BASE_PATH .. "env/__init.lua")
171 end
173 -- prohibit (unintended) definition of new global variables
174 _ENV = setmetatable({}, {
175 __index = _G,
176 __newindex = function()
177 error("Setting of global variable prohibited")
178 end
179 })
181 -- execute configurations
182 for i, config_name in ipairs(WEBMCP_CONFIG_NAMES) do
183 execute.config(config_name)
184 end
186 -- interactive console mode
187 if WEBMCP_MODE == "interactive" then
188 trace.disable() -- avoids memory leakage (TODO: needs general solution for moonbridge?)
189 end
191 -- invoke moonbridge
192 if WEBMCP_MODE == "listen" then
193 local http = require("moonbridge_http")
194 local moonbridge_listen = listen
195 local listeners
196 function _G.listen(args)
197 listeners[#listeners+1] = args
198 end
199 for i = 1, #extraargs/2 do
200 local config = {}
201 listeners = {}
202 execute.config(config_name)
203 for i, listener in ipairs(listeners) do
204 listener.prepare = execute.prefork_initializers
205 listener.connect = http.generate_handler(
206 request.get_http_options(),
207 function(req)
208 execute.postfork_initializers()
209 request.handler(req)
210 end
211 )
212 listener.finish = execute.finalizers
213 moonbridge_listen(listener)
214 end
215 end
216 end
218 --[[ TODO: following lines to be moved to execute.server(...)
220 local success, error_info = xpcall(
221 function()
223 -- execute configuration file
224 do
225 local config_name = request.get_config_name()
226 if config_name then
227 execute.config(config_name)
228 end
229 end
231 -- restore slots if coming from http redirect
232 if cgi.params.tempstore then
233 trace.restore_slots{}
234 local blob = tempstore.pop(cgi.params.tempstore)
235 if blob then slot.restore_all(blob) end
236 end
238 local function file_exists(filename)
239 local file = io.open(filename, "r")
240 if file then
241 io.close(file)
242 return true
243 else
244 return false
245 end
246 end
248 if request.is_404() then
249 request.set_status("404 Not Found")
250 if request.get_404_route() then
251 request.forward(request.get_404_route())
252 else
253 error("No 404 page set.")
254 end
255 elseif request.get_action() then
256 trace.request{
257 module = request.get_module(),
258 action = request.get_action()
259 }
260 if
261 request.get_404_route() and
262 not file_exists(
263 encode.action_file_path{
264 module = request.get_module(),
265 action = request.get_action()
266 }
267 )
268 then
269 request.set_status("404 Not Found")
270 request.forward(request.get_404_route())
271 else
272 if cgi.method ~= "POST" then
273 request.set_status("405 Method Not Allowed")
274 cgi.add_header("Allow: POST")
275 error("Tried to invoke an action with a GET request.")
276 end
277 local action_status = execute.filtered_action{
278 module = request.get_module(),
279 action = request.get_action(),
280 }
281 if not request.is_rerouted() then
282 local routing_mode, routing_module, routing_view
283 routing_mode = cgi.params["_webmcp_routing." .. action_status .. ".mode"]
284 routing_module = cgi.params["_webmcp_routing." .. action_status .. ".module"]
285 routing_view = cgi.params["_webmcp_routing." .. action_status .. ".view"]
286 routing_anchor = cgi.params["_webmcp_routing." .. action_status .. ".anchor"]
287 if not (routing_mode or routing_module or routing_view) then
288 action_status = "default"
289 routing_mode = cgi.params["_webmcp_routing.default.mode"]
290 routing_module = cgi.params["_webmcp_routing.default.module"]
291 routing_view = cgi.params["_webmcp_routing.default.view"]
292 routing_anchor = cgi.params["_webmcp_routing.default.anchor"]
293 end
294 assert(routing_module, "Routing information has no module.")
295 assert(routing_view, "Routing information has no view.")
296 if routing_mode == "redirect" then
297 local routing_params = {}
298 for key, value in pairs(cgi.params) do
299 local status, stripped_key = string.match(
300 key, "^_webmcp_routing%.([^%.]*)%.params%.(.*)$"
301 )
302 if status == action_status then
303 routing_params[stripped_key] = value
304 end
305 end
306 request.redirect{
307 module = routing_module,
308 view = routing_view,
309 id = cgi.params["_webmcp_routing." .. action_status .. ".id"],
310 params = routing_params,
311 anchor = routing_anchor
312 }
313 elseif routing_mode == "forward" then
314 request.forward{ module = routing_module, view = routing_view }
315 else
316 error("Missing or unknown routing mode in request parameters.")
317 end
318 end
319 end
320 else
321 -- no action
322 trace.request{
323 module = request.get_module(),
324 view = request.get_view()
325 }
326 if
327 request.get_404_route() and
328 not file_exists(
329 encode.view_file_path{
330 module = request.get_module(),
331 view = request.get_view()
332 }
333 )
334 then
335 request.set_status("404 Not Found")
336 request.forward(request.get_404_route())
337 end
338 end
340 if not request.get_redirect_data() then
341 request.process_forward()
342 local view = request.get_view()
343 if string.find(view, "^_") then
344 error("Tried to call a private view (prefixed with underscore).")
345 end
346 execute.filtered_view{
347 module = request.get_module(),
348 view = view,
349 }
350 end
352 -- force error due to missing absolute base URL until its too late to display error message
353 --if request.get_redirect_data() then
354 -- request.get_absolute_baseurl()
355 --end
357 end,
359 function(errobj)
360 return {
361 errobj = errobj,
362 stacktrace = string.gsub(
363 debug.traceback('', 2),
364 "^\r?\n?stack traceback:\r?\n?", ""
365 )
366 }
367 end
368 )
370 if not success then trace.error{} end
372 -- laufzeitermittlung
373 trace.exectime{ real = extos.monotonic_hires_time(), cpu = os.clock() }
375 slot.select('trace', trace.render) -- render trace information
377 local redirect_data = request.get_redirect_data()
379 -- log error and switch to error layout, unless success
380 if not success then
381 local errobj = error_info.errobj
382 local stacktrace = error_info.stacktrace
383 if not request.get_status() and not request.get_json_request_slots() then
384 request.set_status("500 Internal Server Error")
385 end
386 slot.set_layout('system_error')
387 slot.select('system_error', function()
388 if getmetatable(errobj) == mondelefant.errorobject_metatable then
389 slot.put(
390 "<p>Database error of class <b>",
391 encode.html(errobj.code),
392 "</b> occured:<br/><b>",
393 encode.html(errobj.message),
394 "</b></p>"
395 )
396 else
397 slot.put("<p><b>", encode.html(tostring(errobj)), "</b></p>")
398 end
399 slot.put("<p>Stack trace follows:<br/>")
400 slot.put(encode.html_newlines(encode.html(stacktrace)))
401 slot.put("</p>")
402 end)
403 elseif redirect_data then
404 local redirect_params = {}
405 for key, value in pairs(redirect_data.params) do
406 redirect_params[key] = value
407 end
408 local slot_dump = slot.dump_all()
409 if slot_dump ~= "" then
410 redirect_params.tempstore = tempstore.save(slot_dump)
411 end
412 local json_request_slots = request.get_json_request_slots()
413 if json_request_slots then
414 redirect_params["_webmcp_json_slots[]"] = json_request_slots
415 end
416 cgi.redirect(
417 encode.url{
418 base = request.get_absolute_baseurl(),
419 module = redirect_data.module,
420 view = redirect_data.view,
421 id = redirect_data.id,
422 params = redirect_params,
423 anchor = redirect_data.anchor
424 }
425 )
426 cgi.send_data()
427 end
429 if not success or not redirect_data then
431 local http_status = request.get_status()
432 if http_status then
433 cgi.set_status(http_status)
434 end
436 local json_request_slots = request.get_json_request_slots()
437 if json_request_slots then
438 cgi.set_content_type('application/json')
439 local data = {}
440 for idx, slot_ident in ipairs(json_request_slots) do
441 data[slot_ident] = slot.get_content(slot_ident)
442 end
443 cgi.send_data(encode.json(data))
444 else
445 cgi.set_content_type(slot.get_content_type())
446 cgi.send_data(slot.render_layout())
447 end
448 end
450 --]]

Impressum / About Us