@@ -74,47 +74,6 @@ def init_sandbox_dir():
7474 except Exception as e :
7575 maxkb_logger .error (f'Exception: { e } ' , exc_info = True )
7676
77- def exist_function (self , code_str , name ):
78- _id = str (uuid .uuid7 ())
79- python_paths = CONFIG .get_sandbox_python_package_paths ().split (',' )
80- set_run_user = f'os.setgid({ pwd .getpwnam (_run_user ).pw_gid } );os.setuid({ pwd .getpwnam (_run_user ).pw_uid } );' if _enable_sandbox else ''
81- _exec_code = f"""
82- try:
83- import os, sys, json
84- path_to_exclude = ['/opt/py3/lib/python3.11/site-packages', '/opt/maxkb-app/apps']
85- sys.path = [p for p in sys.path if p not in path_to_exclude]
86- sys.path += { python_paths }
87- locals_v={{}}
88- globals_v={{}}
89- { set_run_user }
90- os.environ.clear()
91- exec({ dedent (code_str )!a} , globals_v, locals_v)
92- exec_result=locals_v.__contains__('{ name } ')
93- sys.stdout.write("\\ n{ _id } :")
94- json.dump({{'code':200,'msg':'success','data':exec_result}}, sys.stdout, default=str)
95- except Exception as e:
96- if isinstance(e, MemoryError): e = Exception("Cannot allocate more memory: exceeded the limit of { _process_limit_mem_mb } MB.")
97- sys.stdout.write("\\ n{ _id } :")
98- json.dump({{'code':500,'msg':str(e),'data':False}}, sys.stdout, default=str)
99- sys.stdout.flush()
100- """
101- maxkb_logger .debug (f"Sandbox execute code: { _exec_code } " )
102- with tempfile .NamedTemporaryFile (mode = 'w' , suffix = '.py' , delete = True ) as f :
103- f .write (_exec_code )
104- f .flush ()
105- subprocess_result = self ._exec (f .name )
106- if subprocess_result .returncode != 0 :
107- raise Exception (subprocess_result .stderr or subprocess_result .stdout or "Unknown exception occurred" )
108- lines = subprocess_result .stdout .splitlines ()
109- result_line = [line for line in lines if line .startswith (_id )]
110- if not result_line :
111- maxkb_logger .error ("\n " .join (lines ))
112- raise Exception ("No result found." )
113- result = json .loads (result_line [- 1 ].split (":" , 1 )[1 ])
114- if result .get ('code' ) == 200 :
115- return result .get ('data' )
116- raise Exception (result .get ('msg' ))
117-
11877 def exec_code (self , code_str , keywords , function_name = None ):
11978 _id = str (uuid .uuid7 ())
12079 action_function = f'({ function_name !a} , locals_v.get({ function_name !a} ))' if function_name else 'locals_v.popitem()'
0 commit comments