pyembed.cpp 59 KB

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