pyembed.cpp 53 KB

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