pyembed.cpp 60 KB

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