def on_lua_error(self, lua_exception): py_exception = self.splash.get_real_exception() if not py_exception: return py_exception = self._make_script_error(py_exception) self.log("[lua] LuaError is caused by %r" % py_exception) if not isinstance(py_exception, ScriptError): # XXX: we only know how to handle ScriptError self.log("[lua] returning Lua error as-is") return # Remove internal details from the Lua error message # and add cleaned up information to the error info. py_info = py_exception.args[0] lua_info = parse_error_message(lua_exception.args[0]) if isinstance(py_info, dict) and 'message' in py_info: py_info.update(lua_info) py_info['error'] = py_info['message'] # replace Lua error message if 'line_number' in lua_info and 'source' in lua_info: py_info['message'] = "%s:%s: %s" % ( lua_info['source'], lua_info['line_number'], py_info['error'] ) else: py_info['message'] = py_info['error'] raise ScriptError(py_info)
def start(self, lua_source, sandboxed, lua_package_path, lua_sandbox_allowed_modules): self.exceptions = StoredExceptions() self.log(lua_source) self.sandboxed = sandboxed self.lua = SplashLuaRuntime( sandboxed=sandboxed, lua_package_path=lua_package_path, lua_sandbox_allowed_modules=lua_sandbox_allowed_modules, ) self.splash = Splash(self.lua, self.exceptions, self.tab, self.render_options, log=self.log) self.extras = Extras(self.lua, self.exceptions) self.extras.inject_to_globals() self.runner = MainCoroutineRunner(lua=self.lua, splash=self.splash, log=self.log, sandboxed=sandboxed) try: main_coro = self.get_main_coro(lua_source) except lupa.LuaSyntaxError as e: # XXX: is this code active? # It looks like we're always getting LuaError # because of sandbox and coroutine handling code. raise ScriptError({"type": ScriptError.SYNTAX_ERROR, "message": to_unicode(e.args[0])}) except lupa.LuaError as e: # Error happened before starting coroutine info = parse_error_message(e.args[0]) info.update({"type": ScriptError.LUA_INIT_ERROR, "message": to_unicode(e.args[0])}) raise ScriptError(info) # except ValueError as e: # # XXX: when does it happen? # raise ScriptError({ # "type": ScriptError.UNKNOWN_ERROR, # "message": repr(e), # }) self.runner.start(main_coro=main_coro, return_result=self.return_result, return_error=self.return_error)
def error_repr(e): """ Return repr of an exception, for printing as a cell execution result. """ if isinstance(e, (ScriptError, lupa.LuaSyntaxError, lupa.LuaError)): if isinstance(e, ScriptError): info = e.args[0] tp = info['type'] else: info = parse_error_message(e.args[0]) tp = ScriptError.SYNTAX_ERROR line_num = info.get('line_number', -1) message = info.get('error', info.get('message')) return "%s [input]:%s: %s" % (tp, line_num, message) elif isinstance(e, Exception): return repr(e) return ScriptError.UNKNOWN_ERROR
def dispatch(self, cmd_id, *args): """ Execute the script """ args = args or () def truncated_repr(x): return truncated("{!r}".format(x), max_length=400, msg="...[long arguments truncated]") self.log("[lua_runner] dispatch cmd_id={}".format(cmd_id)) self.log( "[lua_runner] arguments are for command %s, waiting for result of %s" % (cmd_id, self._waiting_for_result_id), min_level=3, ) if cmd_id != self._waiting_for_result_id: self.log("[lua_runner] skipping an out-of-order result {}".format(truncated_repr(args)), min_level=1) return while True: self.log('[lua_runner] entering dispatch/loop body, args={}'.format(truncated_repr(args))) try: if self._is_first_iter: args = None else: is_python_result = (len(args) == 1 and isinstance(args[0], PyResult)) if is_python_result: args = args[0] else: args = PyResult(*args) if self._is_stopped: raise StopIteration # Got arguments from an async command; send them to coroutine # and wait for the next async command. self.log("[lua_runner] send %s" % truncated_repr(args)) as_lua = self.lua.python2lua(args) self.log("[lua_runner] send (lua) %s" % truncated_repr(as_lua)) cmd = self.coro.send(as_lua) # cmd is a next async command if self._is_first_iter: self._is_first_iter = False # If cmd is a synchronous result, prepare it to be passed into # the next coroutine step. args = ensure_tuple(cmd) cmd_repr = truncated(repr(cmd), max_length=400, msg='...[long result truncated]') self.log("[lua_runner] got {}".format(cmd_repr)) self._print_instructions_used() except StopIteration: # "main" coroutine is stopped; # previous result is a final result returned from "main" self.log("[lua_runner] returning result") try: res = self.lua.lua2python(self.result) except ValueError as e: # can't convert result to a Python object raise ScriptError({ "type": ScriptError.BAD_MAIN_ERROR, "message": "'main' returned bad result. {!s}".format( e.args[0] ) }) except lupa.LuaError as lua_ex: # Error converting result to Python # This may happen e.g. if conversion hit sandbox limits self.log("[lua_runner] caught LuaError %r" % lua_ex) info = parse_error_message(lua_ex.args[0]) error = info.get('error', '?') raise ScriptError({ "type": ScriptError.LUA_CONVERT_ERROR, "error": error, "message": "Lua error: {!s}".format(error) }) self._print_instructions_used() self.on_result(res) return except lupa.LuaError as lua_ex: # import traceback # print(traceback.format_exc()) # Lua script raised an error self._print_instructions_used() self.log("[lua_runner] caught LuaError %r" % lua_ex) # this can raise a ScriptError self.on_lua_error(lua_ex) # ScriptError is not raised, construct it ourselves info = parse_error_message(lua_ex.args[0]) info.update({ "type": ScriptError.LUA_ERROR, "message": "Lua error: {!s}".format(lua_ex) }) raise ScriptError(info) if isinstance(cmd, AsyncCommand): cmd.bind(self, next(self._command_ids)) self.log("[lua_runner] executing {!r}".format(cmd)) self._waiting_for_result_id = cmd.id self.on_async_command(cmd) return if isinstance(cmd, PyResult): self.log("[lua_runner] got result {!r}".format(cmd)) else: self.log("[lua_runner] got non-command") self.result = cmd
def dispatch(self, cmd_id, *args): """ Execute the script """ args = args or () def truncated_repr(x): return truncated("{!r}".format(x), max_length=400, msg="...[long arguments truncated]") self.log("[lua_runner] dispatch cmd_id={}".format(cmd_id)) self.log( "[lua_runner] arguments are for command %s, waiting for result of %s" % (cmd_id, self._waiting_for_result_id), min_level=3, ) if cmd_id != self._waiting_for_result_id: msg = "[lua_runner] skipping an out-of-order result {}".format( truncated_repr(args)) self.log(msg, min_level=1) if self.strict: raise InternalError(msg) else: return while True: self.log( '[lua_runner] entering dispatch/loop body, args={}'.format( truncated_repr(args))) try: if self._is_first_iter: args = None else: is_python_result = (len(args) == 1 and isinstance(args[0], PyResult)) if is_python_result: args = args[0] else: args = PyResult(*args) if self._is_stopped: raise StopIteration # Got arguments from an async command; send them to coroutine # and wait for the next async command. self.log("[lua_runner] send %s" % truncated_repr(args)) as_lua = self.lua.python2lua(args) self.log("[lua_runner] send (lua) %s" % truncated_repr(as_lua)) cmd = self.coro.send(as_lua) # cmd is a next async command if self._is_first_iter: self._is_first_iter = False # If cmd is a synchronous result, prepare it to be passed into # the next coroutine step. args = ensure_tuple(cmd) cmd_repr = truncated(repr(cmd), max_length=400, msg='...[long result truncated]') self.log("[lua_runner] got {}".format(cmd_repr)) self._print_instructions_used() except StopIteration: # "main" coroutine is stopped; # previous result is a final result returned from "main" self.log("[lua_runner] returning result") try: res = self.lua.lua2python(self.result) except ValueError as e: # can't convert result to a Python object raise ScriptError({ "type": ScriptError.BAD_MAIN_ERROR, "message": "'main' returned bad result. {!s}".format(e.args[0]) }) except lupa.LuaError as lua_ex: # Error converting result to Python # This may happen e.g. if conversion hit sandbox limits self.log("[lua_runner] caught LuaError %r" % lua_ex) info = parse_error_message(lua_ex.args[0]) error = info.get('error', '?') raise ScriptError({ "type": ScriptError.LUA_CONVERT_ERROR, "error": error, "message": "Lua error: {!s}".format(error) }) self._print_instructions_used() self.on_result(res) return except lupa.LuaError as lua_ex: # import traceback # print(traceback.format_exc()) # Lua script raised an error self._print_instructions_used() self.log("[lua_runner] caught LuaError %r" % lua_ex) # this can raise a ScriptError self.on_lua_error(lua_ex) # ScriptError is not raised, construct it ourselves info = parse_error_message(lua_ex.args[0]) info.update({ "type": ScriptError.LUA_ERROR, "message": "Lua error: {!s}".format(lua_ex) }) raise ScriptError(info) if isinstance(cmd, AsyncCommand): cmd.bind(self, next(self._command_ids)) self.log("[lua_runner] executing {!r}".format(cmd)) self._waiting_for_result_id = cmd.id self.on_async_command(cmd) return if isinstance(cmd, PyResult): self.log("[lua_runner] got result {!r}".format(cmd)) else: self.log("[lua_runner] got non-command") self.result = cmd
def dispatch(self, cmd_id, *args): """ Execute the script """ args = args or None args_repr = truncated("{!r}".format(args), max_length=400, msg="...[long arguments truncated]") self.log("[lua_runner] dispatch cmd_id={}, args={}".format( cmd_id, args_repr)) self.log( "[lua_runner] arguments are for command %s, waiting for result of %s" % (cmd_id, self._waiting_for_result_id), min_level=3, ) if cmd_id != self._waiting_for_result_id: self.log("[lua_runner] skipping an out-of-order result {}".format( args_repr), min_level=1) return while True: try: args = args or None # Got arguments from an async command; send them to coroutine # and wait for the next async command. self.log("[lua_runner] send %s" % args_repr) cmd = self.coro.send(args) # cmd is a next async command args = None # don't re-send the same value cmd_repr = truncated(repr(cmd), max_length=400, msg='...[long result truncated]') self.log("[lua_runner] got {}".format(cmd_repr)) self._print_instructions_used() except StopIteration: # "main" coroutine is stopped; # previous result is a final result returned from "main" self.log("[lua_runner] returning result") try: res = self.lua.lua2python(self.result) except ValueError as e: # can't convert result to a Python object raise ScriptError({ "type": ScriptError.BAD_MAIN_ERROR, "message": "'main' returned bad result. {!s}".format(e.args[0]) }) self._print_instructions_used() self.on_result(res) return except lupa.LuaError as lua_ex: # Lua script raised an error self._print_instructions_used() self.log("[lua_runner] caught LuaError %r" % lua_ex) # this can raise a ScriptError self.on_lua_error(lua_ex) # ScriptError is not raised, construct it ourselves info = parse_error_message(lua_ex.args[0]) info.update({ "type": ScriptError.LUA_ERROR, "message": "Lua error: {!s}".format(lua_ex) }) raise ScriptError(info) if isinstance(cmd, AsyncCommand): cmd.bind(self, next(self._command_ids)) self.log("[lua_runner] executing {!r}".format(cmd)) self._waiting_for_result_id = cmd.id self.on_async_command(cmd) return elif isinstance(cmd, ImmediateResult): self.log("[lua_runner] got result {!r}".format(cmd)) args = cmd.value continue else: self.log("[lua_runner] got non-command") if isinstance(cmd, tuple): cmd = list(cmd) self.result = cmd
def dispatch(self, cmd_id, *args): """ Execute the script """ args = args or None args_repr = truncated("{!r}".format(args), max_length=400, msg="...[long arguments truncated]") self.log("[lua_runner] dispatch cmd_id={}, args={}".format(cmd_id, args_repr)) self.log( "[lua_runner] arguments are for command %s, waiting for result of %s" % (cmd_id, self._waiting_for_result_id), min_level=3, ) if cmd_id != self._waiting_for_result_id: self.log("[lua_runner] skipping an out-of-order result {}".format(args_repr), min_level=1) return while True: try: args = args or None # Got arguments from an async command; send them to coroutine # and wait for the next async command. self.log("[lua_runner] send %s" % args_repr) cmd = self.coro.send(self.lua.python2lua(args)) # cmd is a next async command args = None # don't re-send the same value cmd_repr = truncated(repr(cmd), max_length=400, msg='...[long result truncated]') self.log("[lua_runner] got {}".format(cmd_repr)) self._print_instructions_used() except StopIteration: # "main" coroutine is stopped; # previous result is a final result returned from "main" self.log("[lua_runner] returning result") try: res = self.lua.lua2python(self.result) except ValueError as e: # can't convert result to a Python object raise ScriptError({ "type": ScriptError.BAD_MAIN_ERROR, "message": "'main' returned bad result. {!s}".format( e.args[0] ) }) self._print_instructions_used() self.on_result(res) return except lupa.LuaError as lua_ex: # import traceback # print(traceback.format_exc()) # Lua script raised an error self._print_instructions_used() self.log("[lua_runner] caught LuaError %r" % lua_ex) # this can raise a ScriptError self.on_lua_error(lua_ex) # ScriptError is not raised, construct it ourselves info = parse_error_message(lua_ex.args[0]) info.update({ "type": ScriptError.LUA_ERROR, "message": "Lua error: {!s}".format(lua_ex) }) raise ScriptError(info) if isinstance(cmd, AsyncCommand): cmd.bind(self, next(self._command_ids)) self.log("[lua_runner] executing {!r}".format(cmd)) self._waiting_for_result_id = cmd.id self.on_async_command(cmd) return elif isinstance(cmd, ImmediateResult): self.log("[lua_runner] got result {!r}".format(cmd)) args = cmd.value continue else: self.log("[lua_runner] got non-command") if isinstance(cmd, tuple): cmd = list(cmd) self.result = cmd