pyembed.cpp 58 KB

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