pyembed.cpp 49 KB

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