py3embed.cpp 58 KB

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