py3embed.cpp 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #ifdef _WIN32
  14. // There's an issue with Python redefining ssize_t resulting in errors - hide their definition
  15. #define ssize_t python_ssize_t
  16. #include "Python.h"
  17. #undef ssize_t
  18. #else
  19. #define register
  20. #include "Python.h"
  21. #endif
  22. #include "platform.h"
  23. #include "frameobject.h"
  24. #include "jexcept.hpp"
  25. #include "jutil.hpp"
  26. #include "jthread.hpp"
  27. #include "jregexp.hpp"
  28. #include "hqlplugins.hpp"
  29. #include "deftype.hpp"
  30. #include "eclhelper.hpp"
  31. #include "eclrtl.hpp"
  32. #include "eclrtl_imp.hpp"
  33. #include "rtlds_imp.hpp"
  34. #include "rtlfield.hpp"
  35. #include "nbcd.hpp"
  36. #include "roxiemem.hpp"
  37. #include "enginecontext.hpp"
  38. #include <regex>
  39. #if PY_MAJOR_VERSION >=3
  40. #define Py_TPFLAGS_HAVE_ITER 0
  41. #endif
  42. static const char * compatibleVersions[] = {
  43. "Python3.x Embed Helper 1.0.0",
  44. NULL };
  45. static const char *version = "Python3.x Embed Helper 1.0.0";
  46. extern "C" DECL_EXPORT bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  47. {
  48. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  49. {
  50. ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
  51. pbx->compatibleVersions = compatibleVersions;
  52. }
  53. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  54. return false;
  55. pb->magicVersion = PLUGIN_VERSION;
  56. pb->version = version;
  57. pb->moduleName = "python3";
  58. pb->ECL = NULL;
  59. pb->flags = PLUGIN_MULTIPLE_VERSIONS;
  60. pb->description = "Python3.x Embed Helper";
  61. return true;
  62. }
  63. namespace py3embed {
  64. // Use class OwnedPyObject for any objects that are not 'borrowed references'
  65. // so that the appropriate Py_DECREF call is made when the OwnedPyObject goes
  66. // out of scope, even if the function returns prematurely (such as via an exception).
  67. // In particular, checkPythonError is a lot easier to call safely if this is used.
  68. class OwnedPyObject
  69. {
  70. PyObject *ptr;
  71. public:
  72. inline OwnedPyObject() : ptr(NULL) {}
  73. inline OwnedPyObject(PyObject *_ptr) : ptr(_ptr) {}
  74. inline ~OwnedPyObject() { if (ptr) Py_DECREF(ptr); }
  75. inline PyObject * get() const { return ptr; }
  76. inline PyObject * getClear() { PyObject *ret = ptr; ptr = NULL; return ret; }
  77. inline PyObject * operator -> () const { return ptr; }
  78. inline operator PyObject *() const { return ptr; }
  79. inline void clear() { if (ptr) Py_DECREF(ptr); ptr = NULL; }
  80. inline void setown(PyObject *_ptr) { clear(); ptr = _ptr; }
  81. inline void set(PyObject *_ptr) { if (_ptr) Py_INCREF(_ptr); clear(); ptr = _ptr; }
  82. inline PyObject *getLink() { if (ptr) Py_INCREF(ptr); return ptr;}
  83. inline PyObject **ref() { return &ptr; }
  84. };
  85. template <class X>
  86. class OwnedPyX
  87. {
  88. X *ptr;
  89. public:
  90. inline OwnedPyX<X>() : ptr(NULL) {}
  91. inline OwnedPyX<X>(X *_ptr) : ptr(_ptr) {}
  92. inline ~OwnedPyX<X>() { if (ptr) Py_DECREF(ptr); }
  93. inline X * get() const { return ptr; }
  94. inline X * getClear() { PyObject *ret = ptr; ptr = NULL; return ret; }
  95. inline X * operator -> () const { return ptr; }
  96. inline operator X *() const { return ptr; }
  97. inline void clear() { if (ptr) Py_DECREF(ptr); ptr = NULL; }
  98. inline void setown(X *_ptr) { clear(); ptr = _ptr; }
  99. inline void set(X *_ptr) { if (_ptr) Py_INCREF(_ptr); clear(); ptr = _ptr; }
  100. inline X *getLink() { if (ptr) Py_INCREF(ptr); return ptr;}
  101. inline X **ref() { return &ptr; }
  102. };
  103. __declspec(noreturn) static void failx(const char *msg, ...) __attribute__((format(printf, 1, 2), noreturn));
  104. static void failx(const char *message, ...)
  105. {
  106. va_list args;
  107. va_start(args,message);
  108. StringBuffer msg;
  109. msg.append("pyembed: ").valist_appendf(message,args);
  110. va_end(args);
  111. rtlFail(0, msg.str());
  112. }
  113. // call checkPythonError to throw an exception if Python error state is set
  114. static void checkPythonError()
  115. {
  116. PyObject* err = PyErr_Occurred();
  117. if (err)
  118. {
  119. OwnedPyObject pType, pValue, pTraceBack;
  120. PyErr_Fetch(pType.ref(), pValue.ref(), pTraceBack.ref());
  121. OwnedPyObject valStr = PyObject_Str(pValue);
  122. PyErr_Clear();
  123. assertex(PyUnicode_Check(valStr));
  124. const char *text = PyUnicode_AsUTF8AndSize(valStr, NULL);
  125. failx("%s", text);
  126. }
  127. }
  128. // The Python Global Interpreter Lock (GIL) won't know about C++-created threads, so we need to
  129. // call PyGILState_Ensure() and PyGILState_Release at the start and end of every function.
  130. // Wrapping them in a class like this ensures that the release always happens even if
  131. // the function exists prematurely
  132. class GILstateWrapper
  133. {
  134. PyGILState_STATE gstate;
  135. public:
  136. GILstateWrapper()
  137. {
  138. gstate = PyGILState_Ensure();
  139. }
  140. ~GILstateWrapper()
  141. {
  142. PyGILState_Release(gstate);
  143. }
  144. };
  145. // There is a singleton PythonThreadContext per thread. This allows us to
  146. // ensure that we can make repeated calls to a Python function efficiently.
  147. // Note that we assume that a thread is not shared between workunits/queries
  148. class PythonThreadContext
  149. {
  150. public:
  151. PyThreadState *threadState;
  152. public:
  153. PythonThreadContext()
  154. {
  155. threadState = PyEval_SaveThread();
  156. lrutype = NULL;
  157. }
  158. ~PythonThreadContext()
  159. {
  160. PyEval_RestoreThread(threadState);
  161. script.clear();
  162. module.clear();
  163. lru.clear();
  164. }
  165. void addManifestFiles(ICodeContext *codeCtx);
  166. PyObject * importFunction(ICodeContext *codeCtx, size32_t lenChars, const char *utf)
  167. {
  168. size32_t bytes = rtlUtf8Size(lenChars, utf);
  169. StringBuffer text(bytes, utf);
  170. if (!prevtext || strcmp(text, prevtext) != 0)
  171. {
  172. prevtext.clear();
  173. // Name should be in the form module.function
  174. const char *funcname = strrchr(text, '.');
  175. if (!funcname)
  176. rtlFail(0, "pyembed: Expected module.function");
  177. addManifestFiles(codeCtx);
  178. StringBuffer modname(funcname-text, text);
  179. funcname++; // skip the '.'
  180. // If the modname is preceded by a path, add it temporarily to the Python path before importing
  181. bool addedPath = false;
  182. PyObject *sysPath = PySys_GetObject((char *) "path");
  183. if (!sysPath)
  184. rtlFail(0, "pyembed: sys.path returned null");
  185. OwnedPyObject newpath;
  186. const char *pathsep = strrchr(modname, PATHSEPCHAR);
  187. if (pathsep)
  188. {
  189. StringBuffer path(pathsep-modname, modname);
  190. modname.remove(0, 1+pathsep-modname);
  191. newpath.setown(PyUnicode_FromString(path));
  192. Py_ssize_t found = PySequence_Index(sysPath, newpath);
  193. if (found == (Py_ssize_t)-1)
  194. {
  195. PyErr_Clear();
  196. PyList_Insert(sysPath, 0, newpath);
  197. addedPath = true;
  198. }
  199. checkPythonError();
  200. }
  201. module.setown(PyImport_ImportModule(modname));
  202. checkPythonError();
  203. if (pathsep)
  204. {
  205. // Immediately remove the temporary location from the path (if we added it),
  206. // and the just-imported module from the system cache,
  207. // otherwise other code that imports similar name from other location fails.
  208. if (addedPath)
  209. {
  210. Py_ssize_t found = PySequence_Index(sysPath, newpath); // Very likely to be zero, but should we assume? You could argue we should restore path to state prior to import, whatever
  211. if (found != (Py_ssize_t)-1)
  212. PySequence_DelItem(sysPath, found);
  213. else
  214. PyErr_Clear();
  215. }
  216. PyObject *sysModules = PySys_GetObject((char *) "modules");
  217. DBGLOG("Unloading module %s", modname.str());
  218. OwnedPyObject pyMod = PyUnicode_FromString(modname);
  219. PyDict_DelItem(sysModules, pyMod);
  220. checkPythonError();
  221. }
  222. PyObject *dict = PyModule_GetDict(module); // this is a borrowed reference and does not need to be released
  223. script.set(PyDict_GetItemString(dict, funcname));
  224. checkPythonError();
  225. if (!script || !PyCallable_Check(script))
  226. rtlFail(0, "pyembed: Object is not callable");
  227. prevtext.set(text);
  228. }
  229. return script.getLink();
  230. }
  231. PyObject *compileEmbeddedScript(ICodeContext *codeCtx, size32_t lenChars, const char *utf, const char *argstring);
  232. PyObject *getNamedTupleType(const RtlTypeInfo *type);
  233. private:
  234. GILstateWrapper GILState;
  235. OwnedPyObject module;
  236. OwnedPyObject script;
  237. OwnedPyObject lru;
  238. const RtlTypeInfo *lrutype;
  239. StringAttr prevtext;
  240. bool manifestAdded = false;
  241. };
  242. static __thread PythonThreadContext* threadContext; // We reuse per thread, for speed
  243. static bool releaseContext(bool isPooled)
  244. {
  245. if (threadContext)
  246. {
  247. delete threadContext;
  248. threadContext = NULL;
  249. }
  250. return false;
  251. }
  252. // Use a global object to ensure that the Python interpreter is initialized on main thread
  253. static HINSTANCE keepLoadedHandle;
  254. static class Python3xGlobalState
  255. {
  256. public:
  257. Python3xGlobalState()
  258. {
  259. pythonLibrary = (HINSTANCE) 0;
  260. #ifndef _WIN32
  261. // If Py_Initialize is called when stdin is set to a directory, it calls exit()
  262. // We don't want that to happen - just disable Python support in such situations
  263. struct stat sb;
  264. if (fstat(fileno(stdin), &sb) == 0 && S_ISDIR(sb.st_mode))
  265. {
  266. initialized = false;
  267. return;
  268. }
  269. StringBuffer py2modname;
  270. if (findLoadedModule(py2modname, "libpy2embed."))
  271. {
  272. initialized = false;
  273. multiPython = true;
  274. return;
  275. }
  276. #endif
  277. #ifndef _WIN32
  278. // We need to ensure all symbols in the python3.x so are loaded - due to bugs in some distro's python installations
  279. // However this will likely break python2.
  280. // Therefore on systems where both are present, do NOT do this - people using centos systems that suffer from issue
  281. // https://bugs.centos.org/view.php?id=6063 will need to choose which version of python plugin to install but not both
  282. StringBuffer modname;
  283. if (findLoadedModule(modname, "libpython3."))
  284. pythonLibrary = dlopen(modname.str(), RTLD_NOW|RTLD_GLOBAL);
  285. #endif
  286. // Initialize the Python Interpreter
  287. Py_Initialize();
  288. const wchar_t *argv[] = { nullptr };
  289. PySys_SetArgvEx(0, (wchar_t **) argv, 0);
  290. PyEval_InitThreads();
  291. preservedScopes.setown(PyDict_New());
  292. tstate = PyEval_SaveThread();
  293. skipPythonCleanup = queryEnvironmentConf().getPropBool("skipPythonCleanup", true);
  294. initialized = true;
  295. }
  296. ~Python3xGlobalState()
  297. {
  298. if (threadContext)
  299. delete threadContext; // The one on the main thread won't get picked up by the thread hook mechanism
  300. threadContext = NULL;
  301. if (initialized && !skipPythonCleanup)
  302. {
  303. PyEval_RestoreThread(tstate);
  304. // Finish the Python Interpreter
  305. namedtuple.clear();
  306. namedtupleTypes.clear();
  307. compiledScripts.clear();
  308. preservedScopes.clear();
  309. Py_Finalize();
  310. if (pythonLibrary)
  311. FreeSharedObject(pythonLibrary);
  312. }
  313. else
  314. {
  315. // Need to avoid releasing the associated py objects when these members destructors are called.
  316. namedtuple.getClear();
  317. namedtupleTypes.getClear();
  318. compiledScripts.getClear();
  319. preservedScopes.getClear();
  320. }
  321. }
  322. void checkInitialized()
  323. {
  324. if (multiPython)
  325. rtlFail(0, "Python3 not initialized as Python2 already loaded");
  326. else if (!initialized)
  327. rtlFail(0, "Python3 not initialized");
  328. }
  329. bool isInitialized()
  330. {
  331. return initialized;
  332. }
  333. PyFrameObject *pushDummyFrame()
  334. {
  335. PyThreadState* threadstate = PyThreadState_GET();
  336. if (!threadstate->frame)
  337. {
  338. OwnedPyObject globals = PyDict_New();
  339. OwnedPyObject locals = PyDict_New();
  340. OwnedPyX<PyCodeObject> code = PyCode_NewEmpty("<dummy>","<dummy>", 0);
  341. checkPythonError();
  342. PyFrameObject *frame = PyFrame_New(threadstate, code, globals, locals);
  343. checkPythonError();
  344. threadstate->frame = frame;
  345. return frame;
  346. }
  347. return NULL;
  348. }
  349. void popDummyFrame(PyFrameObject *frame)
  350. {
  351. PyThreadState* threadstate = PyThreadState_GET();
  352. if (threadstate->frame == frame)
  353. threadstate->frame = NULL;
  354. }
  355. PyObject *getActivityContextTupleType()
  356. {
  357. // Note - we do not need (and must not have) a lock protecting this. It is protected by the Python GIL,
  358. // and if we add our own lock we are liable to deadlock as the code within Py_CompileStringFlags may
  359. // temporarily release then re-acquire the GIL.
  360. if (!activityContextTupleType)
  361. activityContextTupleType.setown(getNamedTupleType("isLocal,numSlaves,numStrands,slave,strand"));
  362. return activityContextTupleType.get();
  363. }
  364. PyObject *getNamedTupleType(const char *names)
  365. {
  366. // It seems the customized namedtuple types leak, and they are slow to create, so take care to reuse
  367. // Note - we do not need (and must not have) a lock protecting this. It is protected by the Python GIL,
  368. // and if we add our own lock we are liable to deadlock as the code within Py_CompileStringFlags may
  369. // temporarily release then re-acquire the GIL.
  370. if (!namedtuple)
  371. {
  372. namedtupleTypes.setown(PyDict_New());
  373. OwnedPyObject pName = PyUnicode_FromString("collections");
  374. OwnedPyObject collections = PyImport_Import(pName);
  375. checkPythonError();
  376. namedtuple.setown(PyObject_GetAttrString(collections, "namedtuple"));
  377. checkPythonError();
  378. assertex(PyCallable_Check(namedtuple));
  379. }
  380. OwnedPyObject pnames = PyUnicode_FromString(names);
  381. OwnedPyObject mynamedtupletype;
  382. checkPythonError();
  383. mynamedtupletype.set(PyDict_GetItem(namedtupleTypes, pnames)); // NOTE - returns borrowed reference
  384. if (!mynamedtupletype)
  385. {
  386. OwnedPyObject recname = PyUnicode_FromString("namerec"); // MORE - do we care what the name is?
  387. OwnedPyObject ntargs = PyTuple_Pack(2, recname.get(), pnames.get());
  388. checkPythonError();
  389. OwnedPyX<PyFrameObject> frame = pushDummyFrame();
  390. mynamedtupletype.setown(PyObject_CallObject(namedtuple, ntargs));
  391. popDummyFrame(frame);
  392. checkPythonError();
  393. PyDict_SetItem(namedtupleTypes, pnames, mynamedtupletype);
  394. }
  395. checkPythonError();
  396. assertex(PyCallable_Check(mynamedtupletype));
  397. return mynamedtupletype.getClear();
  398. }
  399. PyObject *getNamedTupleType(const RtlTypeInfo *type)
  400. {
  401. const RtlFieldInfo * const *fields = type->queryFields();
  402. if (!fields && type->queryChildType())
  403. fields = type->queryChildType()->queryFields();
  404. assertex(fields);
  405. StringBuffer names;
  406. while (*fields)
  407. {
  408. const RtlFieldInfo *field = *fields;
  409. if (names.length())
  410. names.append(',');
  411. names.append(field->name);
  412. fields++;
  413. }
  414. return getNamedTupleType(names.str());
  415. }
  416. StringBuffer & reformatCompilerError(StringBuffer &ret, const char *error, unsigned leadingLines)
  417. {
  418. // Errors from compiler tend to look like this:
  419. // "('invalid syntax', ('<embed>', 3, 12, ' sfsf ss fs dfs f sfs\n'))"
  420. const char pattern [] = "\\('(.*)', \\('.*', ([0-9]*), ([0-9]*), (.*)\\)\\)";
  421. // Hopefully there are no embedded quotes in the error message or the filename
  422. rtlCompiledStrRegex r;
  423. size32_t outlen;
  424. char * out = NULL;
  425. r.setPattern(pattern, false);
  426. r->replace(outlen, out, strlen(error), error, 2, "$2");
  427. if (outlen < strlen(error))
  428. {
  429. unsigned line = atoi(out);
  430. rtlFree(out);
  431. if (line > leadingLines)
  432. line--;
  433. r->replace(outlen, out, strlen(error), error, 13, ", $3): $1: $4");
  434. ret.appendf("(%d", line);
  435. }
  436. ret.append(outlen, out);
  437. rtlFree(out);
  438. return ret;
  439. }
  440. PyObject *compileScript(const char *text, const char *parameters)
  441. {
  442. // Note - we do not need (and must not have) a lock protecting this. It is protected by the Python GIL,
  443. // and if we add our own lock we are liable to deadlock as the code within Py_CompileStringFlags may
  444. // temporarily release then re-acquire the GIL.
  445. if (!compiledScripts)
  446. compiledScripts.setown(PyDict_New());
  447. OwnedPyObject code;
  448. code.set(PyDict_GetItemString(compiledScripts, text));
  449. if (!code)
  450. {
  451. unsigned leadingLines = (unsigned) -1; // Number of lines from input that have not been offset by 1 line in input to compiler
  452. code.setown(Py_CompileString(text, "", Py_eval_input)); // try compiling as simple expression...
  453. if (!code)
  454. {
  455. PyErr_Clear();
  456. PyCompilerFlags flags = { PyCF_SOURCE_IS_UTF8 };
  457. code.setown(Py_CompileStringFlags(text, "<embed>", Py_file_input, &flags)); // try compiling as global code
  458. if (!code)
  459. {
  460. PyErr_Clear();
  461. StringBuffer wrapped;
  462. wrapPythonText(wrapped, text, parameters, leadingLines);
  463. code.setown(Py_CompileStringFlags(wrapped, "<embed>", Py_file_input, &flags)); // try compiling as a function body
  464. }
  465. }
  466. PyObject* err = PyErr_Occurred();
  467. if (err)
  468. {
  469. OwnedPyObject pType, pValue, pTraceBack;
  470. PyErr_Fetch(pType.ref(), pValue.ref(), pTraceBack.ref());
  471. OwnedPyObject valStr = PyObject_Str(pValue);
  472. PyErr_Clear();
  473. // We reformat the error message a little, to make it more helpful
  474. assertex(PyUnicode_Check(valStr));
  475. const char *errtext = PyUnicode_AsUTF8AndSize(valStr, NULL);
  476. StringBuffer msg;
  477. reformatCompilerError(msg, errtext, leadingLines);
  478. rtlFail(0, msg.str());
  479. }
  480. if (code)
  481. PyDict_SetItemString(compiledScripts, text, code);
  482. }
  483. return code.getClear();
  484. }
  485. PyObject *getNamedScope(const char *key, bool &isNew)
  486. {
  487. if (!preservedScopes)
  488. preservedScopes.setown(PyDict_New());
  489. OwnedPyObject scope;
  490. scope.set(PyDict_GetItemString(preservedScopes, key));
  491. if (!scope)
  492. {
  493. scope.setown(PyDict_New());
  494. PyDict_SetItemString(preservedScopes, key, scope);
  495. isNew = true;
  496. }
  497. else
  498. isNew = false;
  499. return scope.getClear();
  500. }
  501. void releaseNamedScope(const char *key)
  502. {
  503. if (preservedScopes)
  504. {
  505. PyDict_DelItemString(preservedScopes, key);
  506. PyErr_Clear(); // Should be present, but ignore the error if it is not
  507. }
  508. }
  509. static void unregister(const char *key);
  510. static void removePath(const char *file);
  511. protected:
  512. static StringBuffer &wrapPythonText(StringBuffer &out, const char *in, const char *params, unsigned &leadingLines)
  513. {
  514. // Complicated by needing to keep future import lines outside defined function
  515. // Per python spec, a future statement must appear near the top of the module. The only lines that can appear before a future statement are:
  516. // the module docstring (if any),
  517. // comments,
  518. // blank lines, and
  519. // other future statements.
  520. // We don't attempt to parse the python to spot these - instead, we pull all lines up to and including the last future statement out to the global scope.
  521. // Because this is a little unsophisticated it will be fooled by code that includes things that look like future statements inside multiline strings.
  522. // I don't care.
  523. StringArray lines;
  524. lines.appendList(in, "\n", false);
  525. RegExpr expr("^ *from +__future__ +import ");
  526. leadingLines = 0;
  527. ForEachItemIn(idx, lines)
  528. {
  529. if (expr.find(lines.item(idx)))
  530. leadingLines = idx+1;
  531. }
  532. for (unsigned leadingLine = 0; leadingLine < leadingLines; leadingLine++)
  533. out.append(lines.item(leadingLine)).append('\n');
  534. out.appendf("def __user__(%s):\n", params);
  535. for (unsigned line = leadingLines; line < lines.length(); line++)
  536. out.append(" ").append(lines.item(line)).append('\n');
  537. out.appendf("__result__ = __user__(%s)\n", params);
  538. return out;
  539. }
  540. PyThreadState *tstate = nullptr;
  541. bool initialized = false;
  542. bool multiPython = false;
  543. bool skipPythonCleanup = true; // Tensorflow seems to often lockup in the python cleanup process.
  544. HINSTANCE pythonLibrary = 0;
  545. OwnedPyObject namedtuple; // collections.namedtuple
  546. OwnedPyObject namedtupleTypes; // dictionary of return values from namedtuple()
  547. OwnedPyObject compiledScripts; // dictionary of previously compiled scripts
  548. OwnedPyObject preservedScopes; // dictionary of preserved scopes
  549. OwnedPyObject activityContextTupleType; // type used for activity context
  550. } globalState;
  551. MODULE_INIT(INIT_PRIORITY_STANDARD)
  552. {
  553. // Make sure we are never unloaded (as Python may crash if we are)
  554. // we do this by doing a dynamic load of the pyembed library
  555. #ifdef _WIN32
  556. HINSTANCE me = GetModuleHandle("py3embed");
  557. if (me)
  558. {
  559. char helperLibraryName[_MAX_PATH];
  560. ::GetModuleFileName(me, helperLibraryName, _MAX_PATH);
  561. if (strstr(helperLibraryName, "py3embed"))
  562. {
  563. HINSTANCE h = LoadSharedObject(helperLibraryName, false, false);
  564. DBGLOG("LoadSharedObject returned %p", h);
  565. }
  566. }
  567. #else
  568. StringBuffer modname;
  569. if (findLoadedModule(modname, "libpy3embed"))
  570. {
  571. keepLoadedHandle = LoadSharedObject(modname, false, false);
  572. }
  573. #endif
  574. return true;
  575. }
  576. static void checkThreadContext()
  577. {
  578. if (!threadContext)
  579. {
  580. globalState.checkInitialized();
  581. threadContext = new PythonThreadContext;
  582. addThreadTermFunc(releaseContext);
  583. }
  584. }
  585. void PythonThreadContext::addManifestFiles(ICodeContext *codeCtx)
  586. {
  587. if (codeCtx && !manifestAdded) // MORE - this assumes we never reuse a thread for a different workunit, without the thread termination hooks having been called
  588. {
  589. manifestAdded = true;
  590. IEngineContext *engine = codeCtx->queryEngineContext();
  591. if (engine)
  592. {
  593. const StringArray &manifestModules = engine->queryManifestFiles("pyzip");
  594. if (manifestModules.length())
  595. {
  596. PyObject *sysPath = PySys_GetObject((char *) "path");
  597. if (!sysPath)
  598. rtlFail(0, "pyembed: sys.path returned null");
  599. ForEachItemIn(idx, manifestModules)
  600. {
  601. const char *path = manifestModules.item(idx);
  602. DBGLOG("Manifest zip %s", path);
  603. OwnedPyObject newPath = PyUnicode_FromString(path);
  604. PyList_Insert(sysPath, 0, newPath);
  605. checkPythonError();
  606. engine->onTermination(Python3xGlobalState::removePath, manifestModules.item(idx), true);
  607. }
  608. }
  609. }
  610. }
  611. }
  612. PyObject *PythonThreadContext::getNamedTupleType(const RtlTypeInfo *type)
  613. {
  614. if (!lru || (type!=lrutype))
  615. {
  616. lru.setown(globalState.getNamedTupleType(type));
  617. lrutype = type;
  618. }
  619. return lru.getLink();
  620. }
  621. PyObject *PythonThreadContext::compileEmbeddedScript(ICodeContext *codeCtx, size32_t lenChars, const char *utf, const char *argstring)
  622. {
  623. size32_t bytes = rtlUtf8Size(lenChars, utf);
  624. StringBuffer text(bytes, utf);
  625. if (!prevtext || strcmp(text, prevtext) != 0)
  626. {
  627. prevtext.clear();
  628. text.stripChar('\r');
  629. addManifestFiles(codeCtx);
  630. script.setown(globalState.compileScript(text, argstring));
  631. prevtext.set(utf, bytes);
  632. }
  633. return script.getLink();
  634. }
  635. // Conversions from Python objects to ECL data
  636. __declspec(noreturn) static void typeError(const char *expected, const RtlFieldInfo *field) __attribute__((noreturn));
  637. static void typeError(const char *expected, const RtlFieldInfo *field)
  638. {
  639. VStringBuffer msg("pyembed: type mismatch - %s expected", expected);
  640. if (field)
  641. msg.appendf(" for field %s", field->name);
  642. else
  643. msg.appendf(" for return value");
  644. rtlFail(0, msg.str());
  645. }
  646. static bool getBooleanResult(const RtlFieldInfo *field, PyObject *obj)
  647. {
  648. if (obj && obj != Py_None)
  649. {
  650. if (PyBool_Check(obj))
  651. return obj == Py_True;
  652. }
  653. typeError("boolean", field);
  654. }
  655. static void getDataResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, void * &result)
  656. {
  657. if (obj && obj != Py_None && PyByteArray_Check(obj))
  658. rtlStrToDataX(chars, result, PyByteArray_Size(obj), PyByteArray_AsString(obj));
  659. else
  660. typeError("bytearray", field);
  661. }
  662. static double getRealResult(const RtlFieldInfo *field, PyObject *obj)
  663. {
  664. if (obj && obj != Py_None)
  665. {
  666. if (PyFloat_Check(obj))
  667. return PyFloat_AsDouble(obj);
  668. }
  669. typeError("real", field);
  670. }
  671. static __int64 getSignedResult(const RtlFieldInfo *field, PyObject *obj)
  672. {
  673. if (obj && obj != Py_None)
  674. {
  675. if (PyLong_Check(obj))
  676. return (__int64) PyLong_AsLongLong(obj);
  677. }
  678. typeError("integer", field);
  679. }
  680. static unsigned __int64 getUnsignedResult(const RtlFieldInfo *field, PyObject *obj)
  681. {
  682. if (obj && obj != Py_None)
  683. {
  684. if (PyLong_Check(obj))
  685. return (unsigned __int64) PyLong_AsUnsignedLongLong(obj);
  686. }
  687. typeError("integer", field);
  688. }
  689. static void getStringResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, char * &result)
  690. {
  691. if (obj && obj != Py_None)
  692. {
  693. if (PyUnicode_Check(obj))
  694. {
  695. OwnedPyObject temp_bytes = PyUnicode_AsEncodedString(obj, ASCII_LIKE_CODEPAGE, "ignore");
  696. checkPythonError();
  697. const char * text = PyBytes_AsString(temp_bytes);
  698. checkPythonError();
  699. size_t lenBytes = PyBytes_Size(temp_bytes);
  700. rtlStrToStrX(chars, result, lenBytes, text);
  701. }
  702. else if (PyBytes_Check(obj))
  703. {
  704. const char * text = PyBytes_AsString(obj);
  705. checkPythonError();
  706. size_t lenBytes = PyBytes_Size(obj);
  707. rtlStrToStrX(chars, result, lenBytes, text);
  708. }
  709. return;
  710. }
  711. typeError("string", field);
  712. }
  713. static void getUTF8Result(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, char * &result)
  714. {
  715. if (obj && obj != Py_None && PyUnicode_Check(obj))
  716. {
  717. Py_ssize_t lenBytes;
  718. const char *text = PyUnicode_AsUTF8AndSize(obj, &lenBytes);
  719. checkPythonError();
  720. size32_t numchars = rtlUtf8Length(lenBytes, text);
  721. rtlUtf8ToUtf8X(chars, result, numchars, text);
  722. }
  723. else
  724. typeError("unicode string", field);
  725. }
  726. static void getSetResult(PyObject *obj, bool & isAllResult, size32_t & resultBytes, void * & result, int elemType, size32_t elemSize)
  727. {
  728. // MORE - should probably recode to use the getResultDataset mechanism
  729. if (!obj || obj == Py_None || (!PyList_Check(obj) && !PySet_Check(obj)))
  730. rtlFail(0, "pyembed: type mismatch - list or set expected");
  731. rtlRowBuilder out;
  732. size32_t outBytes = 0;
  733. byte *outData = NULL;
  734. OwnedPyObject iter = PyObject_GetIter(obj);
  735. OwnedPyObject elem;
  736. for (elem.setown(PyIter_Next(iter)); elem != NULL; elem.setown(PyIter_Next(iter)))
  737. {
  738. if (elemSize != UNKNOWN_LENGTH)
  739. {
  740. out.ensureAvailable(outBytes + elemSize);
  741. outData = out.getbytes() + outBytes;
  742. outBytes += elemSize;
  743. }
  744. switch ((type_t) elemType)
  745. {
  746. case type_int:
  747. rtlWriteInt(outData, py3embed::getSignedResult(NULL, elem), elemSize);
  748. break;
  749. case type_unsigned:
  750. rtlWriteInt(outData, py3embed::getUnsignedResult(NULL, elem), elemSize);
  751. break;
  752. case type_real:
  753. if (elemSize == sizeof(double))
  754. * (double *) outData = (double) py3embed::getRealResult(NULL, elem);
  755. else
  756. {
  757. assertex(elemSize == sizeof(float));
  758. * (float *) outData = (float) py3embed::getRealResult(NULL, elem);
  759. }
  760. break;
  761. case type_boolean:
  762. assertex(elemSize == sizeof(bool));
  763. * (bool *) outData = py3embed::getBooleanResult(NULL, elem);
  764. break;
  765. case type_string:
  766. case type_varstring:
  767. {
  768. if (!PyUnicode_Check(elem))
  769. rtlFail(0, "pyembed: type mismatch - return value in list was not a STRING");
  770. OwnedPyObject temp_bytes = PyUnicode_AsEncodedString(elem, ASCII_LIKE_CODEPAGE, "ignore");
  771. checkPythonError();
  772. const char * text = PyBytes_AsString(temp_bytes);
  773. checkPythonError();
  774. size_t lenBytes = PyBytes_Size(temp_bytes);
  775. if (elemSize == UNKNOWN_LENGTH)
  776. {
  777. if (elemType == type_string)
  778. {
  779. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  780. outData = out.getbytes() + outBytes;
  781. * (size32_t *) outData = lenBytes;
  782. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  783. outBytes += lenBytes + sizeof(size32_t);
  784. }
  785. else
  786. {
  787. out.ensureAvailable(outBytes + lenBytes + 1);
  788. outData = out.getbytes() + outBytes;
  789. rtlStrToVStr(0, outData, lenBytes, text);
  790. outBytes += lenBytes + 1;
  791. }
  792. }
  793. else
  794. {
  795. if (elemType == type_string)
  796. rtlStrToStr(elemSize, outData, lenBytes, text);
  797. else
  798. rtlStrToVStr(elemSize, outData, lenBytes, text); // Fixed size null terminated strings... weird.
  799. }
  800. break;
  801. }
  802. case type_unicode:
  803. case type_utf8:
  804. {
  805. if (!PyUnicode_Check(elem))
  806. rtlFail(0, "pyembed: type mismatch - return value in list was not a unicode STRING");
  807. Py_ssize_t lenBytes;
  808. const char *text = PyUnicode_AsUTF8AndSize(elem, &lenBytes);
  809. checkPythonError();
  810. size32_t numchars = rtlUtf8Length(lenBytes, text);
  811. if (elemType == type_utf8)
  812. {
  813. assertex (elemSize == UNKNOWN_LENGTH);
  814. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  815. outData = out.getbytes() + outBytes;
  816. * (size32_t *) outData = numchars;
  817. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  818. outBytes += lenBytes + sizeof(size32_t);
  819. }
  820. else
  821. {
  822. if (elemSize == UNKNOWN_LENGTH)
  823. {
  824. out.ensureAvailable(outBytes + numchars*sizeof(UChar) + sizeof(size32_t));
  825. outData = out.getbytes() + outBytes;
  826. // You can't assume that number of chars in utf8 matches number in unicode16 ...
  827. size32_t numchars16;
  828. rtlDataAttr unicode16;
  829. rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
  830. * (size32_t *) outData = numchars16;
  831. rtlUnicodeToUnicode(numchars16, (UChar *) (outData+sizeof(size32_t)), numchars16, unicode16.getustr());
  832. outBytes += numchars16*sizeof(UChar) + sizeof(size32_t);
  833. }
  834. else
  835. rtlUtf8ToUnicode(elemSize / sizeof(UChar), (UChar *) outData, numchars, text);
  836. }
  837. break;
  838. }
  839. case type_data:
  840. {
  841. if (!PyByteArray_Check(elem))
  842. rtlFail(0, "pyembed: type mismatch - return value in list was not a bytearray");
  843. size_t lenBytes = PyByteArray_Size(elem); // Could check does not overflow size32_t
  844. const char *data = PyByteArray_AsString(elem);
  845. if (elemSize == UNKNOWN_LENGTH)
  846. {
  847. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  848. outData = out.getbytes() + outBytes;
  849. * (size32_t *) outData = lenBytes;
  850. rtlStrToData(lenBytes, outData+sizeof(size32_t), lenBytes, data);
  851. outBytes += lenBytes + sizeof(size32_t);
  852. }
  853. else
  854. rtlStrToData(elemSize, outData, lenBytes, data);
  855. break;
  856. }
  857. default:
  858. rtlFail(0, "pyembed: type mismatch - unsupported return type");
  859. break;
  860. }
  861. checkPythonError();
  862. }
  863. isAllResult = false;
  864. resultBytes = outBytes;
  865. result = out.detachdata();
  866. }
  867. static void getUnicodeResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, UChar * &result)
  868. {
  869. if (obj && obj != Py_None && PyUnicode_Check(obj))
  870. {
  871. Py_ssize_t lenBytes;
  872. const char *text = PyUnicode_AsUTF8AndSize(obj, &lenBytes);
  873. checkPythonError();
  874. size32_t numchars = rtlUtf8Length(lenBytes, text);
  875. rtlUtf8ToUnicodeX(chars, result, numchars, text);
  876. }
  877. else
  878. typeError("unicode string", field);
  879. }
  880. // A PythonRowBuilder object is used to construct an ECL row from a python object
  881. class PythonRowBuilder : public CInterfaceOf<IFieldSource>
  882. {
  883. public:
  884. PythonRowBuilder(PyObject *_row)
  885. : iter(NULL), elem(NULL), named(false)
  886. {
  887. pushback.set(_row);
  888. }
  889. virtual bool getBooleanResult(const RtlFieldInfo *field)
  890. {
  891. nextField(field);
  892. return py3embed::getBooleanResult(field, elem);
  893. }
  894. virtual void getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result)
  895. {
  896. nextField(field);
  897. py3embed::getDataResult(field, elem, len, result);
  898. }
  899. virtual double getRealResult(const RtlFieldInfo *field)
  900. {
  901. nextField(field);
  902. return py3embed::getRealResult(field, elem);
  903. }
  904. virtual __int64 getSignedResult(const RtlFieldInfo *field)
  905. {
  906. nextField(field);
  907. return py3embed::getSignedResult(field, elem);
  908. }
  909. virtual unsigned __int64 getUnsignedResult(const RtlFieldInfo *field)
  910. {
  911. nextField(field);
  912. return py3embed::getUnsignedResult(field, elem);
  913. }
  914. virtual void getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result)
  915. {
  916. nextField(field);
  917. py3embed::getStringResult(field, elem, chars, result);
  918. }
  919. virtual void getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result)
  920. {
  921. nextField(field);
  922. py3embed::getUTF8Result(field, elem, chars, result);
  923. }
  924. virtual void getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result)
  925. {
  926. nextField(field);
  927. py3embed::getUnicodeResult(field, elem, chars, result);
  928. }
  929. virtual void getDecimalResult(const RtlFieldInfo *field, Decimal &value)
  930. {
  931. nextField(field);
  932. double ret = py3embed::getRealResult(field, elem);
  933. value.setReal(ret);
  934. }
  935. virtual void processBeginSet(const RtlFieldInfo * field, bool &isAll)
  936. {
  937. nextField(field);
  938. isAll = false; // No concept of an 'all' set in Python
  939. if (!elem || elem == Py_None || (!PyList_Check(elem) && !PySet_Check(elem)))
  940. typeError("list or set", field);
  941. push();
  942. }
  943. virtual bool processNextSet(const RtlFieldInfo * field)
  944. {
  945. nextField(NULL);
  946. pushback.setown(elem.getClear());
  947. return pushback != NULL;
  948. }
  949. virtual void processBeginDataset(const RtlFieldInfo * field)
  950. {
  951. nextField(field);
  952. if (!PyList_Check(elem))
  953. typeError("list", field);
  954. push();
  955. }
  956. virtual void processBeginRow(const RtlFieldInfo * field)
  957. {
  958. // Expect to see a tuple here, or possibly (if the ECL record has a single field), an arbitrary scalar object
  959. // If it's a tuple, we push it onto our stack as the active object
  960. nextField(field);
  961. if (!PyTuple_Check(elem))
  962. {
  963. if (countFields(field->type->queryFields())==1)
  964. {
  965. // Python doesn't seem to support the concept of a tuple containing a single element.
  966. // If we are expecting a single field in our row, then the 'tuple' layer will be missing
  967. elem.setown(PyTuple_Pack(1, elem.get()));
  968. }
  969. else
  970. typeError("tuple", field);
  971. }
  972. push();
  973. }
  974. virtual bool processNextRow(const RtlFieldInfo * field)
  975. {
  976. nextField(NULL);
  977. pushback.setown(elem.getClear());
  978. return pushback != NULL;
  979. }
  980. virtual void processEndSet(const RtlFieldInfo * field)
  981. {
  982. pop();
  983. }
  984. virtual void processEndDataset(const RtlFieldInfo * field)
  985. {
  986. pop();
  987. }
  988. virtual void processEndRow(const RtlFieldInfo * field)
  989. {
  990. pop();
  991. }
  992. protected:
  993. void pop()
  994. {
  995. iter.setown((PyObject *) iterStack.popGet());
  996. parent.setown((PyObject *) parentStack.popGet());
  997. named = namedStack.popGet();
  998. elem.clear();
  999. }
  1000. void push()
  1001. {
  1002. iterStack.append(iter.getClear());
  1003. parentStack.append(parent.getClear());
  1004. namedStack.append(named);
  1005. parent.set(elem);
  1006. iter.setown(PyObject_GetIter(elem));
  1007. named = isNamedTuple(elem);
  1008. elem.clear();
  1009. }
  1010. bool isNamedTuple(PyObject *obj)
  1011. {
  1012. return PyObject_HasAttrString((PyObject *) obj->ob_type, "_fields");
  1013. }
  1014. void nextField(const RtlFieldInfo * field)
  1015. {
  1016. if (pushback)
  1017. elem.setown(pushback.getClear());
  1018. else if (field && named) // If it's named tuple, expect to always resolve fields by name, not position
  1019. {
  1020. elem.setown(PyObject_GetAttrString(parent, field->name));
  1021. }
  1022. else if (iter)
  1023. elem.setown(PyIter_Next(iter));
  1024. else
  1025. elem = NULL;
  1026. checkPythonError();
  1027. }
  1028. OwnedPyObject iter;
  1029. OwnedPyObject pushback;
  1030. OwnedPyObject elem;
  1031. OwnedPyObject parent;
  1032. bool named;
  1033. PointerArray iterStack;
  1034. PointerArray parentStack;
  1035. BoolArray namedStack;
  1036. };
  1037. static size32_t getRowResult(PyObject *result, ARowBuilder &builder)
  1038. {
  1039. PythonRowBuilder pyRowBuilder(result);
  1040. const RtlTypeInfo *typeInfo = builder.queryAllocator()->queryOutputMeta()->queryTypeInfo();
  1041. assertex(typeInfo);
  1042. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  1043. return typeInfo->build(builder, 0, &dummyField, pyRowBuilder);
  1044. }
  1045. // A PythonNamedTupleBuilder object is used to construct a Python named tuple from an ECL row
  1046. class PythonNamedTupleBuilder : public CInterfaceOf<IFieldProcessor>
  1047. {
  1048. public:
  1049. PythonNamedTupleBuilder(PythonThreadContext *_sharedCtx, const RtlFieldInfo *_outerRow)
  1050. : outerRow(_outerRow), sharedCtx(_sharedCtx)
  1051. {
  1052. }
  1053. virtual void processString(unsigned len, const char *value, const RtlFieldInfo * field)
  1054. {
  1055. addArg(PyUnicode_FromStringAndSize(value, len));
  1056. }
  1057. virtual void processBool(bool value, const RtlFieldInfo * field)
  1058. {
  1059. addArg(PyBool_FromLong(value ? 1 : 0));
  1060. }
  1061. virtual void processData(unsigned len, const void *value, const RtlFieldInfo * field)
  1062. {
  1063. addArg(PyByteArray_FromStringAndSize((const char *) value, len));
  1064. }
  1065. virtual void processInt(__int64 value, const RtlFieldInfo * field)
  1066. {
  1067. addArg(PyLong_FromLongLong(value));
  1068. }
  1069. virtual void processUInt(unsigned __int64 value, const RtlFieldInfo * field)
  1070. {
  1071. addArg(PyLong_FromUnsignedLongLong(value));
  1072. }
  1073. virtual void processReal(double value, const RtlFieldInfo * field)
  1074. {
  1075. addArg(PyFloat_FromDouble(value));
  1076. }
  1077. virtual void processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  1078. {
  1079. Decimal val;
  1080. val.setDecimal(digits, precision, value);
  1081. addArg(PyFloat_FromDouble(val.getReal()));
  1082. }
  1083. virtual void processUDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  1084. {
  1085. Decimal val;
  1086. val.setUDecimal(digits, precision, value);
  1087. addArg(PyFloat_FromDouble(val.getReal()));
  1088. }
  1089. virtual void processUnicode(unsigned len, const UChar *value, const RtlFieldInfo * field)
  1090. {
  1091. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  1092. unsigned unicodeChars;
  1093. rtlDataAttr unicode;
  1094. rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), len, value);
  1095. processUtf8(unicodeChars, unicode.getstr(), field);
  1096. }
  1097. virtual void processQString(unsigned len, const char *value, const RtlFieldInfo * field)
  1098. {
  1099. size32_t charCount;
  1100. rtlDataAttr text;
  1101. rtlQStrToStrX(charCount, text.refstr(), len, value);
  1102. processString(charCount, text.getstr(), field);
  1103. }
  1104. virtual void processUtf8(unsigned len, const char *value, const RtlFieldInfo * field)
  1105. {
  1106. size32_t sizeBytes = rtlUtf8Size(len, value);
  1107. PyObject *vval = PyUnicode_FromStringAndSize(value, sizeBytes); // NOTE - requires size in bytes not chars
  1108. checkPythonError();
  1109. addArg(vval);
  1110. }
  1111. virtual bool processBeginSet(const RtlFieldInfo * field, unsigned numElements, bool isAll, const byte *data)
  1112. {
  1113. push();
  1114. if (isAll)
  1115. rtlFail(0, "pyembed: ALL sets are not supported");
  1116. return true;
  1117. }
  1118. virtual bool processBeginDataset(const RtlFieldInfo * field, unsigned numRows)
  1119. {
  1120. push();
  1121. return true;
  1122. }
  1123. virtual bool processBeginRow(const RtlFieldInfo * field)
  1124. {
  1125. if (field != outerRow)
  1126. push();
  1127. return true;
  1128. }
  1129. virtual void processEndSet(const RtlFieldInfo * field)
  1130. {
  1131. pop();
  1132. }
  1133. virtual void processEndDataset(const RtlFieldInfo * field)
  1134. {
  1135. pop();
  1136. }
  1137. virtual void processEndRow(const RtlFieldInfo * field)
  1138. {
  1139. if (field != outerRow)
  1140. {
  1141. args.setown(getTuple(field->type));
  1142. pop();
  1143. }
  1144. }
  1145. PyObject *getTuple(const RtlTypeInfo *type)
  1146. {
  1147. OwnedPyObject mynamedtupletype = sharedCtx ? sharedCtx->getNamedTupleType(type) : globalState.getNamedTupleType(type);
  1148. OwnedPyObject argsTuple = PyList_AsTuple(args);
  1149. OwnedPyObject mynamedtuple = PyObject_CallObject(mynamedtupletype, argsTuple); // Creates a namedtuple from the supplied tuple
  1150. checkPythonError();
  1151. return mynamedtuple.getClear();
  1152. }
  1153. protected:
  1154. void push()
  1155. {
  1156. stack.append(args.getClear());
  1157. args.setown(PyList_New(0));
  1158. }
  1159. void pop()
  1160. {
  1161. OwnedPyObject arg = args.getClear();
  1162. args.setown((PyObject *) stack.popGet());
  1163. addArg(arg.getClear());
  1164. }
  1165. void addArg(PyObject *arg)
  1166. {
  1167. if (!args)
  1168. {
  1169. args.setown(PyList_New(0));
  1170. }
  1171. PyList_Append(args, arg);
  1172. Py_DECREF(arg);
  1173. }
  1174. OwnedPyObject args;
  1175. PointerArray stack;
  1176. const RtlFieldInfo *outerRow;
  1177. PythonThreadContext *sharedCtx;
  1178. };
  1179. //----------------------------------------------------------------------
  1180. // GILBlock ensures the we hold the Python "Global interpreter lock" for the appropriate duration
  1181. class GILBlock
  1182. {
  1183. public:
  1184. GILBlock(PyThreadState * &_state) : state(_state)
  1185. {
  1186. PyEval_RestoreThread(state);
  1187. }
  1188. ~GILBlock()
  1189. {
  1190. state = PyEval_SaveThread();
  1191. }
  1192. private:
  1193. PyThreadState * &state;
  1194. };
  1195. // GILUnblock ensures the we release the Python "Global interpreter lock" for the appropriate duration
  1196. class GILUnblock
  1197. {
  1198. public:
  1199. GILUnblock()
  1200. {
  1201. state = PyEval_SaveThread();
  1202. }
  1203. ~GILUnblock()
  1204. {
  1205. PyEval_RestoreThread(state);
  1206. }
  1207. private:
  1208. PyThreadState *state;
  1209. };
  1210. //----------------------------------------------------------------------
  1211. // Wrap an IRowStream into a Python generator
  1212. struct ECLDatasetIterator
  1213. {
  1214. PyObject_HEAD;
  1215. const RtlTypeInfo *typeInfo; // Not linked (or linkable)
  1216. IRowStream * val; // Linked
  1217. };
  1218. PyObject* ECLDatasetIterator_iter(PyObject *self)
  1219. {
  1220. Py_INCREF(self);
  1221. return self;
  1222. }
  1223. void ECLDatasetIterator_dealloc(PyObject *self)
  1224. {
  1225. ECLDatasetIterator *p = (ECLDatasetIterator *)self;
  1226. if (p->val)
  1227. {
  1228. GILUnblock b;
  1229. p->val->stop();
  1230. ::Release(p->val);
  1231. p->val = NULL;
  1232. }
  1233. self->ob_type->tp_free(self);
  1234. }
  1235. PyObject* ECLDatasetIterator_iternext(PyObject *self)
  1236. {
  1237. ECLDatasetIterator *p = (ECLDatasetIterator *)self;
  1238. roxiemem::OwnedConstRoxieRow nextRow;
  1239. if (p->val)
  1240. {
  1241. GILUnblock b;
  1242. nextRow.setown(p->val->ungroupedNextRow());
  1243. if (!nextRow)
  1244. {
  1245. p->val->stop();
  1246. ::Release(p->val);
  1247. p->val = NULL;
  1248. }
  1249. }
  1250. if (p->val)
  1251. {
  1252. RtlFieldStrInfo dummyField("<row>", NULL, p->typeInfo);
  1253. PythonNamedTupleBuilder tupleBuilder(NULL, &dummyField);
  1254. const byte *brow = (const byte *) nextRow.get();
  1255. p->typeInfo->process(brow, brow, &dummyField, tupleBuilder);
  1256. return tupleBuilder.getTuple(p->typeInfo);
  1257. }
  1258. else
  1259. {
  1260. // If we get here, it's EOF
  1261. PyErr_SetNone(PyExc_StopIteration);
  1262. return NULL;
  1263. }
  1264. }
  1265. static PyTypeObject ECLDatasetIteratorType =
  1266. {
  1267. PyVarObject_HEAD_INIT(NULL, 0)
  1268. "ECLDatasetIterator._MyIter", /*tp_name*/
  1269. sizeof(ECLDatasetIterator), /*tp_basicsize*/
  1270. 0, /*tp_itemsize*/
  1271. ECLDatasetIterator_dealloc, /*tp_dealloc*/
  1272. 0, /*tp_print*/
  1273. 0, /*tp_getattr*/
  1274. 0, /*tp_setattr*/
  1275. 0, /*tp_compare*/
  1276. 0, /*tp_repr*/
  1277. 0, /*tp_as_number*/
  1278. 0, /*tp_as_sequence*/
  1279. 0, /*tp_as_mapping*/
  1280. 0, /*tp_hash */
  1281. 0, /*tp_call*/
  1282. 0, /*tp_str*/
  1283. 0, /*tp_getattro*/
  1284. 0, /*tp_setattro*/
  1285. 0, /*tp_as_buffer*/
  1286. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags: tell python to use tp_iter and tp_iternext fields. */
  1287. "ECL dataset iterator object.", /* tp_doc */
  1288. 0, /* tp_traverse */
  1289. 0, /* tp_clear */
  1290. 0, /* tp_richcompare */
  1291. 0, /* tp_weaklistoffset */
  1292. ECLDatasetIterator_iter, /* tp_iter: __iter__() method */
  1293. ECLDatasetIterator_iternext /* tp_iternext: next() method */
  1294. };
  1295. static PyObject *createECLDatasetIterator(const RtlTypeInfo *_typeInfo, IRowStream * _val)
  1296. {
  1297. ECLDatasetIteratorType.tp_new = PyType_GenericNew;
  1298. if (PyType_Ready(&ECLDatasetIteratorType) < 0) return NULL;
  1299. ECLDatasetIterator *p = PyObject_New(ECLDatasetIterator, &ECLDatasetIteratorType);
  1300. if (!p)
  1301. {
  1302. checkPythonError();
  1303. rtlFail(0, "pyembed: failed to create dataset iterator");
  1304. }
  1305. p->typeInfo = _typeInfo;
  1306. p->val = _val;
  1307. return (PyObject *)p;
  1308. }
  1309. //-----------------------------------------------------
  1310. void Python3xGlobalState::unregister(const char *key)
  1311. {
  1312. checkThreadContext();
  1313. GILBlock b(threadContext->threadState);
  1314. globalState.releaseNamedScope(key);
  1315. }
  1316. void Python3xGlobalState::removePath(const char *path)
  1317. {
  1318. checkThreadContext();
  1319. GILBlock b(threadContext->threadState);
  1320. // Remove a manifest file from the Python path, and remove from sys.modules any modules loaded from that location
  1321. PyObject *sysPath = PySys_GetObject((char *) "path");
  1322. if (sysPath)
  1323. {
  1324. OwnedPyObject newPath = PyUnicode_FromString(path);
  1325. Py_ssize_t found = PySequence_Index(sysPath, newPath);
  1326. if (found != (Py_ssize_t)-1)
  1327. {
  1328. PySequence_DelItem(sysPath, found);
  1329. checkPythonError();
  1330. }
  1331. else
  1332. PyErr_Clear();
  1333. PyObject *sysModules = PySys_GetObject((char *) "modules");
  1334. checkPythonError();
  1335. OwnedPyObject values = PyDict_Values(sysModules);
  1336. checkPythonError();
  1337. Py_ssize_t len = PyList_Size(values);
  1338. size_t pathLen = strlen(path);
  1339. for (Py_ssize_t idx = 0; idx < len; idx++)
  1340. {
  1341. PyObject *module = PyList_GetItem(values, idx);
  1342. if (PyObject_HasAttrString(module, "__file__"))
  1343. {
  1344. OwnedPyObject file = PyObject_GetAttrString(module, "__file__");
  1345. if (file && PyUnicode_Check(file))
  1346. {
  1347. const char *fileName = PyUnicode_AsUTF8AndSize(file, NULL);
  1348. if (strncmp(fileName, path, pathLen)==0)
  1349. {
  1350. OwnedPyObject modname = PyObject_GetAttrString(module, "__name__");
  1351. DBGLOG("Unloading module %s", fileName);
  1352. PyDict_DelItem(sysModules, modname);
  1353. }
  1354. }
  1355. }
  1356. checkPythonError();
  1357. }
  1358. }
  1359. }
  1360. // A Python function that returns a dataset will return a PythonRowStream object that can be
  1361. // interrogated to return each row of the result in turn
  1362. class PythonRowStream : public CInterfaceOf<IRowStream>
  1363. {
  1364. public:
  1365. PythonRowStream(PyObject *result, IEngineRowAllocator *_resultAllocator)
  1366. : resultIterator(NULL)
  1367. {
  1368. // NOTE - the caller should already have the GIL lock before creating me
  1369. if (!result || result == Py_None)
  1370. typeError("list or generator", NULL);
  1371. resultIterator.setown(PyObject_GetIter(result)); // We allow anything that is iterable to be returned for a row stream
  1372. checkPythonError();
  1373. resultAllocator.set(_resultAllocator);
  1374. }
  1375. ~PythonRowStream()
  1376. {
  1377. if (resultIterator)
  1378. {
  1379. checkThreadContext();
  1380. GILBlock b(threadContext->threadState);
  1381. resultIterator.clear();
  1382. }
  1383. }
  1384. virtual const void *nextRow()
  1385. {
  1386. checkThreadContext();
  1387. GILBlock b(threadContext->threadState);
  1388. if (!resultIterator)
  1389. return NULL;
  1390. OwnedPyObject row = PyIter_Next(resultIterator);
  1391. checkPythonError();
  1392. if (!row)
  1393. return NULL;
  1394. RtlDynamicRowBuilder rowBuilder(resultAllocator);
  1395. size32_t len = py3embed::getRowResult(row, rowBuilder);
  1396. checkPythonError();
  1397. return rowBuilder.finalizeRowClear(len);
  1398. }
  1399. virtual void stop()
  1400. {
  1401. checkThreadContext();
  1402. GILBlock b(threadContext->threadState);
  1403. resultAllocator.clear();
  1404. resultIterator.clear();
  1405. }
  1406. protected:
  1407. Linked<IEngineRowAllocator> resultAllocator;
  1408. OwnedPyObject resultIterator;
  1409. };
  1410. // Each call to a Python function will use a new Python3xEmbedFunctionContext object
  1411. // This takes care of ensuring that the Python GIL is locked while we are executing python code,
  1412. // and released when we are not
  1413. class Python3xEmbedContextBase : public CInterfaceOf<IEmbedFunctionContext>
  1414. {
  1415. public:
  1416. Python3xEmbedContextBase(PythonThreadContext *_sharedCtx, ICodeContext *_codeCtx)
  1417. : sharedCtx(_sharedCtx), codeCtx(_codeCtx)
  1418. {
  1419. PyEval_RestoreThread(sharedCtx->threadState);
  1420. }
  1421. virtual void setActivityOptions(const IThorActivityContext *ctx)
  1422. {
  1423. OwnedPyObject mynamedtupletype = globalState.getActivityContextTupleType();
  1424. OwnedPyObject args = PyTuple_New(5);
  1425. OwnedPyObject isLocal;
  1426. isLocal.set(ctx->isLocal() ? Py_True : Py_False);
  1427. PyTuple_SET_ITEM((PyTupleObject *) args.get(), 0, isLocal.getClear());
  1428. PyTuple_SET_ITEM((PyTupleObject *) args.get(), 1, PyLong_FromLong(ctx->numSlaves()));
  1429. PyTuple_SET_ITEM((PyTupleObject *) args.get(), 2, PyLong_FromLong(ctx->numStrands()));
  1430. PyTuple_SET_ITEM((PyTupleObject *) args.get(), 3, PyLong_FromLong(ctx->querySlave()));
  1431. PyTuple_SET_ITEM((PyTupleObject *) args.get(), 4, PyLong_FromLong(ctx->queryStrand()));
  1432. OwnedPyObject activityTuple = PyObject_CallObject(mynamedtupletype, args); // Creates a namedtuple from the supplied tuple
  1433. checkPythonError();
  1434. PyDict_SetItemString(locals, "__activity__", activityTuple.getClear());
  1435. checkPythonError();
  1436. }
  1437. void setScopes(ICodeContext *codeCtx, const char *_options)
  1438. {
  1439. locals.setown(PyDict_New());
  1440. StringArray options;
  1441. options.appendList(_options, ",");
  1442. StringBuffer scopeKey;
  1443. const char *scopeKey2 = nullptr;
  1444. bool registerCallback = false;
  1445. bool wuidScope = false;
  1446. IEngineContext *engine = nullptr;
  1447. ForEachItemIn(idx, options)
  1448. {
  1449. const char *opt = options.item(idx);
  1450. const char *val = strchr(opt, '=');
  1451. if (val)
  1452. {
  1453. StringBuffer optName(val-opt, opt);
  1454. val++;
  1455. if (strieq(optName, "globalscope"))
  1456. scopeKey2 = val;
  1457. else if (strieq(optName, "persist"))
  1458. {
  1459. if (scopeKey.length())
  1460. failx("persist option specified more than once");
  1461. if (strieq(val, "global"))
  1462. scopeKey.append("global");
  1463. else if (strieq(val, "workunit"))
  1464. {
  1465. engine = codeCtx->queryEngineContext();
  1466. wuidScope = true;
  1467. if (!engine)
  1468. failx("Persist mode 'workunit' not supported here");
  1469. }
  1470. else if (strieq(val, "query"))
  1471. {
  1472. engine = codeCtx->queryEngineContext();
  1473. wuidScope = false;
  1474. if (!engine)
  1475. failx("Persist mode 'query' not supported here");
  1476. }
  1477. else
  1478. failx("Unrecognized persist mode %s", val);
  1479. }
  1480. else
  1481. failx("Unrecognized option %s", optName.str());
  1482. }
  1483. else
  1484. failx("Unrecognized option %s", opt);
  1485. }
  1486. if (engine)
  1487. engine->getQueryId(scopeKey, wuidScope);
  1488. if (scopeKey2)
  1489. scopeKey.append(':').append(scopeKey2);
  1490. if (scopeKey.length())
  1491. {
  1492. bool isNew;
  1493. globals.setown(globalState.getNamedScope(scopeKey, isNew));
  1494. if (isNew && engine)
  1495. engine->onTermination(Python3xGlobalState::unregister, scopeKey.str(), wuidScope);
  1496. }
  1497. else
  1498. globals.setown(PyDict_New());
  1499. PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); // required for import to work
  1500. }
  1501. ~Python3xEmbedContextBase()
  1502. {
  1503. // We need to clear these before calling savethread, or we won't own the GIL
  1504. locals.clear();
  1505. globals.clear();
  1506. result.clear();
  1507. script.clear();
  1508. sharedCtx->threadState = PyEval_SaveThread();
  1509. }
  1510. virtual bool getBooleanResult()
  1511. {
  1512. return py3embed::getBooleanResult(NULL, result);
  1513. }
  1514. virtual void getDataResult(size32_t &__chars, void * &__result)
  1515. {
  1516. py3embed::getDataResult(NULL, result, __chars, __result);
  1517. }
  1518. virtual double getRealResult()
  1519. {
  1520. return py3embed::getRealResult(NULL, result);
  1521. }
  1522. virtual __int64 getSignedResult()
  1523. {
  1524. return py3embed::getSignedResult(NULL, result);
  1525. }
  1526. virtual unsigned __int64 getUnsignedResult()
  1527. {
  1528. return py3embed::getUnsignedResult(NULL, result);
  1529. }
  1530. virtual void getStringResult(size32_t &__chars, char * &__result)
  1531. {
  1532. py3embed::getStringResult(NULL, result, __chars, __result);
  1533. }
  1534. virtual void getUTF8Result(size32_t &__chars, char * &__result)
  1535. {
  1536. py3embed::getUTF8Result(NULL, result, __chars, __result);
  1537. }
  1538. virtual void getUnicodeResult(size32_t &__chars, UChar * &__result)
  1539. {
  1540. py3embed::getUnicodeResult(NULL, result, __chars, __result);
  1541. }
  1542. virtual void getSetResult(bool & __isAllResult, size32_t & __resultBytes, void * & __result, int elemType, size32_t elemSize)
  1543. {
  1544. py3embed::getSetResult(result, __isAllResult, __resultBytes, __result, elemType, elemSize);
  1545. }
  1546. virtual IRowStream *getDatasetResult(IEngineRowAllocator * _resultAllocator)
  1547. {
  1548. return new PythonRowStream(result, _resultAllocator);
  1549. }
  1550. virtual byte * getRowResult(IEngineRowAllocator * _resultAllocator)
  1551. {
  1552. RtlDynamicRowBuilder rowBuilder(_resultAllocator);
  1553. size32_t len = py3embed::getRowResult(result, rowBuilder);
  1554. return (byte *) rowBuilder.finalizeRowClear(len);
  1555. }
  1556. virtual size32_t getTransformResult(ARowBuilder & builder)
  1557. {
  1558. return py3embed::getRowResult(result, builder);
  1559. }
  1560. virtual void bindBooleanParam(const char *name, bool val)
  1561. {
  1562. addArg(name, PyBool_FromLong(val ? 1 : 0));
  1563. }
  1564. virtual void bindDataParam(const char *name, size32_t len, const void *val)
  1565. {
  1566. addArg(name, PyByteArray_FromStringAndSize((const char *) val, len));
  1567. }
  1568. virtual void bindFloatParam(const char *name, float val)
  1569. {
  1570. addArg(name, PyFloat_FromDouble((double) val));
  1571. }
  1572. virtual void bindRealParam(const char *name, double val)
  1573. {
  1574. addArg(name, PyFloat_FromDouble(val));
  1575. }
  1576. virtual void bindSignedSizeParam(const char *name, int size, __int64 val)
  1577. {
  1578. addArg(name, PyLong_FromLongLong(val));
  1579. }
  1580. virtual void bindSignedParam(const char *name, __int64 val)
  1581. {
  1582. addArg(name, PyLong_FromLongLong(val));
  1583. }
  1584. virtual void bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val)
  1585. {
  1586. addArg(name, PyLong_FromUnsignedLongLong(val));
  1587. }
  1588. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  1589. {
  1590. addArg(name, PyLong_FromUnsignedLongLong(val));
  1591. }
  1592. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  1593. {
  1594. addArg(name, PyUnicode_Decode(val, len, ASCII_LIKE_CODEPAGE, "ignore"));
  1595. }
  1596. virtual void bindVStringParam(const char *name, const char *val)
  1597. {
  1598. addArg(name, PyUnicode_FromString(val));
  1599. }
  1600. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  1601. {
  1602. size32_t sizeBytes = rtlUtf8Size(chars, val);
  1603. PyObject *vval = PyUnicode_FromStringAndSize(val, sizeBytes); // NOTE - requires size in bytes not chars
  1604. checkPythonError();
  1605. addArg(name, vval);
  1606. }
  1607. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  1608. {
  1609. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  1610. unsigned unicodeChars;
  1611. char *unicode;
  1612. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  1613. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  1614. PyObject *vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  1615. checkPythonError();
  1616. addArg(name, vval);
  1617. rtlFree(unicode);
  1618. }
  1619. virtual void bindSetParam(const char *name, int elemType, size32_t elemSize, bool isAll, size32_t totalBytes, const void *setData)
  1620. {
  1621. if (isAll)
  1622. rtlFail(0, "pyembed: Cannot pass ALL");
  1623. type_t typecode = (type_t) elemType;
  1624. const byte *inData = (const byte *) setData;
  1625. const byte *endData = inData + totalBytes;
  1626. OwnedPyObject vval = PyList_New(0);
  1627. while (inData < endData)
  1628. {
  1629. OwnedPyObject thisElem;
  1630. size32_t thisSize = elemSize;
  1631. switch (typecode)
  1632. {
  1633. case type_int:
  1634. thisElem.setown(PyLong_FromLongLong(rtlReadInt(inData, elemSize)));
  1635. break;
  1636. case type_unsigned:
  1637. thisElem.setown(PyLong_FromUnsignedLongLong(rtlReadUInt(inData, elemSize)));
  1638. break;
  1639. case type_varstring:
  1640. {
  1641. size32_t numChars = strlen((const char *) inData);
  1642. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, numChars));
  1643. if (elemSize == UNKNOWN_LENGTH)
  1644. thisSize = numChars + 1;
  1645. break;
  1646. }
  1647. case type_string:
  1648. if (elemSize == UNKNOWN_LENGTH)
  1649. {
  1650. thisSize = * (size32_t *) inData;
  1651. inData += sizeof(size32_t);
  1652. }
  1653. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, thisSize));
  1654. break;
  1655. case type_real:
  1656. if (elemSize == sizeof(double))
  1657. thisElem.setown(PyFloat_FromDouble(* (double *) inData));
  1658. else
  1659. thisElem.setown(PyFloat_FromDouble(* (float *) inData));
  1660. break;
  1661. case type_boolean:
  1662. assertex(elemSize == sizeof(bool));
  1663. thisElem.setown(PyBool_FromLong(*(bool*)inData ? 1 : 0));
  1664. break;
  1665. case type_unicode:
  1666. {
  1667. if (elemSize == UNKNOWN_LENGTH)
  1668. {
  1669. thisSize = (* (size32_t *) inData) * sizeof(UChar); // NOTE - it's in chars...
  1670. inData += sizeof(size32_t);
  1671. }
  1672. unsigned unicodeChars;
  1673. rtlDataAttr unicode;
  1674. rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), thisSize / sizeof(UChar), (const UChar *) inData);
  1675. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode.getstr());
  1676. thisElem.setown(PyUnicode_FromStringAndSize(unicode.getstr(), sizeBytes)); // NOTE - requires size in bytes not chars
  1677. checkPythonError();
  1678. break;
  1679. }
  1680. case type_utf8:
  1681. {
  1682. assertex (elemSize == UNKNOWN_LENGTH);
  1683. size32_t numChars = * (size32_t *) inData;
  1684. inData += sizeof(size32_t);
  1685. thisSize = rtlUtf8Size(numChars, inData);
  1686. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, thisSize)); // NOTE - requires size in bytes not chars
  1687. break;
  1688. }
  1689. case type_data:
  1690. if (elemSize == UNKNOWN_LENGTH)
  1691. {
  1692. thisSize = * (size32_t *) inData;
  1693. inData += sizeof(size32_t);
  1694. }
  1695. thisElem.setown(PyByteArray_FromStringAndSize((const char *) inData, thisSize));
  1696. break;
  1697. }
  1698. checkPythonError();
  1699. inData += thisSize;
  1700. PyList_Append(vval, thisElem);
  1701. }
  1702. addArg(name, vval.getLink());
  1703. }
  1704. virtual void bindRowParam(const char *name, IOutputMetaData & metaVal, const byte *val) override
  1705. {
  1706. const RtlTypeInfo *typeInfo = metaVal.queryTypeInfo();
  1707. assertex(typeInfo);
  1708. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  1709. PythonNamedTupleBuilder tupleBuilder(sharedCtx, &dummyField);
  1710. typeInfo->process(val, val, &dummyField, tupleBuilder); // Creates a tuple from the incoming ECL row
  1711. addArg(name, tupleBuilder.getTuple(typeInfo));
  1712. }
  1713. virtual void bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val)
  1714. {
  1715. addArg(name, createECLDatasetIterator(metaVal.queryTypeInfo(), LINK(val)));
  1716. }
  1717. protected:
  1718. virtual void addArg(const char *name, PyObject *arg) = 0;
  1719. PythonThreadContext *sharedCtx = nullptr;
  1720. ICodeContext *codeCtx = nullptr;
  1721. OwnedPyObject locals;
  1722. OwnedPyObject globals;
  1723. OwnedPyObject result;
  1724. OwnedPyObject script;
  1725. };
  1726. class Python3xEmbedScriptContext : public Python3xEmbedContextBase
  1727. {
  1728. public:
  1729. Python3xEmbedScriptContext(PythonThreadContext *_sharedCtx, ICodeContext *_codeCtx)
  1730. : Python3xEmbedContextBase(_sharedCtx, _codeCtx)
  1731. {
  1732. }
  1733. ~Python3xEmbedScriptContext()
  1734. {
  1735. }
  1736. virtual IInterface *bindParamWriter(IInterface *esdl, const char *esdlservice, const char *esdltype, const char *name)
  1737. {
  1738. return NULL;
  1739. }
  1740. virtual void paramWriterCommit(IInterface *writer)
  1741. {
  1742. }
  1743. virtual void writeResult(IInterface *esdl, const char *esdlservice, const char *esdltype, IInterface *writer)
  1744. {
  1745. }
  1746. virtual void importFunction(size32_t lenChars, const char *text)
  1747. {
  1748. throwUnexpected();
  1749. }
  1750. virtual void compileEmbeddedScript(size32_t lenChars, const char *utf)
  1751. {
  1752. script.setown(sharedCtx->compileEmbeddedScript(codeCtx, lenChars, utf, argstring));
  1753. }
  1754. virtual void loadCompiledScript(size32_t chars, const void *_script) override
  1755. {
  1756. throwUnexpected();
  1757. }
  1758. virtual void enter() override {}
  1759. virtual void reenter(ICodeContext *codeCtx) override {}
  1760. virtual void exit() override {}
  1761. virtual void setActivityOptions(const IThorActivityContext *ctx) override
  1762. {
  1763. Python3xEmbedContextBase::setActivityOptions(ctx);
  1764. argstring.append("__activity__");
  1765. }
  1766. virtual void callFunction()
  1767. {
  1768. result.setown(PyEval_EvalCode(script.get(), globals, locals));
  1769. checkPythonError();
  1770. if (!result || result == Py_None)
  1771. result.set(PyDict_GetItemString(globals, "__result__"));
  1772. if (!result || result == Py_None)
  1773. result.set(PyDict_GetItemString(locals, "__result__"));
  1774. }
  1775. void setargs(const char *args)
  1776. {
  1777. argstring.set(args);
  1778. }
  1779. protected:
  1780. virtual void addArg(const char *name, PyObject *arg)
  1781. {
  1782. if (!arg)
  1783. return;
  1784. if (argstring.length())
  1785. argstring.append(',');
  1786. argstring.append(name);
  1787. if (script)
  1788. PyDict_SetItemString(globals, name, arg); // Back compatibility - if compiler did not recognize the prebind flag, we need to use globals
  1789. else
  1790. PyDict_SetItemString(locals, name, arg);
  1791. Py_DECREF(arg);
  1792. checkPythonError();
  1793. }
  1794. StringBuffer argstring;
  1795. };
  1796. class Python3xEmbedImportContext : public Python3xEmbedContextBase
  1797. {
  1798. public:
  1799. Python3xEmbedImportContext(PythonThreadContext *_sharedCtx, ICodeContext *_codeCtx)
  1800. : Python3xEmbedContextBase(_sharedCtx, _codeCtx)
  1801. {
  1802. argcount = 0;
  1803. }
  1804. ~Python3xEmbedImportContext()
  1805. {
  1806. }
  1807. virtual IInterface *bindParamWriter(IInterface *esdl, const char *esdlservice, const char *esdltype, const char *name)
  1808. {
  1809. return NULL;
  1810. }
  1811. virtual void paramWriterCommit(IInterface *writer)
  1812. {
  1813. }
  1814. virtual void writeResult(IInterface *esdl, const char *esdlservice, const char *esdltype, IInterface *writer)
  1815. {
  1816. }
  1817. virtual void importFunction(size32_t lenChars, const char *utf)
  1818. {
  1819. script.setown(sharedCtx->importFunction(codeCtx, lenChars, utf));
  1820. }
  1821. virtual void compileEmbeddedScript(size32_t len, const char *text)
  1822. {
  1823. throwUnexpected();
  1824. }
  1825. virtual void loadCompiledScript(size32_t chars, const void *_script) override
  1826. {
  1827. throwUnexpected();
  1828. }
  1829. virtual void enter() override {}
  1830. virtual void reenter(ICodeContext *codeCtx) override {}
  1831. virtual void exit() override {}
  1832. virtual void callFunction()
  1833. {
  1834. result.setown(PyObject_CallObject(script, args));
  1835. checkPythonError();
  1836. }
  1837. private:
  1838. virtual void addArg(const char *name, PyObject *arg)
  1839. {
  1840. if (argcount)
  1841. _PyTuple_Resize(args.ref(), argcount+1);
  1842. else
  1843. args.setown(PyTuple_New(1));
  1844. PyTuple_SET_ITEM((PyTupleObject *) args.get(), argcount++, arg); // Note - 'steals' the arg reference
  1845. }
  1846. int argcount;
  1847. OwnedPyObject args;
  1848. };
  1849. class Python3xEmbedContext : public CInterfaceOf<IEmbedContext>
  1850. {
  1851. public:
  1852. virtual IEmbedFunctionContext *createFunctionContext(unsigned flags, const char *options) override
  1853. {
  1854. return createFunctionContextEx(nullptr, nullptr, flags, options);
  1855. }
  1856. virtual IEmbedFunctionContext *createFunctionContextEx(ICodeContext * ctx, const IThorActivityContext *activityCtx, unsigned flags, const char *options) override
  1857. {
  1858. checkThreadContext();
  1859. Owned<Python3xEmbedContextBase> ret;
  1860. if (flags & EFimport)
  1861. ret.setown(new Python3xEmbedImportContext(threadContext, ctx));
  1862. else
  1863. ret.setown(new Python3xEmbedScriptContext(threadContext, ctx));
  1864. ret->setScopes(ctx, options);
  1865. if (activityCtx)
  1866. ret->setActivityOptions(activityCtx);
  1867. return ret.getClear();
  1868. }
  1869. virtual IEmbedServiceContext *createServiceContext(const char *service, unsigned flags, const char *options) override
  1870. {
  1871. throwUnexpected();
  1872. }
  1873. };
  1874. extern DECL_EXPORT IEmbedContext* getEmbedContext()
  1875. {
  1876. return new Python3xEmbedContext;
  1877. }
  1878. extern DECL_EXPORT void syntaxCheck(size32_t & __lenResult, char * & __result, const char *funcname, size32_t charsBody, const char * body, const char *argNames, const char *compilerOptions, const char *persistOptions)
  1879. {
  1880. StringBuffer result;
  1881. if (globalState.isInitialized())
  1882. {
  1883. // NOTE - compilation of a script does not actually resolve imports - so the fact that the manifest is not on the path does not matter
  1884. // This does mean that many errors cannot be caught until runtime, but that's Python for you...
  1885. try
  1886. {
  1887. checkThreadContext();
  1888. Owned<Python3xEmbedScriptContext> ctx = new Python3xEmbedScriptContext(threadContext, nullptr);
  1889. ctx->setargs(argNames);
  1890. ctx->compileEmbeddedScript(charsBody, body);
  1891. }
  1892. catch (IException *E)
  1893. {
  1894. StringBuffer msg;
  1895. result.append(E->errorMessage(msg));
  1896. E->Release();
  1897. }
  1898. }
  1899. __lenResult = result.length();
  1900. __result = result.detach();
  1901. }
  1902. } // namespace