]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/cpp_api/s_async.cpp
Display Lua memory usage at the time of Out-of-Memory error
[dragonfireclient.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                 (*it)->Kill();
70                 delete *it;
71         }
72
73         jobQueueMutex.Lock();
74         jobQueue.clear();
75         jobQueueMutex.Unlock();
76         workerThreads.clear();
77 }
78
79 /******************************************************************************/
80 bool AsyncEngine::registerFunction(const char* name, lua_CFunction func)
81 {
82         if (initDone) {
83                 return false;
84         }
85         functionList[name] = func;
86         return true;
87 }
88
89 /******************************************************************************/
90 void AsyncEngine::initialize(unsigned int numEngines)
91 {
92         initDone = true;
93
94         for (unsigned int i = 0; i < numEngines; i++) {
95                 AsyncWorkerThread *toAdd = new AsyncWorkerThread(this, 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, int errorhandler)
148 {
149         lua_getglobal(L, "core");
150         resultQueueMutex.Lock();
151         while (!resultQueue.empty()) {
152                 LuaJobInfo jobDone = resultQueue.front();
153                 resultQueue.pop_front();
154
155                 lua_getfield(L, -1, "async_event_handler");
156
157                 if (lua_isnil(L, -1)) {
158                         FATAL_ERROR("Async event handler does not exist!");
159                 }
160
161                 luaL_checktype(L, -1, LUA_TFUNCTION);
162
163                 lua_pushinteger(L, jobDone.id);
164                 lua_pushlstring(L, jobDone.serializedResult.data(),
165                                 jobDone.serializedResult.size());
166
167                 PCALL_RESL(L, lua_pcall(L, 2, 0, errorhandler));
168         }
169         resultQueueMutex.Unlock();
170         lua_pop(L, 1); // Pop core
171 }
172
173 /******************************************************************************/
174 void AsyncEngine::pushFinishedJobs(lua_State* L) {
175         // Result Table
176         resultQueueMutex.Lock();
177
178         unsigned int index = 1;
179         lua_createtable(L, resultQueue.size(), 0);
180         int top = lua_gettop(L);
181
182         while (!resultQueue.empty()) {
183                 LuaJobInfo jobDone = resultQueue.front();
184                 resultQueue.pop_front();
185
186                 lua_createtable(L, 0, 2);  // Pre-allocate space for two map fields
187                 int top_lvl2 = lua_gettop(L);
188
189                 lua_pushstring(L, "jobid");
190                 lua_pushnumber(L, jobDone.id);
191                 lua_settable(L, top_lvl2);
192
193                 lua_pushstring(L, "retval");
194                 lua_pushlstring(L, jobDone.serializedResult.data(),
195                         jobDone.serializedResult.size());
196                 lua_settable(L, top_lvl2);
197
198                 lua_rawseti(L, top, index++);
199         }
200
201         resultQueueMutex.Unlock();
202 }
203
204 /******************************************************************************/
205 void AsyncEngine::prepareEnvironment(lua_State* L, int top)
206 {
207         for (std::map<std::string, lua_CFunction>::iterator it = functionList.begin();
208                         it != functionList.end(); it++) {
209                 lua_pushstring(L, it->first.c_str());
210                 lua_pushcfunction(L, it->second);
211                 lua_settable(L, top);
212         }
213 }
214
215 /******************************************************************************/
216 AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher,
217                 unsigned int threadNum) :
218         ScriptApiBase(),
219         jobDispatcher(jobDispatcher),
220         threadnum(threadNum)
221 {
222         lua_State *L = getStack();
223
224         // Prepare job lua environment
225         lua_getglobal(L, "core");
226         int top = lua_gettop(L);
227
228         // Push builtin initialization type
229         lua_pushstring(L, "async");
230         lua_setglobal(L, "INIT");
231
232         jobDispatcher->prepareEnvironment(L, top);
233 }
234
235 /******************************************************************************/
236 AsyncWorkerThread::~AsyncWorkerThread()
237 {
238         sanity_check(IsRunning() == false);
239 }
240
241 /******************************************************************************/
242 void* AsyncWorkerThread::Thread()
243 {
244         ThreadStarted();
245
246         // Register thread for error logging
247         char number[21];
248         snprintf(number, sizeof(number), "%u", threadnum);
249         log_register_thread(std::string("AsyncWorkerThread_") + number);
250
251         porting::setThreadName((std::string("AsyncWorkTh_") + number).c_str());
252
253         lua_State *L = getStack();
254
255         std::string script = getServer()->getBuiltinLuaPath() + DIR_DELIM + "init.lua";
256         if (!loadScript(script)) {
257                 errorstream
258                         << "AsyncWorkerThread execution of async base environment failed!"
259                         << std::endl;
260                 abort();
261         }
262
263         lua_getglobal(L, "core");
264         if (lua_isnil(L, -1)) {
265                 errorstream << "Unable to find core within async environment!";
266                 abort();
267         }
268
269         // Main loop
270         while (!StopRequested()) {
271                 // Wait for job
272                 LuaJobInfo toProcess = jobDispatcher->getJob();
273
274                 if (toProcess.valid == false || StopRequested()) {
275                         continue;
276                 }
277
278                 lua_getfield(L, -1, "job_processor");
279                 if (lua_isnil(L, -1)) {
280                         errorstream << "Unable to get async job processor!" << std::endl;
281                         abort();
282                 }
283
284                 luaL_checktype(L, -1, LUA_TFUNCTION);
285
286                 // Call it
287                 lua_pushlstring(L,
288                                 toProcess.serializedFunction.data(),
289                                 toProcess.serializedFunction.size());
290                 lua_pushlstring(L,
291                                 toProcess.serializedParams.data(),
292                                 toProcess.serializedParams.size());
293
294                 int result = lua_pcall(L, 2, 1, m_errorhandler);
295                 if (result) {
296                         PCALL_RES(result);
297                         toProcess.serializedResult = "";
298                 } else {
299                         // Fetch result
300                         size_t length;
301                         const char *retval = lua_tolstring(L, -1, &length);
302                         toProcess.serializedResult = std::string(retval, length);
303                 }
304
305                 lua_pop(L, 1);  // Pop retval
306
307                 // Put job result
308                 jobDispatcher->putJobResult(toProcess);
309         }
310
311         lua_pop(L, 1);  // Pop core
312
313         log_deregister_thread();
314
315         return 0;
316 }
317