pyembed.cpp 70 KB

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