pyembed.cpp 62 KB

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