pyembed.cpp 59 KB

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