|
| 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 | +extern "C" { |
| 21 | +#include "lua.h" |
| 22 | +#include "lauxlib.h" |
| 23 | +#include "lualib.h" |
| 24 | +int luaopen_marshal(lua_State *L); |
| 25 | +} |
| 26 | +#include <stdio.h> |
| 27 | + |
| 28 | +#include "l_async_events.h" |
| 29 | +#include "log.h" |
| 30 | +#include "filesys.h" |
| 31 | +#include "porting.h" |
| 32 | + |
| 33 | +//TODO replace by ShadowNinja version not yet merged to master |
| 34 | +static int script_error_handler(lua_State *L) { |
| 35 | + lua_getfield(L, LUA_GLOBALSINDEX, "debug"); |
| 36 | + if (!lua_istable(L, -1)) { |
| 37 | + lua_pop(L, 1); |
| 38 | + return 1; |
| 39 | + } |
| 40 | + lua_getfield(L, -1, "traceback"); |
| 41 | + if (!lua_isfunction(L, -1)) { |
| 42 | + lua_pop(L, 2); |
| 43 | + return 1; |
| 44 | + } |
| 45 | + lua_pushvalue(L, 1); |
| 46 | + lua_pushinteger(L, 2); |
| 47 | + lua_call(L, 2, 1); |
| 48 | + return 1; |
| 49 | +} |
| 50 | + |
| 51 | +/******************************************************************************/ |
| 52 | +static void scriptError(const char *fmt, ...) |
| 53 | +{ |
| 54 | + va_list argp; |
| 55 | + va_start(argp, fmt); |
| 56 | + char buf[10000]; |
| 57 | + vsnprintf(buf, 10000, fmt, argp); |
| 58 | + va_end(argp); |
| 59 | + errorstream<<"ERROR: "<<buf; |
| 60 | + fprintf(stderr,"ERROR: %s\n",buf); |
| 61 | +} |
| 62 | + |
| 63 | +/******************************************************************************/ |
| 64 | +AsyncEngine::AsyncEngine() : |
| 65 | + m_initDone(false), |
| 66 | + m_JobIdCounter(0) |
| 67 | +{ |
| 68 | + assert(m_JobQueueMutex.Init() == 0); |
| 69 | + assert(m_ResultQueueMutex.Init() == 0); |
| 70 | +} |
| 71 | + |
| 72 | +/******************************************************************************/ |
| 73 | +AsyncEngine::~AsyncEngine() |
| 74 | +{ |
| 75 | + /** request all threads to stop **/ |
| 76 | + for (std::vector<AsyncWorkerThread*>::iterator i= m_WorkerThreads.begin(); |
| 77 | + i != m_WorkerThreads.end();i++) { |
| 78 | + (*i)->Stop(); |
| 79 | + } |
| 80 | + |
| 81 | + |
| 82 | + /** wakeup all threads **/ |
| 83 | + for (std::vector<AsyncWorkerThread*>::iterator i= m_WorkerThreads.begin(); |
| 84 | + i != m_WorkerThreads.end();i++) { |
| 85 | + m_JobQueueCounter.Post(); |
| 86 | + } |
| 87 | + |
| 88 | + /** wait for threads to finish **/ |
| 89 | + for (std::vector<AsyncWorkerThread*>::iterator i= m_WorkerThreads.begin(); |
| 90 | + i != m_WorkerThreads.end();i++) { |
| 91 | + (*i)->Wait(); |
| 92 | + } |
| 93 | + |
| 94 | + /** force kill all threads **/ |
| 95 | + for (std::vector<AsyncWorkerThread*>::iterator i= m_WorkerThreads.begin(); |
| 96 | + i != m_WorkerThreads.end();i++) { |
| 97 | + (*i)->Kill(); |
| 98 | + delete *i; |
| 99 | + } |
| 100 | + |
| 101 | + m_JobQueueMutex.Lock(); |
| 102 | + m_JobQueue.clear(); |
| 103 | + m_JobQueueMutex.Unlock(); |
| 104 | + m_WorkerThreads.clear(); |
| 105 | +} |
| 106 | + |
| 107 | +/******************************************************************************/ |
| 108 | +bool AsyncEngine::registerFunction(const char* name, lua_CFunction fct) { |
| 109 | + |
| 110 | + if (m_initDone) return false; |
| 111 | + m_FunctionList[name] = fct; |
| 112 | + return true; |
| 113 | +} |
| 114 | + |
| 115 | +/******************************************************************************/ |
| 116 | +void AsyncEngine::Initialize(unsigned int numengines) { |
| 117 | + m_initDone = true; |
| 118 | + |
| 119 | + for (unsigned int i=0; i < numengines; i ++) { |
| 120 | + |
| 121 | + AsyncWorkerThread* toadd = new AsyncWorkerThread(this,i); |
| 122 | + m_WorkerThreads.push_back(toadd); |
| 123 | + toadd->Start(); |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +/******************************************************************************/ |
| 128 | +unsigned int AsyncEngine::doAsyncJob(std::string fct, std::string params) { |
| 129 | + |
| 130 | + m_JobQueueMutex.Lock(); |
| 131 | + LuaJobInfo toadd; |
| 132 | + toadd.JobId = m_JobIdCounter++; |
| 133 | + toadd.serializedFunction = fct; |
| 134 | + toadd.serializedParams = params; |
| 135 | + |
| 136 | + m_JobQueue.push_back(toadd); |
| 137 | + |
| 138 | + m_JobQueueCounter.Post(); |
| 139 | + |
| 140 | + m_JobQueueMutex.Unlock(); |
| 141 | + |
| 142 | + return toadd.JobId; |
| 143 | +} |
| 144 | + |
| 145 | +/******************************************************************************/ |
| 146 | +LuaJobInfo AsyncEngine::getJob() { |
| 147 | + |
| 148 | + m_JobQueueCounter.Wait(); |
| 149 | + m_JobQueueMutex.Lock(); |
| 150 | + |
| 151 | + LuaJobInfo retval; |
| 152 | + |
| 153 | + if (m_JobQueue.size() != 0) { |
| 154 | + retval = m_JobQueue.front(); |
| 155 | + m_JobQueue.erase((m_JobQueue.begin())); |
| 156 | + } |
| 157 | + m_JobQueueMutex.Unlock(); |
| 158 | + |
| 159 | + return retval; |
| 160 | +} |
| 161 | + |
| 162 | +/******************************************************************************/ |
| 163 | +void AsyncEngine::putJobResult(LuaJobInfo result) { |
| 164 | + m_ResultQueueMutex.Lock(); |
| 165 | + m_ResultQueue.push_back(result); |
| 166 | + m_ResultQueueMutex.Unlock(); |
| 167 | +} |
| 168 | + |
| 169 | +/******************************************************************************/ |
| 170 | +void AsyncEngine::Step(lua_State *L) { |
| 171 | + m_ResultQueueMutex.Lock(); |
| 172 | + while(!m_ResultQueue.empty()) { |
| 173 | + |
| 174 | + LuaJobInfo jobdone = m_ResultQueue.front(); |
| 175 | + m_ResultQueue.erase(m_ResultQueue.begin()); |
| 176 | + lua_getglobal(L, "engine"); |
| 177 | + |
| 178 | + lua_getfield(L, -1, "async_event_handler"); |
| 179 | + |
| 180 | + if(lua_isnil(L, -1)) |
| 181 | + assert("Someone managed to destroy a async callback in engine!" == 0); |
| 182 | + |
| 183 | + luaL_checktype(L, -1, LUA_TFUNCTION); |
| 184 | + |
| 185 | + lua_pushinteger(L, jobdone.JobId); |
| 186 | + lua_pushlstring(L, jobdone.serializedResult.c_str(), |
| 187 | + jobdone.serializedResult.length()); |
| 188 | + |
| 189 | + if(lua_pcall(L, 2, 0, 0)) { |
| 190 | + scriptError("Async ENGINE step: %s", lua_tostring(L, -1)); |
| 191 | + } |
| 192 | + |
| 193 | + lua_pop(L,1); |
| 194 | + } |
| 195 | + m_ResultQueueMutex.Unlock(); |
| 196 | +} |
| 197 | + |
| 198 | +/******************************************************************************/ |
| 199 | +void AsyncEngine::PushFinishedJobs(lua_State* L) { |
| 200 | + //Result Table |
| 201 | + m_ResultQueueMutex.Lock(); |
| 202 | + |
| 203 | + unsigned int index=1; |
| 204 | + lua_newtable(L); |
| 205 | + int top = lua_gettop(L); |
| 206 | + |
| 207 | + while(!m_ResultQueue.empty()) { |
| 208 | + |
| 209 | + LuaJobInfo jobdone = m_ResultQueue.front(); |
| 210 | + m_ResultQueue.erase(m_ResultQueue.begin()); |
| 211 | + |
| 212 | + lua_pushnumber(L,index); |
| 213 | + |
| 214 | + lua_newtable(L); |
| 215 | + int top_lvl2 = lua_gettop(L); |
| 216 | + |
| 217 | + lua_pushstring(L,"jobid"); |
| 218 | + lua_pushnumber(L,jobdone.JobId); |
| 219 | + lua_settable(L, top_lvl2); |
| 220 | + |
| 221 | + lua_pushstring(L,"retval"); |
| 222 | + lua_pushstring(L, jobdone.serializedResult.c_str()); |
| 223 | + lua_settable(L, top_lvl2); |
| 224 | + |
| 225 | + lua_settable(L, top); |
| 226 | + index++; |
| 227 | + } |
| 228 | + |
| 229 | + m_ResultQueueMutex.Unlock(); |
| 230 | + |
| 231 | +} |
| 232 | +/******************************************************************************/ |
| 233 | +void AsyncEngine::PrepareEnvironment(lua_State* L, int top) { |
| 234 | + for(std::map<std::string,lua_CFunction>::iterator i = m_FunctionList.begin(); |
| 235 | + i != m_FunctionList.end(); i++) { |
| 236 | + |
| 237 | + lua_pushstring(L,i->first.c_str()); |
| 238 | + lua_pushcfunction(L,i->second); |
| 239 | + lua_settable(L, top); |
| 240 | + |
| 241 | + } |
| 242 | +} |
| 243 | + |
| 244 | +/******************************************************************************/ |
| 245 | +int async_worker_ErrorHandler(lua_State *L) { |
| 246 | + lua_getfield(L, LUA_GLOBALSINDEX, "debug"); |
| 247 | + if (!lua_istable(L, -1)) { |
| 248 | + lua_pop(L, 1); |
| 249 | + return 1; |
| 250 | + } |
| 251 | + lua_getfield(L, -1, "traceback"); |
| 252 | + if (!lua_isfunction(L, -1)) { |
| 253 | + lua_pop(L, 2); |
| 254 | + return 1; |
| 255 | + } |
| 256 | + lua_pushvalue(L, 1); |
| 257 | + lua_pushinteger(L, 2); |
| 258 | + lua_call(L, 2, 1); |
| 259 | + return 1; |
| 260 | +} |
| 261 | + |
| 262 | +/******************************************************************************/ |
| 263 | +AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobdispatcher, |
| 264 | + unsigned int numthreadnumber) : |
| 265 | + m_JobDispatcher(jobdispatcher), |
| 266 | + m_luaerrorhandler(-1), |
| 267 | + m_threadnum(numthreadnumber) |
| 268 | +{ |
| 269 | + // create luastack |
| 270 | + m_LuaStack = luaL_newstate(); |
| 271 | + |
| 272 | + // load basic lua modules |
| 273 | + luaL_openlibs(m_LuaStack); |
| 274 | + |
| 275 | + // load serialization functions |
| 276 | + luaopen_marshal(m_LuaStack); |
| 277 | +} |
| 278 | + |
| 279 | +/******************************************************************************/ |
| 280 | +AsyncWorkerThread::~AsyncWorkerThread() { |
| 281 | + |
| 282 | + assert(IsRunning() == false); |
| 283 | + lua_close(m_LuaStack); |
| 284 | +} |
| 285 | + |
| 286 | +/******************************************************************************/ |
| 287 | +void* AsyncWorkerThread::worker_thread_main() { |
| 288 | + |
| 289 | + //register thread for error logging |
| 290 | + char number[21]; |
| 291 | + snprintf(number,sizeof(number),"%d",m_threadnum); |
| 292 | + log_register_thread(std::string("AsyncWorkerThread_") + number); |
| 293 | + |
| 294 | + /** prepare job lua environment **/ |
| 295 | + lua_newtable(m_LuaStack); |
| 296 | + lua_setglobal(m_LuaStack, "engine"); |
| 297 | + |
| 298 | + lua_getglobal(m_LuaStack, "engine"); |
| 299 | + int top = lua_gettop(m_LuaStack); |
| 300 | + |
| 301 | + lua_pushstring(m_LuaStack, DIR_DELIM); |
| 302 | + lua_setglobal(m_LuaStack, "DIR_DELIM"); |
| 303 | + |
| 304 | + lua_pushstring(m_LuaStack, |
| 305 | + std::string(porting::path_share + DIR_DELIM + "builtin").c_str()); |
| 306 | + lua_setglobal(m_LuaStack, "SCRIPTDIR"); |
| 307 | + |
| 308 | + |
| 309 | + m_JobDispatcher->PrepareEnvironment(m_LuaStack,top); |
| 310 | + |
| 311 | + std::string asyncscript = |
| 312 | + porting::path_share + DIR_DELIM + "builtin" |
| 313 | + + DIR_DELIM + "async_env.lua"; |
| 314 | + |
| 315 | + lua_pushcfunction(m_LuaStack, async_worker_ErrorHandler); |
| 316 | + m_luaerrorhandler = lua_gettop(m_LuaStack); |
| 317 | + |
| 318 | + if(!runScript(asyncscript)) { |
| 319 | + infostream |
| 320 | + << "AsyncWorkderThread::worker_thread_main execution of async base environment failed!" |
| 321 | + << std::endl; |
| 322 | + assert("no future with broken builtin async environment scripts" == 0); |
| 323 | + } |
| 324 | + /** main loop **/ |
| 325 | + while(IsRunning()) { |
| 326 | + //wait for job |
| 327 | + LuaJobInfo toprocess = m_JobDispatcher->getJob(); |
| 328 | + |
| 329 | + if (!IsRunning()) { continue; } |
| 330 | + |
| 331 | + //first push error handler |
| 332 | + lua_pushcfunction(m_LuaStack, script_error_handler); |
| 333 | + int errorhandler = lua_gettop(m_LuaStack); |
| 334 | + |
| 335 | + lua_getglobal(m_LuaStack, "engine"); |
| 336 | + if(lua_isnil(m_LuaStack, -1)) |
| 337 | + assert("unable to find engine within async environment" == 0); |
| 338 | + |
| 339 | + lua_getfield(m_LuaStack, -1, "job_processor"); |
| 340 | + if(lua_isnil(m_LuaStack, -1)) |
| 341 | + assert("Someone managed to destroy a async worker engine!" == 0); |
| 342 | + |
| 343 | + luaL_checktype(m_LuaStack, -1, LUA_TFUNCTION); |
| 344 | + |
| 345 | + //call it |
| 346 | + lua_pushlstring(m_LuaStack, |
| 347 | + toprocess.serializedFunction.c_str(), |
| 348 | + toprocess.serializedFunction.length()); |
| 349 | + lua_pushlstring(m_LuaStack, |
| 350 | + toprocess.serializedParams.c_str(), |
| 351 | + toprocess.serializedParams.length()); |
| 352 | + |
| 353 | + if (!IsRunning()) { continue; } |
| 354 | + if(lua_pcall(m_LuaStack, 2, 2, errorhandler)) { |
| 355 | + scriptError("Async WORKER thread: %s\n", lua_tostring(m_LuaStack, -1)); |
| 356 | + toprocess.serializedResult="ERROR"; |
| 357 | + } |
| 358 | + else { |
| 359 | + //fetch result |
| 360 | + const char *retval = lua_tostring(m_LuaStack, -2); |
| 361 | + unsigned int lenght = lua_tointeger(m_LuaStack,-1); |
| 362 | + toprocess.serializedResult = std::string(retval,lenght); |
| 363 | + } |
| 364 | + |
| 365 | + if (!IsRunning()) { continue; } |
| 366 | + //put job result |
| 367 | + m_JobDispatcher->putJobResult(toprocess); |
| 368 | + } |
| 369 | + log_deregister_thread(); |
| 370 | + return 0; |
| 371 | +} |
| 372 | + |
| 373 | +/******************************************************************************/ |
| 374 | +bool AsyncWorkerThread::runScript(std::string script) { |
| 375 | + |
| 376 | + int ret = luaL_loadfile(m_LuaStack, script.c_str()) || |
| 377 | + lua_pcall(m_LuaStack, 0, 0, m_luaerrorhandler); |
| 378 | + if(ret){ |
| 379 | + errorstream<<"==== ERROR FROM LUA WHILE INITIALIZING ASYNC ENVIRONMENT ====="<<std::endl; |
| 380 | + errorstream<<"Failed to load and run script from "<<std::endl; |
| 381 | + errorstream<<script<<":"<<std::endl; |
| 382 | + errorstream<<std::endl; |
| 383 | + errorstream<<lua_tostring(m_LuaStack, -1)<<std::endl; |
| 384 | + errorstream<<std::endl; |
| 385 | + errorstream<<"=================== END OF ERROR FROM LUA ===================="<<std::endl; |
| 386 | + lua_pop(m_LuaStack, 1); // Pop error message from stack |
| 387 | + lua_pop(m_LuaStack, 1); // Pop the error handler from stack |
| 388 | + return false; |
| 389 | + } |
| 390 | + return true; |
| 391 | +} |
| 392 | + |
| 393 | +/******************************************************************************/ |
| 394 | +void* AsyncWorkerThread::worker_thread_wrapper(void* thread) { |
| 395 | + return ((AsyncWorkerThread*) thread)->worker_thread_main(); |
| 396 | +} |
0 commit comments