pyembed.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464
  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. code.setown(Py_CompileString(wrapped, "<embed>", Py_file_input));
  309. }
  310. checkPythonError();
  311. if (code)
  312. PyDict_SetItemString(compiledScripts, text, code);
  313. }
  314. return code.getClear();
  315. }
  316. protected:
  317. static StringBuffer &wrapPythonText(StringBuffer &out, const char *in)
  318. {
  319. out.append("def __user__():\n ");
  320. char c;
  321. while ((c = *in++) != '\0')
  322. {
  323. out.append(c);
  324. if (c=='\n')
  325. out.append(" ");
  326. }
  327. out.append("\n__result__ = __user__()\n");
  328. return out;
  329. }
  330. PyThreadState *tstate;
  331. bool initialized;
  332. HINSTANCE pythonLibrary;
  333. OwnedPyObject namedtuple; // collections.namedtuple
  334. OwnedPyObject namedtupleTypes; // dictionary of return values from namedtuple()
  335. OwnedPyObject compiledScripts; // dictionary of previously compiled scripts
  336. CriticalSection lock;
  337. } globalState;
  338. PyObject *PythonThreadContext::getNamedTupleType(const RtlTypeInfo *type)
  339. {
  340. if (!lru || (type!=lrutype))
  341. {
  342. lru.setown(globalState.getNamedTupleType(type));
  343. lrutype = type;
  344. }
  345. return lru.getLink();
  346. }
  347. PyObject *PythonThreadContext::compileEmbeddedScript(size32_t lenChars, const char *utf)
  348. {
  349. size32_t bytes = rtlUtf8Size(lenChars, utf);
  350. StringBuffer text(bytes, utf);
  351. if (!prevtext || strcmp(text, prevtext) != 0)
  352. {
  353. prevtext.clear();
  354. script.setown(globalState.compileScript(text));
  355. prevtext.set(utf, bytes);
  356. }
  357. return script.getLink();
  358. }
  359. static int countFields(const RtlFieldInfo * const * fields)
  360. {
  361. unsigned count = 0;
  362. loop
  363. {
  364. if (!*fields)
  365. break;
  366. fields++;
  367. count++;
  368. }
  369. return count;
  370. }
  371. // Conversions from Python objects to ECL data
  372. static void typeError(const char *expected, const RtlFieldInfo *field) __attribute__((noreturn));
  373. static void typeError(const char *expected, const RtlFieldInfo *field)
  374. {
  375. VStringBuffer msg("pyembed: type mismatch - %s expected", expected);
  376. if (field)
  377. msg.appendf(" for field %s", field->name->str());
  378. rtlFail(0, msg.str());
  379. }
  380. static bool getBooleanResult(const RtlFieldInfo *field, PyObject *obj)
  381. {
  382. assertex(obj && obj != Py_None);
  383. if (!PyBool_Check(obj))
  384. typeError("boolean", field);
  385. return obj == Py_True;
  386. }
  387. static void getDataResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, void * &result)
  388. {
  389. assertex(obj && obj != Py_None);
  390. if (!PyByteArray_Check(obj))
  391. typeError("bytearray", field);
  392. rtlStrToDataX(chars, result, PyByteArray_Size(obj), PyByteArray_AsString(obj));
  393. }
  394. static double getRealResult(const RtlFieldInfo *field, PyObject *obj)
  395. {
  396. assertex(obj && obj != Py_None);
  397. if (!PyFloat_Check(obj))
  398. typeError("real", field);
  399. return PyFloat_AsDouble(obj);
  400. }
  401. static __int64 getSignedResult(const RtlFieldInfo *field, PyObject *obj)
  402. {
  403. assertex(obj && obj != Py_None);
  404. __int64 ret;
  405. if (PyInt_Check(obj))
  406. ret = PyInt_AsUnsignedLongLongMask(obj);
  407. else if (PyLong_Check(obj))
  408. ret = (__int64) PyLong_AsLongLong(obj);
  409. else
  410. typeError("integer", field);
  411. return ret;
  412. }
  413. static unsigned __int64 getUnsignedResult(const RtlFieldInfo *field, PyObject *obj)
  414. {
  415. assertex(obj && obj != Py_None);
  416. unsigned __int64 ret;
  417. if (PyInt_Check(obj))
  418. ret = PyInt_AsUnsignedLongLongMask(obj);
  419. else if (PyLong_Check(obj))
  420. ret = (unsigned __int64) PyLong_AsUnsignedLongLong(obj);
  421. else
  422. typeError("integer", field);
  423. return ret;
  424. }
  425. static void getStringResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, char * &result)
  426. {
  427. assertex(obj && obj != Py_None);
  428. if (PyString_Check(obj))
  429. {
  430. const char * text = PyString_AsString(obj);
  431. checkPythonError();
  432. size_t lenBytes = PyString_Size(obj);
  433. rtlStrToStrX(chars, result, lenBytes, text);
  434. }
  435. else
  436. typeError("string", field);
  437. }
  438. static void getUTF8Result(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, char * &result)
  439. {
  440. assertex(obj && obj != Py_None);
  441. if (PyUnicode_Check(obj))
  442. {
  443. OwnedPyObject utf8 = PyUnicode_AsUTF8String(obj);
  444. checkPythonError();
  445. size_t lenBytes = PyString_Size(utf8);
  446. const char * text = PyString_AsString(utf8);
  447. checkPythonError();
  448. size32_t numchars = rtlUtf8Length(lenBytes, text);
  449. rtlUtf8ToUtf8X(chars, result, numchars, text);
  450. }
  451. else
  452. typeError("unicode string", field);
  453. }
  454. static void getSetResult(PyObject *obj, bool & isAllResult, size32_t & resultBytes, void * & result, int elemType, size32_t elemSize)
  455. {
  456. // MORE - should probably recode to use the getResultDataset mechanism
  457. assertex(obj && obj != Py_None);
  458. if (!PyList_Check(obj) && !PySet_Check(obj))
  459. rtlFail(0, "pyembed: type mismatch - list or set expected");
  460. rtlRowBuilder out;
  461. size32_t outBytes = 0;
  462. byte *outData = NULL;
  463. OwnedPyObject iter = PyObject_GetIter(obj);
  464. OwnedPyObject elem;
  465. for (elem.setown(PyIter_Next(iter)); elem != NULL; elem.setown(PyIter_Next(iter)))
  466. {
  467. if (elemSize != UNKNOWN_LENGTH)
  468. {
  469. out.ensureAvailable(outBytes + elemSize);
  470. outData = out.getbytes() + outBytes;
  471. outBytes += elemSize;
  472. }
  473. switch ((type_t) elemType)
  474. {
  475. case type_int:
  476. rtlWriteInt(outData, pyembed::getSignedResult(NULL, elem), elemSize);
  477. break;
  478. case type_unsigned:
  479. rtlWriteInt(outData, pyembed::getUnsignedResult(NULL, elem), elemSize);
  480. break;
  481. case type_real:
  482. if (elemSize == sizeof(double))
  483. * (double *) outData = (double) pyembed::getRealResult(NULL, elem);
  484. else
  485. {
  486. assertex(elemSize == sizeof(float));
  487. * (float *) outData = (float) pyembed::getRealResult(NULL, elem);
  488. }
  489. break;
  490. case type_boolean:
  491. assertex(elemSize == sizeof(bool));
  492. * (bool *) outData = pyembed::getBooleanResult(NULL, elem);
  493. break;
  494. case type_string:
  495. case type_varstring:
  496. {
  497. if (!PyString_Check(elem))
  498. rtlFail(0, "pyembed: type mismatch - return value in list was not a STRING");
  499. const char * text = PyString_AsString(elem);
  500. checkPythonError();
  501. size_t lenBytes = PyString_Size(elem);
  502. if (elemSize == UNKNOWN_LENGTH)
  503. {
  504. if (elemType == type_string)
  505. {
  506. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  507. outData = out.getbytes() + outBytes;
  508. * (size32_t *) outData = lenBytes;
  509. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  510. outBytes += lenBytes + sizeof(size32_t);
  511. }
  512. else
  513. {
  514. out.ensureAvailable(outBytes + lenBytes + 1);
  515. outData = out.getbytes() + outBytes;
  516. rtlStrToVStr(0, outData, lenBytes, text);
  517. outBytes += lenBytes + 1;
  518. }
  519. }
  520. else
  521. {
  522. if (elemType == type_string)
  523. rtlStrToStr(elemSize, outData, lenBytes, text);
  524. else
  525. rtlStrToVStr(elemSize, outData, lenBytes, text); // Fixed size null terminated strings... weird.
  526. }
  527. break;
  528. }
  529. case type_unicode:
  530. case type_utf8:
  531. {
  532. if (!PyUnicode_Check(elem))
  533. rtlFail(0, "pyembed: type mismatch - return value in list was not a unicode STRING");
  534. OwnedPyObject utf8 = PyUnicode_AsUTF8String(elem);
  535. checkPythonError();
  536. size_t lenBytes = PyString_Size(utf8);
  537. const char * text = PyString_AsString(utf8);
  538. checkPythonError();
  539. size32_t numchars = rtlUtf8Length(lenBytes, text);
  540. if (elemType == type_utf8)
  541. {
  542. assertex (elemSize == UNKNOWN_LENGTH);
  543. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  544. outData = out.getbytes() + outBytes;
  545. * (size32_t *) outData = numchars;
  546. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  547. outBytes += lenBytes + sizeof(size32_t);
  548. }
  549. else
  550. {
  551. if (elemSize == UNKNOWN_LENGTH)
  552. {
  553. out.ensureAvailable(outBytes + numchars*sizeof(UChar) + sizeof(size32_t));
  554. outData = out.getbytes() + outBytes;
  555. // You can't assume that number of chars in utf8 matches number in unicode16 ...
  556. size32_t numchars16;
  557. rtlDataAttr unicode16;
  558. rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
  559. * (size32_t *) outData = numchars16;
  560. rtlUnicodeToUnicode(numchars16, (UChar *) (outData+sizeof(size32_t)), numchars16, unicode16.getustr());
  561. outBytes += numchars16*sizeof(UChar) + sizeof(size32_t);
  562. }
  563. else
  564. rtlUtf8ToUnicode(elemSize / sizeof(UChar), (UChar *) outData, numchars, text);
  565. }
  566. break;
  567. }
  568. case type_data:
  569. {
  570. if (!PyByteArray_Check(elem))
  571. rtlFail(0, "pyembed: type mismatch - return value in list was not a bytearray");
  572. size_t lenBytes = PyByteArray_Size(elem); // Could check does not overflow size32_t
  573. const char *data = PyByteArray_AsString(elem);
  574. if (elemSize == UNKNOWN_LENGTH)
  575. {
  576. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  577. outData = out.getbytes() + outBytes;
  578. * (size32_t *) outData = lenBytes;
  579. rtlStrToData(lenBytes, outData+sizeof(size32_t), lenBytes, data);
  580. outBytes += lenBytes + sizeof(size32_t);
  581. }
  582. else
  583. rtlStrToData(elemSize, outData, lenBytes, data);
  584. break;
  585. }
  586. default:
  587. rtlFail(0, "pyembed: type mismatch - unsupported return type");
  588. break;
  589. }
  590. checkPythonError();
  591. }
  592. isAllResult = false;
  593. resultBytes = outBytes;
  594. result = out.detachdata();
  595. }
  596. static void getUnicodeResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, UChar * &result)
  597. {
  598. assertex(obj && obj != Py_None);
  599. if (PyUnicode_Check(obj))
  600. {
  601. OwnedPyObject utf8 = PyUnicode_AsUTF8String(obj);
  602. checkPythonError();
  603. size_t lenBytes = PyString_Size(utf8);
  604. const char * text = PyString_AsString(utf8);
  605. checkPythonError();
  606. size32_t numchars = rtlUtf8Length(lenBytes, text);
  607. rtlUtf8ToUnicodeX(chars, result, numchars, text);
  608. }
  609. else
  610. typeError("unicode string", field);
  611. }
  612. // A PythonRowBuilder object is used to construct an ECL row from a python object
  613. class PythonRowBuilder : public CInterfaceOf<IFieldSource>
  614. {
  615. public:
  616. PythonRowBuilder(PyObject *_row)
  617. : iter(NULL), elem(NULL), named(false)
  618. {
  619. pushback.set(_row);
  620. }
  621. virtual bool getBooleanResult(const RtlFieldInfo *field)
  622. {
  623. nextField(field);
  624. return pyembed::getBooleanResult(field, elem);
  625. }
  626. virtual void getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result)
  627. {
  628. nextField(field);
  629. pyembed::getDataResult(field, elem, len, result);
  630. }
  631. virtual double getRealResult(const RtlFieldInfo *field)
  632. {
  633. nextField(field);
  634. return pyembed::getRealResult(field, elem);
  635. }
  636. virtual __int64 getSignedResult(const RtlFieldInfo *field)
  637. {
  638. nextField(field);
  639. return pyembed::getSignedResult(field, elem);
  640. }
  641. virtual unsigned __int64 getUnsignedResult(const RtlFieldInfo *field)
  642. {
  643. nextField(field);
  644. return pyembed::getUnsignedResult(field, elem);
  645. }
  646. virtual void getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result)
  647. {
  648. nextField(field);
  649. pyembed::getStringResult(field, elem, chars, result);
  650. }
  651. virtual void getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result)
  652. {
  653. nextField(field);
  654. pyembed::getUTF8Result(field, elem, chars, result);
  655. }
  656. virtual void getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result)
  657. {
  658. nextField(field);
  659. pyembed::getUnicodeResult(field, elem, chars, result);
  660. }
  661. virtual void getDecimalResult(const RtlFieldInfo *field, Decimal &value)
  662. {
  663. nextField(field);
  664. double ret = pyembed::getRealResult(field, elem);
  665. value.setReal(ret);
  666. }
  667. virtual void processBeginSet(const RtlFieldInfo * field, bool &isAll)
  668. {
  669. nextField(field);
  670. isAll = false; // No concept of an 'all' set in Python
  671. assertex(elem && elem != Py_None);
  672. if (!PyList_Check(elem) && !PySet_Check(elem))
  673. typeError("list or set", field);
  674. push();
  675. }
  676. virtual bool processNextSet(const RtlFieldInfo * field)
  677. {
  678. nextField(NULL);
  679. pushback.setown(elem.getClear());
  680. return pushback != NULL;
  681. }
  682. virtual void processBeginDataset(const RtlFieldInfo * field)
  683. {
  684. nextField(field);
  685. if (!PyList_Check(elem))
  686. typeError("list", field);
  687. push();
  688. }
  689. virtual void processBeginRow(const RtlFieldInfo * field)
  690. {
  691. // Expect to see a tuple here, or possibly (if the ECL record has a single field), an arbitrary scalar object
  692. // If it's a tuple, we push it onto our stack as the active object
  693. nextField(NULL); // MORE - should it be passing field?
  694. if (!PyTuple_Check(elem))
  695. {
  696. if (countFields(field->type->queryFields())==1)
  697. {
  698. // Python doesn't seem to support the concept of a tuple containing a single element.
  699. // If we are expecting a single field in our row, then the 'tuple' layer will be missing
  700. elem.setown(PyTuple_Pack(1, elem.get()));
  701. }
  702. else
  703. typeError("tuple", field);
  704. }
  705. push();
  706. }
  707. virtual bool processNextRow(const RtlFieldInfo * field)
  708. {
  709. nextField(NULL);
  710. pushback.setown(elem.getClear());
  711. return pushback != NULL;
  712. }
  713. virtual void processEndSet(const RtlFieldInfo * field)
  714. {
  715. pop();
  716. }
  717. virtual void processEndDataset(const RtlFieldInfo * field)
  718. {
  719. pop();
  720. }
  721. virtual void processEndRow(const RtlFieldInfo * field)
  722. {
  723. pop();
  724. }
  725. protected:
  726. void pop()
  727. {
  728. iter.setown((PyObject *) iterStack.pop());
  729. parent.setown((PyObject *) parentStack.pop());
  730. named = namedStack.pop();
  731. elem.clear();
  732. }
  733. void push()
  734. {
  735. iterStack.append(iter.getClear());
  736. parentStack.append(parent.getClear());
  737. namedStack.append(named);
  738. parent.set(elem);
  739. iter.setown(PyObject_GetIter(elem));
  740. named = isNamedTuple(elem);
  741. elem.clear();
  742. }
  743. bool isNamedTuple(PyObject *obj)
  744. {
  745. return PyObject_HasAttrString((PyObject *) obj->ob_type, "_fields");
  746. }
  747. void nextField(const RtlFieldInfo * field)
  748. {
  749. if (pushback)
  750. elem.setown(pushback.getClear());
  751. else if (field && named) // If it's named tuple, expect to always resolve fields by name, not position
  752. {
  753. elem.setown(PyObject_GetAttrString(parent, field->name->str()));
  754. }
  755. else if (iter)
  756. elem.setown(PyIter_Next(iter));
  757. else
  758. elem = NULL;
  759. checkPythonError();
  760. }
  761. OwnedPyObject iter;
  762. OwnedPyObject pushback;
  763. OwnedPyObject elem;
  764. OwnedPyObject parent;
  765. bool named;
  766. PointerArray iterStack;
  767. PointerArray parentStack;
  768. BoolArray namedStack;
  769. };
  770. static size32_t getRowResult(PyObject *result, ARowBuilder &builder)
  771. {
  772. PythonRowBuilder pyRowBuilder(result);
  773. const RtlTypeInfo *typeInfo = builder.queryAllocator()->queryOutputMeta()->queryTypeInfo();
  774. assertex(typeInfo);
  775. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  776. return typeInfo->build(builder, 0, &dummyField, pyRowBuilder);
  777. }
  778. // A PythonNamedTupleBuilder object is used to construct a Python named tuple from an ECL row
  779. class PythonNamedTupleBuilder : public CInterfaceOf<IFieldProcessor>
  780. {
  781. public:
  782. PythonNamedTupleBuilder(PythonThreadContext *_sharedCtx, const RtlFieldInfo *_outerRow)
  783. : outerRow(_outerRow), sharedCtx(_sharedCtx)
  784. {
  785. }
  786. virtual void processString(unsigned len, const char *value, const RtlFieldInfo * field)
  787. {
  788. addArg(PyString_FromStringAndSize(value, len));
  789. }
  790. virtual void processBool(bool value, const RtlFieldInfo * field)
  791. {
  792. addArg(PyBool_FromLong(value ? 1 : 0));
  793. }
  794. virtual void processData(unsigned len, const void *value, const RtlFieldInfo * field)
  795. {
  796. addArg(PyByteArray_FromStringAndSize((const char *) value, len));
  797. }
  798. virtual void processInt(__int64 value, const RtlFieldInfo * field)
  799. {
  800. addArg(PyLong_FromLongLong(value));
  801. }
  802. virtual void processUInt(unsigned __int64 value, const RtlFieldInfo * field)
  803. {
  804. addArg(PyLong_FromUnsignedLongLong(value));
  805. }
  806. virtual void processReal(double value, const RtlFieldInfo * field)
  807. {
  808. addArg(PyFloat_FromDouble(value));
  809. }
  810. virtual void processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  811. {
  812. Decimal val;
  813. val.setDecimal(digits, precision, value);
  814. addArg(PyFloat_FromDouble(val.getReal()));
  815. }
  816. virtual void processUDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  817. {
  818. Decimal val;
  819. val.setUDecimal(digits, precision, value);
  820. addArg(PyFloat_FromDouble(val.getReal()));
  821. }
  822. virtual void processUnicode(unsigned len, const UChar *value, const RtlFieldInfo * field)
  823. {
  824. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  825. unsigned unicodeChars;
  826. rtlDataAttr unicode;
  827. rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), len, value);
  828. processUtf8(unicodeChars, unicode.getstr(), field);
  829. }
  830. virtual void processQString(unsigned len, const char *value, const RtlFieldInfo * field)
  831. {
  832. size32_t charCount;
  833. rtlDataAttr text;
  834. rtlQStrToStrX(charCount, text.refstr(), len, value);
  835. processString(charCount, text.getstr(), field);
  836. }
  837. virtual void processSetAll(const RtlFieldInfo * field)
  838. {
  839. rtlFail(0, "pyembed: ALL sets are not supported");
  840. }
  841. virtual void processUtf8(unsigned len, const char *value, const RtlFieldInfo * field)
  842. {
  843. size32_t sizeBytes = rtlUtf8Size(len, value);
  844. PyObject *vval = PyUnicode_FromStringAndSize(value, sizeBytes); // NOTE - requires size in bytes not chars
  845. checkPythonError();
  846. addArg(vval);
  847. }
  848. virtual bool processBeginSet(const RtlFieldInfo * field)
  849. {
  850. push();
  851. return true;
  852. }
  853. virtual bool processBeginDataset(const RtlFieldInfo * field)
  854. {
  855. push();
  856. return true;
  857. }
  858. virtual bool processBeginRow(const RtlFieldInfo * field)
  859. {
  860. if (field != outerRow)
  861. push();
  862. return true;
  863. }
  864. virtual void processEndSet(const RtlFieldInfo * field)
  865. {
  866. pop();
  867. }
  868. virtual void processEndDataset(const RtlFieldInfo * field)
  869. {
  870. pop();
  871. }
  872. virtual void processEndRow(const RtlFieldInfo * field)
  873. {
  874. if (field != outerRow)
  875. {
  876. args.setown(getTuple(field->type));
  877. pop();
  878. }
  879. }
  880. PyObject *getTuple(const RtlTypeInfo *type)
  881. {
  882. OwnedPyObject mynamedtupletype = sharedCtx ? sharedCtx->getNamedTupleType(type) : globalState.getNamedTupleType(type);
  883. OwnedPyObject argsTuple = PyList_AsTuple(args);
  884. OwnedPyObject mynamedtuple = PyObject_CallObject(mynamedtupletype, argsTuple); // Creates a namedtuple from the supplied tuple
  885. checkPythonError();
  886. return mynamedtuple.getClear();
  887. }
  888. protected:
  889. void push()
  890. {
  891. stack.append(args.getClear());
  892. }
  893. void pop()
  894. {
  895. addArg(args.getClear());
  896. args.setown((PyObject *) stack.pop());
  897. }
  898. void addArg(PyObject *arg)
  899. {
  900. if (!args)
  901. {
  902. args.setown(PyList_New(0));
  903. }
  904. PyList_Append(args, arg);
  905. Py_DECREF(arg);
  906. }
  907. OwnedPyObject args;
  908. PointerArray stack;
  909. const RtlFieldInfo *outerRow;
  910. PythonThreadContext *sharedCtx;
  911. };
  912. //----------------------------------------------------------------------
  913. // Wrap an IRowStream into a Python generator
  914. struct ECLDatasetIterator
  915. {
  916. PyObject_HEAD;
  917. const RtlTypeInfo *typeInfo; // Not linked (or linkable)
  918. IRowStream * val; // Linked
  919. };
  920. PyObject* ECLDatasetIterator_iter(PyObject *self)
  921. {
  922. Py_INCREF(self);
  923. return self;
  924. }
  925. void ECLDatasetIterator_dealloc(PyObject *self)
  926. {
  927. ECLDatasetIterator *p = (ECLDatasetIterator *)self;
  928. if (p->val)
  929. {
  930. p->val->stop();
  931. ::Release(p->val);
  932. p->val = NULL;
  933. }
  934. self->ob_type->tp_free(self);
  935. }
  936. PyObject* ECLDatasetIterator_iternext(PyObject *self)
  937. {
  938. ECLDatasetIterator *p = (ECLDatasetIterator *)self;
  939. if (p->val)
  940. {
  941. const byte *nextRow = (const byte *) p->val->nextRow();
  942. if (!nextRow)
  943. {
  944. p->val->stop();
  945. ::Release(p->val);
  946. p->val = NULL;
  947. }
  948. else
  949. {
  950. RtlFieldStrInfo dummyField("<row>", NULL, p->typeInfo);
  951. PythonNamedTupleBuilder tupleBuilder(NULL, &dummyField);
  952. p->typeInfo->process(nextRow, nextRow, &dummyField, tupleBuilder);
  953. return tupleBuilder.getTuple(p->typeInfo);
  954. }
  955. }
  956. // If we get here, it's EOF
  957. PyErr_SetNone(PyExc_StopIteration);
  958. return NULL;
  959. }
  960. static PyTypeObject ECLDatasetIteratorType =
  961. {
  962. PyObject_HEAD_INIT(NULL)
  963. 0, /*ob_size*/
  964. "ECLDatasetIterator._MyIter", /*tp_name*/
  965. sizeof(ECLDatasetIterator), /*tp_basicsize*/
  966. 0, /*tp_itemsize*/
  967. ECLDatasetIterator_dealloc, /*tp_dealloc*/
  968. 0, /*tp_print*/
  969. 0, /*tp_getattr*/
  970. 0, /*tp_setattr*/
  971. 0, /*tp_compare*/
  972. 0, /*tp_repr*/
  973. 0, /*tp_as_number*/
  974. 0, /*tp_as_sequence*/
  975. 0, /*tp_as_mapping*/
  976. 0, /*tp_hash */
  977. 0, /*tp_call*/
  978. 0, /*tp_str*/
  979. 0, /*tp_getattro*/
  980. 0, /*tp_setattro*/
  981. 0, /*tp_as_buffer*/
  982. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags: tell python to use tp_iter and tp_iternext fields. */
  983. "ECL dataset iterator object.", /* tp_doc */
  984. 0, /* tp_traverse */
  985. 0, /* tp_clear */
  986. 0, /* tp_richcompare */
  987. 0, /* tp_weaklistoffset */
  988. ECLDatasetIterator_iter, /* tp_iter: __iter__() method */
  989. ECLDatasetIterator_iternext /* tp_iternext: next() method */
  990. };
  991. static PyObject *createECLDatasetIterator(const RtlTypeInfo *_typeInfo, IRowStream * _val)
  992. {
  993. ECLDatasetIteratorType.tp_new = PyType_GenericNew;
  994. if (PyType_Ready(&ECLDatasetIteratorType) < 0) return NULL;
  995. ECLDatasetIterator *p = PyObject_New(ECLDatasetIterator, &ECLDatasetIteratorType);
  996. if (!p)
  997. {
  998. checkPythonError();
  999. rtlFail(0, "pyembed: failed to create dataset iterator");
  1000. }
  1001. p->typeInfo = _typeInfo;
  1002. p->val = _val;
  1003. return (PyObject *)p;
  1004. }
  1005. //-----------------------------------------------------
  1006. // GILBlock ensures the we hold the Python "Global interpreter lock" for the appropriate duration
  1007. class GILBlock
  1008. {
  1009. public:
  1010. GILBlock(PyThreadState * &_state) : state(_state)
  1011. {
  1012. PyEval_RestoreThread(state);
  1013. }
  1014. ~GILBlock()
  1015. {
  1016. state = PyEval_SaveThread();
  1017. }
  1018. private:
  1019. PyThreadState * &state;
  1020. };
  1021. // A Python function that returns a dataset will return a PythonRowStream object that can be
  1022. // interrogated to return each row of the result in turn
  1023. class PythonRowStream : public CInterfaceOf<IRowStream>
  1024. {
  1025. public:
  1026. PythonRowStream(PythonThreadContext *_sharedCtx, PyObject *result, IEngineRowAllocator *_resultAllocator)
  1027. : sharedCtx(_sharedCtx), resultIterator(NULL)
  1028. {
  1029. // NOTE - the caller should already have the GIL lock before creating me
  1030. if (!result || result == Py_None)
  1031. typeError("list or generator", NULL);
  1032. resultIterator.setown(PyObject_GetIter(result)); // We allow anything that is iterable to be returned for a row stream
  1033. checkPythonError();
  1034. resultAllocator.set(_resultAllocator);
  1035. }
  1036. virtual const void *nextRow()
  1037. {
  1038. GILBlock b(sharedCtx->threadState);
  1039. if (!resultIterator)
  1040. return NULL;
  1041. OwnedPyObject row = PyIter_Next(resultIterator);
  1042. if (!row)
  1043. return NULL;
  1044. RtlDynamicRowBuilder rowBuilder(resultAllocator);
  1045. size32_t len = pyembed::getRowResult(row, rowBuilder);
  1046. return rowBuilder.finalizeRowClear(len);
  1047. }
  1048. virtual void stop()
  1049. {
  1050. resultAllocator.clear();
  1051. resultIterator.clear();
  1052. }
  1053. protected:
  1054. PythonThreadContext *sharedCtx;
  1055. Linked<IEngineRowAllocator> resultAllocator;
  1056. OwnedPyObject resultIterator;
  1057. };
  1058. // Each call to a Python function will use a new Python27EmbedFunctionContext object
  1059. // This takes care of ensuring that the Python GIL is locked while we are executing python code,
  1060. // and released when we are not
  1061. class Python27EmbedContextBase : public CInterfaceOf<IEmbedFunctionContext>
  1062. {
  1063. public:
  1064. Python27EmbedContextBase(PythonThreadContext *_sharedCtx)
  1065. : sharedCtx(_sharedCtx)
  1066. {
  1067. PyEval_RestoreThread(sharedCtx->threadState);
  1068. locals.setown(PyDict_New());
  1069. globals.setown(PyDict_New());
  1070. PyDict_SetItemString(locals, "__builtins__", PyEval_GetBuiltins()); // required for import to work
  1071. }
  1072. ~Python27EmbedContextBase()
  1073. {
  1074. // We need to clear these before calling savethread, or we won't own the GIL
  1075. locals.clear();
  1076. globals.clear();
  1077. result.clear();
  1078. script.clear();
  1079. sharedCtx->threadState = PyEval_SaveThread();
  1080. }
  1081. virtual bool getBooleanResult()
  1082. {
  1083. return pyembed::getBooleanResult(NULL, result);
  1084. }
  1085. virtual void getDataResult(size32_t &__chars, void * &__result)
  1086. {
  1087. pyembed::getDataResult(NULL, result, __chars, __result);
  1088. }
  1089. virtual double getRealResult()
  1090. {
  1091. return pyembed::getRealResult(NULL, result);
  1092. }
  1093. virtual __int64 getSignedResult()
  1094. {
  1095. return pyembed::getSignedResult(NULL, result);
  1096. }
  1097. virtual unsigned __int64 getUnsignedResult()
  1098. {
  1099. return pyembed::getUnsignedResult(NULL, result);
  1100. }
  1101. virtual void getStringResult(size32_t &__chars, char * &__result)
  1102. {
  1103. pyembed::getStringResult(NULL, result, __chars, __result);
  1104. }
  1105. virtual void getUTF8Result(size32_t &__chars, char * &__result)
  1106. {
  1107. pyembed::getUTF8Result(NULL, result, __chars, __result);
  1108. }
  1109. virtual void getUnicodeResult(size32_t &__chars, UChar * &__result)
  1110. {
  1111. pyembed::getUnicodeResult(NULL, result, __chars, __result);
  1112. }
  1113. virtual void getSetResult(bool & __isAllResult, size32_t & __resultBytes, void * & __result, int elemType, size32_t elemSize)
  1114. {
  1115. pyembed::getSetResult(result, __isAllResult, __resultBytes, __result, elemType, elemSize);
  1116. }
  1117. virtual IRowStream *getDatasetResult(IEngineRowAllocator * _resultAllocator)
  1118. {
  1119. return new PythonRowStream(sharedCtx, result, _resultAllocator);
  1120. }
  1121. virtual byte * getRowResult(IEngineRowAllocator * _resultAllocator)
  1122. {
  1123. RtlDynamicRowBuilder rowBuilder(_resultAllocator);
  1124. size32_t len = pyembed::getRowResult(result, rowBuilder);
  1125. return (byte *) rowBuilder.finalizeRowClear(len);
  1126. }
  1127. virtual size32_t getTransformResult(ARowBuilder & builder)
  1128. {
  1129. return pyembed::getRowResult(result, builder);
  1130. }
  1131. virtual void bindBooleanParam(const char *name, bool val)
  1132. {
  1133. addArg(name, PyBool_FromLong(val ? 1 : 0));
  1134. }
  1135. virtual void bindDataParam(const char *name, size32_t len, const void *val)
  1136. {
  1137. addArg(name, PyByteArray_FromStringAndSize((const char *) val, len));
  1138. }
  1139. virtual void bindRealParam(const char *name, double val)
  1140. {
  1141. addArg(name, PyFloat_FromDouble(val));
  1142. }
  1143. virtual void bindSignedParam(const char *name, __int64 val)
  1144. {
  1145. addArg(name, PyLong_FromLongLong(val));
  1146. }
  1147. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  1148. {
  1149. addArg(name, PyLong_FromUnsignedLongLong(val));
  1150. }
  1151. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  1152. {
  1153. addArg(name, PyString_FromStringAndSize(val, len));
  1154. }
  1155. virtual void bindVStringParam(const char *name, const char *val)
  1156. {
  1157. addArg(name, PyString_FromString(val));
  1158. }
  1159. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  1160. {
  1161. size32_t sizeBytes = rtlUtf8Size(chars, val);
  1162. PyObject *vval = PyUnicode_FromStringAndSize(val, sizeBytes); // NOTE - requires size in bytes not chars
  1163. checkPythonError();
  1164. addArg(name, vval);
  1165. }
  1166. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  1167. {
  1168. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  1169. unsigned unicodeChars;
  1170. char *unicode;
  1171. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  1172. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  1173. PyObject *vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  1174. checkPythonError();
  1175. addArg(name, vval);
  1176. rtlFree(unicode);
  1177. }
  1178. virtual void bindSetParam(const char *name, int elemType, size32_t elemSize, bool isAll, size32_t totalBytes, void *setData)
  1179. {
  1180. if (isAll)
  1181. rtlFail(0, "pyembed: Cannot pass ALL");
  1182. type_t typecode = (type_t) elemType;
  1183. const byte *inData = (const byte *) setData;
  1184. const byte *endData = inData + totalBytes;
  1185. OwnedPyObject vval = PyList_New(0);
  1186. while (inData < endData)
  1187. {
  1188. OwnedPyObject thisElem;
  1189. size32_t thisSize = elemSize;
  1190. switch (typecode)
  1191. {
  1192. case type_int:
  1193. thisElem.setown(PyLong_FromLongLong(rtlReadInt(inData, elemSize)));
  1194. break;
  1195. case type_unsigned:
  1196. thisElem.setown(PyLong_FromUnsignedLongLong(rtlReadUInt(inData, elemSize)));
  1197. break;
  1198. case type_varstring:
  1199. {
  1200. size32_t numChars = strlen((const char *) inData);
  1201. thisElem.setown(PyString_FromStringAndSize((const char *) inData, numChars));
  1202. if (elemSize == UNKNOWN_LENGTH)
  1203. thisSize = numChars + 1;
  1204. break;
  1205. }
  1206. case type_string:
  1207. if (elemSize == UNKNOWN_LENGTH)
  1208. {
  1209. thisSize = * (size32_t *) inData;
  1210. inData += sizeof(size32_t);
  1211. }
  1212. thisElem.setown(PyString_FromStringAndSize((const char *) inData, thisSize));
  1213. break;
  1214. case type_real:
  1215. if (elemSize == sizeof(double))
  1216. thisElem.setown(PyFloat_FromDouble(* (double *) inData));
  1217. else
  1218. thisElem.setown(PyFloat_FromDouble(* (float *) inData));
  1219. break;
  1220. case type_boolean:
  1221. assertex(elemSize == sizeof(bool));
  1222. thisElem.setown(PyBool_FromLong(*(bool*)inData ? 1 : 0));
  1223. break;
  1224. case type_unicode:
  1225. {
  1226. if (elemSize == UNKNOWN_LENGTH)
  1227. {
  1228. thisSize = (* (size32_t *) inData) * sizeof(UChar); // NOTE - it's in chars...
  1229. inData += sizeof(size32_t);
  1230. }
  1231. unsigned unicodeChars;
  1232. rtlDataAttr unicode;
  1233. rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), thisSize / sizeof(UChar), (const UChar *) inData);
  1234. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode.getstr());
  1235. thisElem.setown(PyUnicode_FromStringAndSize(unicode.getstr(), sizeBytes)); // NOTE - requires size in bytes not chars
  1236. checkPythonError();
  1237. break;
  1238. }
  1239. case type_utf8:
  1240. {
  1241. assertex (elemSize == UNKNOWN_LENGTH);
  1242. size32_t numChars = * (size32_t *) inData;
  1243. inData += sizeof(size32_t);
  1244. thisSize = rtlUtf8Size(numChars, inData);
  1245. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, thisSize)); // NOTE - requires size in bytes not chars
  1246. break;
  1247. }
  1248. case type_data:
  1249. if (elemSize == UNKNOWN_LENGTH)
  1250. {
  1251. thisSize = * (size32_t *) inData;
  1252. inData += sizeof(size32_t);
  1253. }
  1254. thisElem.setown(PyByteArray_FromStringAndSize((const char *) inData, thisSize));
  1255. break;
  1256. }
  1257. checkPythonError();
  1258. inData += thisSize;
  1259. PyList_Append(vval, thisElem);
  1260. }
  1261. addArg(name, vval.getLink());
  1262. }
  1263. virtual void bindRowParam(const char *name, IOutputMetaData & metaVal, byte *val)
  1264. {
  1265. const RtlTypeInfo *typeInfo = metaVal.queryTypeInfo();
  1266. assertex(typeInfo);
  1267. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  1268. PythonNamedTupleBuilder tupleBuilder(sharedCtx, &dummyField);
  1269. typeInfo->process(val, val, &dummyField, tupleBuilder); // Creates a tuple from the incoming ECL row
  1270. addArg(name, tupleBuilder.getTuple(typeInfo));
  1271. }
  1272. virtual void bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val)
  1273. {
  1274. addArg(name, createECLDatasetIterator(metaVal.queryTypeInfo(), LINK(val)));
  1275. }
  1276. protected:
  1277. virtual void addArg(const char *name, PyObject *arg) = 0;
  1278. PythonThreadContext *sharedCtx;
  1279. OwnedPyObject locals;
  1280. OwnedPyObject globals;
  1281. OwnedPyObject result;
  1282. OwnedPyObject script;
  1283. };
  1284. class Python27EmbedScriptContext : public Python27EmbedContextBase
  1285. {
  1286. public:
  1287. Python27EmbedScriptContext(PythonThreadContext *_sharedCtx, const char *options)
  1288. : Python27EmbedContextBase(_sharedCtx)
  1289. {
  1290. }
  1291. ~Python27EmbedScriptContext()
  1292. {
  1293. }
  1294. virtual void importFunction(size32_t lenChars, const char *text)
  1295. {
  1296. throwUnexpected();
  1297. }
  1298. virtual void compileEmbeddedScript(size32_t lenChars, const char *utf)
  1299. {
  1300. script.setown(sharedCtx->compileEmbeddedScript(lenChars, utf));
  1301. }
  1302. virtual void callFunction()
  1303. {
  1304. result.setown(PyEval_EvalCode((PyCodeObject *) script.get(), locals, globals));
  1305. checkPythonError();
  1306. if (!result || result == Py_None)
  1307. result.set(PyDict_GetItemString(locals, "__result__"));
  1308. if (!result || result == Py_None)
  1309. result.set(PyDict_GetItemString(globals, "__result__"));
  1310. }
  1311. protected:
  1312. virtual void addArg(const char *name, PyObject *arg)
  1313. {
  1314. if (!arg)
  1315. return;
  1316. assertex(arg);
  1317. PyDict_SetItemString(locals, name, arg);
  1318. Py_DECREF(arg);
  1319. checkPythonError();
  1320. }
  1321. };
  1322. class Python27EmbedImportContext : public Python27EmbedContextBase
  1323. {
  1324. public:
  1325. Python27EmbedImportContext(PythonThreadContext *_sharedCtx, const char *options)
  1326. : Python27EmbedContextBase(_sharedCtx)
  1327. {
  1328. argcount = 0;
  1329. }
  1330. ~Python27EmbedImportContext()
  1331. {
  1332. }
  1333. virtual void importFunction(size32_t lenChars, const char *utf)
  1334. {
  1335. script.setown(sharedCtx->importFunction(lenChars, utf));
  1336. }
  1337. virtual void compileEmbeddedScript(size32_t len, const char *text)
  1338. {
  1339. throwUnexpected();
  1340. }
  1341. virtual void callFunction()
  1342. {
  1343. result.setown(PyObject_CallObject(script, args));
  1344. checkPythonError();
  1345. }
  1346. private:
  1347. virtual void addArg(const char *name, PyObject *arg)
  1348. {
  1349. if (argcount)
  1350. _PyTuple_Resize(args.ref(), argcount+1);
  1351. else
  1352. args.setown(PyTuple_New(1));
  1353. PyTuple_SET_ITEM((PyTupleObject *) args.get(), argcount++, arg); // Note - 'steals' the arg reference
  1354. }
  1355. int argcount;
  1356. OwnedPyObject args;
  1357. };
  1358. class Python27EmbedContext : public CInterfaceOf<IEmbedContext>
  1359. {
  1360. public:
  1361. virtual IEmbedFunctionContext *createFunctionContext(bool isImport, const char *options)
  1362. {
  1363. if (!threadContext)
  1364. {
  1365. if (!globalState.isInitialized())
  1366. rtlFail(0, "Python not initialized");
  1367. threadContext = new PythonThreadContext;
  1368. threadHookChain = addThreadTermFunc(releaseContext);
  1369. }
  1370. if (isImport)
  1371. return new Python27EmbedImportContext(threadContext, options);
  1372. else
  1373. return new Python27EmbedScriptContext(threadContext, options);
  1374. }
  1375. };
  1376. extern IEmbedContext* getEmbedContext()
  1377. {
  1378. return new Python27EmbedContext;
  1379. }
  1380. extern bool syntaxCheck(const char *script)
  1381. {
  1382. return true; // MORE
  1383. }
  1384. } // namespace