Fix server crashing on Lua errors
[oweals/minetest.git] / src / script / cpp_api / s_async.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 sapier, <sapier AT gmx DOT net>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22
23 extern "C" {
24 #include "lua.h"
25 #include "lauxlib.h"
26 #include "lualib.h"
27 }
28
29 #include "server.h"
30 #include "s_async.h"
31 #include "log.h"
32 #include "filesys.h"
33 #include "porting.h"
34 #include "common/c_internal.h"
35
36 /******************************************************************************/
37 AsyncEngine::AsyncEngine() :
38         initDone(false),
39         jobIdCounter(0)
40 {
41 }
42
43 /******************************************************************************/
44 AsyncEngine::~AsyncEngine()
45 {
46
47         // Request all threads to stop
48         for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
49                         it != workerThreads.end(); it++) {
50                 (*it)->stop();
51         }
52
53
54         // Wake up all threads
55         for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
56                         it != workerThreads.end(); it++) {
57                 jobQueueCounter.post();
58         }
59
60         // Wait for threads to finish
61         for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
62                         it != workerThreads.end(); it++) {
63                 (*it)->wait();
64         }
65
66         // Force kill all threads
67         for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin();
68                         it != workerThreads.end(); it++) {
69                 delete *it;
70         }
71
72         jobQueueMutex.lock();
73         jobQueue.clear();
74         jobQueueMutex.unlock();
75         workerThreads.clear();
76 }
77
78 /******************************************************************************/
79 bool AsyncEngine::registerFunction(const char* name, lua_CFunction func)
80 {
81         if (initDone) {
82                 return false;
83         }
84         functionList[name] = func;
85         return true;
86 }
87
88 /******************************************************************************/
89 void AsyncEngine::initialize(unsigned int numEngines)
90 {
91         initDone = true;
92
93         for (unsigned int i = 0; i < numEngines; i++) {
94                 AsyncWorkerThread *toAdd = new AsyncWorkerThread(this,
95                         std::string("AsyncWorker-") + itos(i));
96                 workerThreads.push_back(toAdd);
97                 toAdd->start();
98         }
99 }
100
101 /******************************************************************************/
102 unsigned int AsyncEngine::queueAsyncJob(std::string func, std::string params)
103 {
104         jobQueueMutex.lock();
105         LuaJobInfo toAdd;
106         toAdd.id = jobIdCounter++;
107         toAdd.serializedFunction = func;
108         toAdd.serializedParams = params;
109
110         jobQueue.push_back(toAdd);
111
112         jobQueueCounter.post();
113
114         jobQueueMutex.unlock();
115
116         return toAdd.id;
117 }
118
119 /******************************************************************************/
120 LuaJobInfo AsyncEngine::getJob()
121 {
122         jobQueueCounter.wait();
123         jobQueueMutex.lock();
124
125         LuaJobInfo retval;
126         retval.valid = false;
127
128         if (!jobQueue.empty()) {
129                 retval = jobQueue.front();
130                 jobQueue.pop_front();
131                 retval.valid = true;
132         }
133         jobQueueMutex.unlock();
134
135         return retval;
136 }
137
138 /******************************************************************************/
139 void AsyncEngine::putJobResult(LuaJobInfo result)
140 {
141         resultQueueMutex.lock();
142         resultQueue.push_back(result);
143         resultQueueMutex.unlock();
144 }
145
146 /******************************************************************************/
147 void AsyncEngine::step(lua_State *L)
148 {
149         int error_handler = PUSH_ERROR_HANDLER(L);
150         lua_getglobal(L, "core");
151         resultQueueMutex.lock();
152         while (!resultQueue.empty()) {
153                 LuaJobInfo jobDone = resultQueue.front();
154                 resultQueue.pop_front();
155
156                 lua_getfield(L, -1, "async_event_handler");
157
158                 if (lua_isnil(L, -1)) {
159                         FATAL_ERROR("Async event handler does not exist!");
160                 }
161
162                 luaL_checktype(L, -1, LUA_TFUNCTION);
163
164                 lua_pushinteger(L, jobDone.id);
165                 lua_pushlstring(L, jobDone.serializedResult.data(),
166                                 jobDone.serializedResult.size());
167
168                 PCALL_RESL(L, lua_pcall(L, 2, 0, error_handler));
169         }
170         resultQueueMutex.unlock();
171         lua_pop(L, 2); // Pop core and error handler
172 }
173
174 /******************************************************************************/
175 void AsyncEngine::pushFinishedJobs(lua_State* L) {
176         // Result Table
177         MutexAutoLock l(resultQueueMutex);
178
179         unsigned int index = 1;
180         lua_createtable(L, resultQueue.size(), 0);
181         int top = lua_gettop(L);
182
183         while (!resultQueue.empty()) {
184                 LuaJobInfo jobDone = resultQueue.front();
185                 resultQueue.pop_front();
186
187                 lua_createtable(L, 0, 2);  // Pre-allocate space for two map fields
188                 int top_lvl2 = lua_gettop(L);
189
190                 lua_pushstring(L, "jobid");
191                 lua_pushnumber(L, jobDone.id);
192                 lua_settable(L, top_lvl2);
193
194                 lua_pushstring(L, "retval");
195                 lua_pushlstring(L, jobDone.serializedResult.data(),
196                         jobDone.serializedResult.size());
197                 lua_settable(L, top_lvl2);
198
199                 lua_rawseti(L, top, index++);
200         }
201 }
202
203 /******************************************************************************/
204 void AsyncEngine::prepareEnvironment(lua_State* L, int top)
205 {
206         for (std::map<std::string, lua_CFunction>::iterator it = functionList.begin();
207                         it != functionList.end(); it++) {
208                 lua_pushstring(L, it->first.c_str());
209                 lua_pushcfunction(L, it->second);
210                 lua_settable(L, top);
211         }
212 }
213
214 /******************************************************************************/
215 AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
216                 const std::string &name) :
217         Thread(name),
218         ScriptApiBase(),
219         jobDispatcher(jobDispatcher)
220 {
221         lua_State *L = getStack();
222
223         // Prepare job lua environment
224         lua_getglobal(L, "core");
225         int top = lua_gettop(L);
226
227         // Push builtin initialization type
228         lua_pushstring(L, "async");
229         lua_setglobal(L, "INIT");
230
231         jobDispatcher->prepareEnvironment(L, top);
232 }
233
234 /******************************************************************************/
235 AsyncWorkerThread::~AsyncWorkerThread()
236 {
237         sanity_check(!isRunning());
238 }
239
240 /******************************************************************************/
241 void* AsyncWorkerThread::run()
242 {
243         lua_State *L = getStack();
244
245         std::string script = getServer()->getBuiltinLuaPath() + DIR_DELIM + "init.lua";
246         try {
247                 loadScript(script);
248         } catch (const ModError &e) {
249                 errorstream << "Execution of async base environment failed: "
250                         << e.what() << std::endl;
251                 FATAL_ERROR("Execution of async base environment failed");
252         }
253
254         int error_handler = PUSH_ERROR_HANDLER(L);
255
256         lua_getglobal(L, "core");
257         if (lua_isnil(L, -1)) {
258                 FATAL_ERROR("Unable to find core within async environment!");
259         }
260
261         // Main loop
262         while (!stopRequested()) {
263                 // Wait for job
264                 LuaJobInfo toProcess = jobDispatcher->getJob();
265
266                 if (toProcess.valid == false || stopRequested()) {
267                         continue;
268                 }
269
270                 lua_getfield(L, -1, "job_processor");
271                 if (lua_isnil(L, -1)) {
272                         FATAL_ERROR("Unable to get async job processor!");
273                 }
274
275                 luaL_checktype(L, -1, LUA_TFUNCTION);
276
277                 // Call it
278                 lua_pushlstring(L,
279                                 toProcess.serializedFunction.data(),
280                                 toProcess.serializedFunction.size());
281                 lua_pushlstring(L,
282                                 toProcess.serializedParams.data(),
283                                 toProcess.serializedParams.size());
284
285                 int result = lua_pcall(L, 2, 1, error_handler);
286                 if (result) {
287                         PCALL_RES(result);
288                         toProcess.serializedResult = "";
289                 } else {
290                         // Fetch result
291                         size_t length;
292                         const char *retval = lua_tolstring(L, -1, &length);
293                         toProcess.serializedResult = std::string(retval, length);
294                 }
295
296                 lua_pop(L, 1);  // Pop retval
297
298                 // Put job result
299                 jobDispatcher->putJobResult(toProcess);
300         }
301
302         lua_pop(L, 2);  // Pop core and error handler
303
304         return 0;
305 }
306