pyembed.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include "Python.h"
  15. #include "eclrtl.hpp"
  16. #include "jexcept.hpp"
  17. #include "jthread.hpp"
  18. #include "hqlplugins.hpp"
  19. #ifdef _WIN32
  20. #define EXPORT __declspec(dllexport)
  21. #else
  22. #define EXPORT
  23. #endif
  24. static const char * compatibleVersions[] = {
  25. "Python2.7 Embed Helper 1.0.0",
  26. NULL };
  27. static const char *version = "Python2.7 Embed Helper 1.0.0";
  28. static const char * EclDefinition =
  29. "EXPORT Language := SERVICE\n"
  30. " boolean getEmbedContext():cpp,pure,namespace='pyembed',entrypoint='getEmbedContext',prototype='IEmbedContext* getEmbedContext()';\n"
  31. " boolean syntaxCheck(const varstring src):cpp,pure,namespace='pyembed',entrypoint='syntaxCheck';\n"
  32. "END;"
  33. "EXPORT getEmbedContext := Language.getEmbedContext;"
  34. "EXPORT syntaxCheck := Language.syntaxCheck;"
  35. "EXPORT boolean supportsImport := true;"
  36. "EXPORT boolean supportsScript := true;";
  37. extern "C" EXPORT bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  38. {
  39. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  40. {
  41. ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
  42. pbx->compatibleVersions = compatibleVersions;
  43. }
  44. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  45. return false;
  46. pb->magicVersion = PLUGIN_VERSION;
  47. pb->version = version;
  48. pb->moduleName = "python";
  49. pb->ECL = EclDefinition;
  50. pb->flags = PLUGIN_DLL_MODULE | PLUGIN_MULTIPLE_VERSIONS;
  51. pb->description = "Python2.7 Embed Helper";
  52. return true;
  53. }
  54. namespace pyembed {
  55. // Use class OwnedPyObject for any objects that are not 'borrowed references'
  56. // so that the appropriate Py_DECREF call is made when the OwnedPyObject goes
  57. // out of scope, even if the function returns prematurely (such as via an exception).
  58. // In particular, checkPythonError is a lot easier to call safely if this is used.
  59. class OwnedPyObject
  60. {
  61. PyObject *ptr;
  62. public:
  63. inline OwnedPyObject() : ptr(NULL) {}
  64. inline OwnedPyObject(PyObject *_ptr) : ptr(_ptr) {}
  65. inline ~OwnedPyObject() { if (ptr) Py_DECREF(ptr); }
  66. inline PyObject * get() const { return ptr; }
  67. inline PyObject * operator -> () const { return ptr; }
  68. inline operator PyObject *() const { return ptr; }
  69. inline void clear() { if (ptr) Py_DECREF(ptr); ptr = NULL; }
  70. inline void setown(PyObject *_ptr) { clear(); ptr = _ptr; }
  71. inline void set(PyObject *_ptr) { clear(); ptr = _ptr; if (ptr) Py_INCREF(ptr);}
  72. inline PyObject *getLink() { if (ptr) Py_INCREF(ptr); return ptr;}
  73. inline PyObject **ref() { return &ptr; }
  74. };
  75. // call checkPythonError to throw an exception if Python error state is set
  76. static void checkPythonError()
  77. {
  78. PyObject* err = PyErr_Occurred();
  79. if (err)
  80. {
  81. OwnedPyObject pType, pValue, pTraceBack;
  82. PyErr_Fetch(pType.ref(), pValue.ref(), pTraceBack.ref());
  83. OwnedPyObject valStr = PyObject_Str(pValue);
  84. PyErr_Clear();
  85. VStringBuffer errMessage("pyembed: %s", PyString_AsString(valStr));
  86. rtlFail(0, errMessage.str());
  87. }
  88. }
  89. // The Python Global Interpreter Lock (GIL) won't know about C++-created threads, so we need to
  90. // call PyGILState_Ensure() and PyGILState_Release at the start and end of every function.
  91. // Wrapping them in a class like this ensures that the release always happens even if
  92. // the function exists prematurely
  93. class GILstateWrapper
  94. {
  95. PyGILState_STATE gstate;
  96. public:
  97. GILstateWrapper()
  98. {
  99. gstate = PyGILState_Ensure();
  100. }
  101. ~GILstateWrapper()
  102. {
  103. PyGILState_Release(gstate);
  104. }
  105. };
  106. // There is a singleton PythonThreadContext per thread. This allows us to
  107. // ensure that we can make repeated calls to a Python function efficiently.
  108. class PythonThreadContext
  109. {
  110. public:
  111. PyThreadState *threadState;
  112. public:
  113. PythonThreadContext()
  114. {
  115. threadState = PyEval_SaveThread();
  116. }
  117. ~PythonThreadContext()
  118. {
  119. PyEval_RestoreThread(threadState);
  120. script.clear();
  121. }
  122. inline PyObject * importFunction(const char *text)
  123. {
  124. if (!prevtext || strcmp(text, prevtext) != 0)
  125. {
  126. prevtext.clear();
  127. // Name should be in the form module.function
  128. const char *funcname = strrchr(text, '.');
  129. if (!funcname)
  130. rtlFail(0, "Expected module.function");
  131. StringBuffer modname(funcname-text, text);
  132. funcname++; // skip the '.'
  133. // If the modname is preceded by a path, add it to the python path before importing
  134. const char *pathsep = strrchr(modname, PATHSEPCHAR);
  135. if (pathsep)
  136. {
  137. StringBuffer path(pathsep-modname, modname);
  138. modname.remove(0, 1+pathsep-modname);
  139. PyObject *sys_path = PySys_GetObject((char *) "path");
  140. OwnedPyObject new_path = PyString_FromString(path);
  141. if (sys_path)
  142. {
  143. PyList_Append(sys_path, new_path);
  144. checkPythonError();
  145. }
  146. }
  147. module.setown(PyImport_ImportModule(modname));
  148. checkPythonError();
  149. PyObject *dict = PyModule_GetDict(module); // this is a borrowed reference and does not need to be released
  150. script.set(PyDict_GetItemString(dict, funcname));
  151. checkPythonError();
  152. if (!script || !PyCallable_Check(script))
  153. rtlFail(0, "Object is not callable");
  154. prevtext.set(text);
  155. }
  156. return script.getLink();
  157. }
  158. inline PyObject *compileEmbeddedScript(const char *text)
  159. {
  160. if (!prevtext || strcmp(text, prevtext) != 0)
  161. {
  162. prevtext.clear();
  163. // Try compiling as a eval first... if that fails, try as a script.
  164. script.setown(Py_CompileString(text, "", Py_eval_input));
  165. if (!script)
  166. {
  167. PyErr_Clear();
  168. StringBuffer wrapped;
  169. wrapPythonText(wrapped, text);
  170. script.setown(Py_CompileString(wrapped, "<embed>", Py_file_input));
  171. }
  172. checkPythonError();
  173. prevtext.set(text);
  174. }
  175. return script.getLink();
  176. }
  177. private:
  178. static StringBuffer &wrapPythonText(StringBuffer &out, const char *in)
  179. {
  180. out.append("def __user__():\n ");
  181. char c;
  182. while ((c = *in++) != '\0')
  183. {
  184. out.append(c);
  185. if (c=='\n')
  186. out.append(" ");
  187. }
  188. out.append("\n__result__ = __user__()\n");
  189. return out;
  190. }
  191. GILstateWrapper GILState;
  192. OwnedPyObject module;
  193. OwnedPyObject script;
  194. StringAttr prevtext;
  195. };
  196. static __thread PythonThreadContext* threadContext; // We reuse per thread, for speed
  197. static __thread ThreadTermFunc threadHookChain;
  198. static void releaseContext()
  199. {
  200. delete threadContext;
  201. threadContext = NULL;
  202. if (threadHookChain)
  203. (*threadHookChain)();
  204. }
  205. // Use a global object to ensure that the Python interpreter is initialized on main thread
  206. static class Python27GlobalState
  207. {
  208. public:
  209. Python27GlobalState()
  210. {
  211. // Initialize the Python Interpreter
  212. Py_Initialize();
  213. PyEval_InitThreads();
  214. tstate = PyEval_SaveThread();
  215. }
  216. ~Python27GlobalState()
  217. {
  218. if (threadContext)
  219. delete threadContext; // The one on the main thread won't get picked up by the thread hook mechanism
  220. threadContext = NULL;
  221. PyEval_RestoreThread(tstate);
  222. // Finish the Python Interpreter
  223. Py_Finalize();
  224. }
  225. protected:
  226. PyThreadState *tstate;
  227. } globalState;
  228. // Each call to a Python function will use a new Python27EmbedFunctionContext object
  229. // This takes care of ensuring that the Python GIL is locked while we are executing python code,
  230. // and released when we are not
  231. class Python27EmbedContextBase : public CInterfaceOf<IEmbedFunctionContext>
  232. {
  233. public:
  234. Python27EmbedContextBase(PythonThreadContext *_sharedCtx)
  235. : sharedCtx(_sharedCtx)
  236. {
  237. PyEval_RestoreThread(sharedCtx->threadState);
  238. locals.setown(PyDict_New());
  239. globals.setown(PyDict_New());
  240. PyDict_SetItemString(locals, "__builtins__", PyEval_GetBuiltins()); // required for import to work
  241. }
  242. ~Python27EmbedContextBase()
  243. {
  244. // We need to clear these before calling savethread, or we won't own the GIL
  245. locals.clear();
  246. globals.clear();
  247. result.clear();
  248. script.clear();
  249. sharedCtx->threadState = PyEval_SaveThread();
  250. }
  251. virtual bool getBooleanResult()
  252. {
  253. assertex(result);
  254. if (!PyBool_Check(result))
  255. throw MakeStringException(MSGAUD_user, 0, "pyembed: Type mismatch on result");
  256. return result == Py_True;
  257. }
  258. virtual double getRealResult()
  259. {
  260. assertex(result && result != Py_None);
  261. return (__int64) PyFloat_AsDouble(result);
  262. }
  263. virtual __int64 getSignedResult()
  264. {
  265. assertex(result && result != Py_None);
  266. return (__int64) PyLong_AsLongLong(result);
  267. }
  268. virtual unsigned __int64 getUnsignedResult()
  269. {
  270. assertex(result && result != Py_None);
  271. return (__int64) PyLong_AsUnsignedLongLong(result);
  272. }
  273. virtual void getStringResult(size32_t &__chars, char * &__result)
  274. {
  275. assertex(result && result != Py_None);
  276. if (PyString_Check(result))
  277. {
  278. const char * text = PyString_AsString(result);
  279. checkPythonError();
  280. size_t lenBytes = PyString_Size(result);
  281. rtlStrToStrX(__chars, __result, lenBytes, text);
  282. }
  283. else
  284. rtlFail(0, "Python type mismatch - return value was not a string");
  285. }
  286. virtual void getUTF8Result(size32_t &__chars, char * &__result)
  287. {
  288. assertex(result && result != Py_None);
  289. if (PyUnicode_Check(result))
  290. {
  291. OwnedPyObject utf8 = PyUnicode_AsUTF8String(result);
  292. checkPythonError();
  293. size_t lenBytes = PyString_Size(utf8);
  294. const char * text = PyString_AsString(utf8);
  295. checkPythonError();
  296. size32_t numchars = rtlUtf8Length(lenBytes, text);
  297. rtlUtf8ToUtf8X(__chars, __result, numchars, text);
  298. }
  299. else
  300. rtlFail(0, "Python type mismatch - return value was not a unicode string");
  301. }
  302. virtual void getUnicodeResult(size32_t &__chars, UChar * &__result)
  303. {
  304. assertex(result && result != Py_None);
  305. if (PyUnicode_Check(result))
  306. {
  307. OwnedPyObject utf8 = PyUnicode_AsUTF8String(result);
  308. checkPythonError();
  309. size_t lenBytes = PyString_Size(utf8);
  310. const char * text = PyString_AsString(utf8);
  311. checkPythonError();
  312. size32_t numchars = rtlUtf8Length(lenBytes, text);
  313. rtlUtf8ToUnicodeX(__chars, __result, numchars, text);
  314. }
  315. else
  316. rtlFail(0, "Python type mismatch - return value was not a unicode string");
  317. }
  318. protected:
  319. PythonThreadContext *sharedCtx;
  320. OwnedPyObject locals;
  321. OwnedPyObject globals;
  322. OwnedPyObject result;
  323. OwnedPyObject script;
  324. };
  325. class Python27EmbedScriptContext : public Python27EmbedContextBase
  326. {
  327. public:
  328. Python27EmbedScriptContext(PythonThreadContext *_sharedCtx, const char *options)
  329. : Python27EmbedContextBase(_sharedCtx)
  330. {
  331. }
  332. ~Python27EmbedScriptContext()
  333. {
  334. }
  335. virtual void bindBooleanParam(const char *name, bool val)
  336. {
  337. OwnedPyObject vval = PyBool_FromLong(val ? 1 : 0);
  338. PyDict_SetItemString(locals, name, vval);
  339. }
  340. virtual void bindRealParam(const char *name, double val)
  341. {
  342. OwnedPyObject vval = PyFloat_FromDouble(val);
  343. PyDict_SetItemString(locals, name, vval);
  344. }
  345. virtual void bindSignedParam(const char *name, __int64 val)
  346. {
  347. OwnedPyObject vval = PyLong_FromLongLong(val);
  348. PyDict_SetItemString(locals, name, vval);
  349. }
  350. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  351. {
  352. OwnedPyObject vval = PyLong_FromUnsignedLongLong(val);
  353. PyDict_SetItemString(locals, name, vval);
  354. }
  355. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  356. {
  357. OwnedPyObject vval = PyString_FromStringAndSize(val, len);
  358. PyDict_SetItemString(locals, name, vval);
  359. }
  360. virtual void bindVStringParam(const char *name, const char *val)
  361. {
  362. OwnedPyObject vval = PyString_FromString(val);
  363. PyDict_SetItemString(locals, name, vval);
  364. }
  365. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  366. {
  367. size32_t sizeBytes = rtlUtf8Size(chars, val);
  368. OwnedPyObject vval = PyUnicode_FromStringAndSize(val, sizeBytes); // NOTE - requires size in bytes not chars
  369. PyDict_SetItemString(locals, name, vval);
  370. }
  371. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  372. {
  373. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  374. unsigned unicodeChars;
  375. char *unicode;
  376. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  377. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  378. OwnedPyObject vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  379. checkPythonError();
  380. PyDict_SetItemString(locals, name, vval);
  381. rtlFree(unicode);
  382. }
  383. virtual void importFunction(const char *text)
  384. {
  385. throwUnexpected();
  386. }
  387. virtual void compileEmbeddedScript(const char *text)
  388. {
  389. script.setown(sharedCtx->compileEmbeddedScript(text));
  390. }
  391. virtual void callFunction()
  392. {
  393. result.setown(PyEval_EvalCode((PyCodeObject *) script.get(), locals, globals));
  394. checkPythonError();
  395. if (!result || result == Py_None)
  396. result.set(PyDict_GetItemString(locals, "__result__"));
  397. if (!result || result == Py_None)
  398. result.set(PyDict_GetItemString(globals, "__result__"));
  399. }
  400. };
  401. class Python27EmbedImportContext : public Python27EmbedContextBase
  402. {
  403. public:
  404. Python27EmbedImportContext(PythonThreadContext *_sharedCtx, const char *options)
  405. : Python27EmbedContextBase(_sharedCtx)
  406. {
  407. argcount = 0;
  408. }
  409. ~Python27EmbedImportContext()
  410. {
  411. }
  412. virtual void bindBooleanParam(const char *name, bool val)
  413. {
  414. addArg(PyBool_FromLong(val ? 1 : 0));
  415. }
  416. virtual void bindRealParam(const char *name, double val)
  417. {
  418. addArg(PyFloat_FromDouble(val));
  419. }
  420. virtual void bindSignedParam(const char *name, __int64 val)
  421. {
  422. addArg(PyLong_FromLongLong(val));
  423. }
  424. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  425. {
  426. addArg(PyLong_FromUnsignedLongLong(val));
  427. }
  428. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  429. {
  430. addArg(PyString_FromStringAndSize(val, len));
  431. }
  432. virtual void bindVStringParam(const char *name, const char *val)
  433. {
  434. addArg(PyString_FromString(val));
  435. }
  436. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  437. {
  438. size32_t sizeBytes = rtlUtf8Size(chars, val);
  439. addArg(PyUnicode_FromStringAndSize(val, sizeBytes)); // NOTE - requires size in bytes not chars
  440. }
  441. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  442. {
  443. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  444. unsigned unicodeChars;
  445. char *unicode;
  446. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  447. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  448. PyObject *vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  449. checkPythonError();
  450. addArg(vval);
  451. rtlFree(unicode);
  452. }
  453. virtual void importFunction(const char *text)
  454. {
  455. script.setown(sharedCtx->importFunction(text));
  456. }
  457. virtual void compileEmbeddedScript(const char *text)
  458. {
  459. throwUnexpected();
  460. }
  461. virtual void callFunction()
  462. {
  463. result.setown(PyObject_CallObject(script, args));
  464. checkPythonError();
  465. }
  466. private:
  467. void addArg(PyObject *arg)
  468. {
  469. if (argcount)
  470. _PyTuple_Resize(args.ref(), argcount+1);
  471. else
  472. args.setown(PyTuple_New(1));
  473. PyTuple_SET_ITEM((PyTupleObject *) args.get(), argcount++, arg); // Note - 'steals' the arg reference
  474. }
  475. int argcount;
  476. OwnedPyObject args;
  477. };
  478. class Python27EmbedContext : public CInterfaceOf<IEmbedContext>
  479. {
  480. public:
  481. virtual IEmbedFunctionContext *createFunctionContext(bool isImport, const char *options)
  482. {
  483. if (!threadContext)
  484. {
  485. threadContext = new PythonThreadContext;
  486. threadHookChain = addThreadTermFunc(releaseContext);
  487. }
  488. if (isImport)
  489. return new Python27EmbedImportContext(threadContext, options);
  490. else
  491. return new Python27EmbedScriptContext(threadContext, options);
  492. }
  493. };
  494. extern IEmbedContext* getEmbedContext()
  495. {
  496. return new Python27EmbedContext;
  497. }
  498. extern bool syntaxCheck(const char *script)
  499. {
  500. return true; // MORE
  501. }
  502. } // namespace