pyembed.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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(size32_t lenChars, const char *utf)
  123. {
  124. size32_t bytes = rtlUtf8Size(lenChars, utf);
  125. StringBuffer text(bytes, utf);
  126. if (!prevtext || strcmp(text, prevtext) != 0)
  127. {
  128. prevtext.clear();
  129. // Name should be in the form module.function
  130. const char *funcname = strrchr(text, '.');
  131. if (!funcname)
  132. rtlFail(0, "Expected module.function");
  133. StringBuffer modname(funcname-text, text);
  134. funcname++; // skip the '.'
  135. // If the modname is preceded by a path, add it to the python path before importing
  136. const char *pathsep = strrchr(modname, PATHSEPCHAR);
  137. if (pathsep)
  138. {
  139. StringBuffer path(pathsep-modname, modname);
  140. modname.remove(0, 1+pathsep-modname);
  141. PyObject *sys_path = PySys_GetObject((char *) "path");
  142. OwnedPyObject new_path = PyString_FromString(path);
  143. if (sys_path)
  144. {
  145. PyList_Append(sys_path, new_path);
  146. checkPythonError();
  147. }
  148. }
  149. module.setown(PyImport_ImportModule(modname));
  150. checkPythonError();
  151. PyObject *dict = PyModule_GetDict(module); // this is a borrowed reference and does not need to be released
  152. script.set(PyDict_GetItemString(dict, funcname));
  153. checkPythonError();
  154. if (!script || !PyCallable_Check(script))
  155. rtlFail(0, "Object is not callable");
  156. prevtext.set(text);
  157. }
  158. return script.getLink();
  159. }
  160. inline PyObject *compileEmbeddedScript(size32_t lenChars, const char *utf)
  161. {
  162. size32_t bytes = rtlUtf8Size(lenChars, utf);
  163. StringBuffer text(bytes, utf);
  164. if (!prevtext || strcmp(text, prevtext) != 0)
  165. {
  166. prevtext.clear();
  167. // Try compiling as a eval first... if that fails, try as a script.
  168. script.setown(Py_CompileString(text, "", Py_eval_input));
  169. if (!script)
  170. {
  171. PyErr_Clear();
  172. StringBuffer wrapped;
  173. wrapPythonText(wrapped, text);
  174. script.setown(Py_CompileString(wrapped, "<embed>", Py_file_input));
  175. }
  176. checkPythonError();
  177. prevtext.set(text);
  178. }
  179. return script.getLink();
  180. }
  181. private:
  182. static StringBuffer &wrapPythonText(StringBuffer &out, const char *in)
  183. {
  184. out.append("def __user__():\n ");
  185. char c;
  186. while ((c = *in++) != '\0')
  187. {
  188. out.append(c);
  189. if (c=='\n')
  190. out.append(" ");
  191. }
  192. out.append("\n__result__ = __user__()\n");
  193. return out;
  194. }
  195. GILstateWrapper GILState;
  196. OwnedPyObject module;
  197. OwnedPyObject script;
  198. StringAttr prevtext;
  199. };
  200. static __thread PythonThreadContext* threadContext; // We reuse per thread, for speed
  201. static __thread ThreadTermFunc threadHookChain;
  202. static void releaseContext()
  203. {
  204. delete threadContext;
  205. threadContext = NULL;
  206. if (threadHookChain)
  207. (*threadHookChain)();
  208. }
  209. // Use a global object to ensure that the Python interpreter is initialized on main thread
  210. static class Python27GlobalState
  211. {
  212. public:
  213. Python27GlobalState()
  214. {
  215. // Initialize the Python Interpreter
  216. Py_Initialize();
  217. PyEval_InitThreads();
  218. tstate = PyEval_SaveThread();
  219. }
  220. ~Python27GlobalState()
  221. {
  222. if (threadContext)
  223. delete threadContext; // The one on the main thread won't get picked up by the thread hook mechanism
  224. threadContext = NULL;
  225. PyEval_RestoreThread(tstate);
  226. // Finish the Python Interpreter
  227. Py_Finalize();
  228. }
  229. protected:
  230. PyThreadState *tstate;
  231. } globalState;
  232. // Each call to a Python function will use a new Python27EmbedFunctionContext object
  233. // This takes care of ensuring that the Python GIL is locked while we are executing python code,
  234. // and released when we are not
  235. class Python27EmbedContextBase : public CInterfaceOf<IEmbedFunctionContext>
  236. {
  237. public:
  238. Python27EmbedContextBase(PythonThreadContext *_sharedCtx)
  239. : sharedCtx(_sharedCtx)
  240. {
  241. PyEval_RestoreThread(sharedCtx->threadState);
  242. locals.setown(PyDict_New());
  243. globals.setown(PyDict_New());
  244. PyDict_SetItemString(locals, "__builtins__", PyEval_GetBuiltins()); // required for import to work
  245. }
  246. ~Python27EmbedContextBase()
  247. {
  248. // We need to clear these before calling savethread, or we won't own the GIL
  249. locals.clear();
  250. globals.clear();
  251. result.clear();
  252. script.clear();
  253. sharedCtx->threadState = PyEval_SaveThread();
  254. }
  255. virtual bool getBooleanResult()
  256. {
  257. assertex(result);
  258. if (!PyBool_Check(result))
  259. throw MakeStringException(MSGAUD_user, 0, "pyembed: Type mismatch on result");
  260. return result == Py_True;
  261. }
  262. virtual double getRealResult()
  263. {
  264. assertex(result && result != Py_None);
  265. return (__int64) PyFloat_AsDouble(result);
  266. }
  267. virtual __int64 getSignedResult()
  268. {
  269. assertex(result && result != Py_None);
  270. return (__int64) PyLong_AsLongLong(result);
  271. }
  272. virtual unsigned __int64 getUnsignedResult()
  273. {
  274. assertex(result && result != Py_None);
  275. return (__int64) PyLong_AsUnsignedLongLong(result);
  276. }
  277. virtual void getStringResult(size32_t &__chars, char * &__result)
  278. {
  279. assertex(result && result != Py_None);
  280. if (PyString_Check(result))
  281. {
  282. const char * text = PyString_AsString(result);
  283. checkPythonError();
  284. size_t lenBytes = PyString_Size(result);
  285. rtlStrToStrX(__chars, __result, lenBytes, text);
  286. }
  287. else
  288. rtlFail(0, "Python type mismatch - return value was not a string");
  289. }
  290. virtual void getUTF8Result(size32_t &__chars, char * &__result)
  291. {
  292. assertex(result && result != Py_None);
  293. if (PyUnicode_Check(result))
  294. {
  295. OwnedPyObject utf8 = PyUnicode_AsUTF8String(result);
  296. checkPythonError();
  297. size_t lenBytes = PyString_Size(utf8);
  298. const char * text = PyString_AsString(utf8);
  299. checkPythonError();
  300. size32_t numchars = rtlUtf8Length(lenBytes, text);
  301. rtlUtf8ToUtf8X(__chars, __result, numchars, text);
  302. }
  303. else
  304. rtlFail(0, "Python type mismatch - return value was not a unicode string");
  305. }
  306. virtual void getUnicodeResult(size32_t &__chars, UChar * &__result)
  307. {
  308. assertex(result && result != Py_None);
  309. if (PyUnicode_Check(result))
  310. {
  311. OwnedPyObject utf8 = PyUnicode_AsUTF8String(result);
  312. checkPythonError();
  313. size_t lenBytes = PyString_Size(utf8);
  314. const char * text = PyString_AsString(utf8);
  315. checkPythonError();
  316. size32_t numchars = rtlUtf8Length(lenBytes, text);
  317. rtlUtf8ToUnicodeX(__chars, __result, numchars, text);
  318. }
  319. else
  320. rtlFail(0, "Python type mismatch - return value was not a unicode string");
  321. }
  322. protected:
  323. PythonThreadContext *sharedCtx;
  324. OwnedPyObject locals;
  325. OwnedPyObject globals;
  326. OwnedPyObject result;
  327. OwnedPyObject script;
  328. };
  329. class Python27EmbedScriptContext : public Python27EmbedContextBase
  330. {
  331. public:
  332. Python27EmbedScriptContext(PythonThreadContext *_sharedCtx, const char *options)
  333. : Python27EmbedContextBase(_sharedCtx)
  334. {
  335. }
  336. ~Python27EmbedScriptContext()
  337. {
  338. }
  339. virtual void bindBooleanParam(const char *name, bool val)
  340. {
  341. OwnedPyObject vval = PyBool_FromLong(val ? 1 : 0);
  342. PyDict_SetItemString(locals, name, vval);
  343. }
  344. virtual void bindRealParam(const char *name, double val)
  345. {
  346. OwnedPyObject vval = PyFloat_FromDouble(val);
  347. PyDict_SetItemString(locals, name, vval);
  348. }
  349. virtual void bindSignedParam(const char *name, __int64 val)
  350. {
  351. OwnedPyObject vval = PyLong_FromLongLong(val);
  352. PyDict_SetItemString(locals, name, vval);
  353. }
  354. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  355. {
  356. OwnedPyObject vval = PyLong_FromUnsignedLongLong(val);
  357. PyDict_SetItemString(locals, name, vval);
  358. }
  359. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  360. {
  361. OwnedPyObject vval = PyString_FromStringAndSize(val, len);
  362. PyDict_SetItemString(locals, name, vval);
  363. }
  364. virtual void bindVStringParam(const char *name, const char *val)
  365. {
  366. OwnedPyObject vval = PyString_FromString(val);
  367. PyDict_SetItemString(locals, name, vval);
  368. }
  369. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  370. {
  371. size32_t sizeBytes = rtlUtf8Size(chars, val);
  372. OwnedPyObject vval = PyUnicode_FromStringAndSize(val, sizeBytes); // NOTE - requires size in bytes not chars
  373. PyDict_SetItemString(locals, name, vval);
  374. }
  375. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  376. {
  377. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  378. unsigned unicodeChars;
  379. char *unicode;
  380. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  381. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  382. OwnedPyObject vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  383. checkPythonError();
  384. PyDict_SetItemString(locals, name, vval);
  385. rtlFree(unicode);
  386. }
  387. virtual void importFunction(size32_t lenChars, const char *text)
  388. {
  389. throwUnexpected();
  390. }
  391. virtual void compileEmbeddedScript(size32_t lenChars, const char *utf)
  392. {
  393. script.setown(sharedCtx->compileEmbeddedScript(lenChars, utf));
  394. }
  395. virtual void callFunction()
  396. {
  397. result.setown(PyEval_EvalCode((PyCodeObject *) script.get(), locals, globals));
  398. checkPythonError();
  399. if (!result || result == Py_None)
  400. result.set(PyDict_GetItemString(locals, "__result__"));
  401. if (!result || result == Py_None)
  402. result.set(PyDict_GetItemString(globals, "__result__"));
  403. }
  404. };
  405. class Python27EmbedImportContext : public Python27EmbedContextBase
  406. {
  407. public:
  408. Python27EmbedImportContext(PythonThreadContext *_sharedCtx, const char *options)
  409. : Python27EmbedContextBase(_sharedCtx)
  410. {
  411. argcount = 0;
  412. }
  413. ~Python27EmbedImportContext()
  414. {
  415. }
  416. virtual void bindBooleanParam(const char *name, bool val)
  417. {
  418. addArg(PyBool_FromLong(val ? 1 : 0));
  419. }
  420. virtual void bindRealParam(const char *name, double val)
  421. {
  422. addArg(PyFloat_FromDouble(val));
  423. }
  424. virtual void bindSignedParam(const char *name, __int64 val)
  425. {
  426. addArg(PyLong_FromLongLong(val));
  427. }
  428. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  429. {
  430. addArg(PyLong_FromUnsignedLongLong(val));
  431. }
  432. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  433. {
  434. addArg(PyString_FromStringAndSize(val, len));
  435. }
  436. virtual void bindVStringParam(const char *name, const char *val)
  437. {
  438. addArg(PyString_FromString(val));
  439. }
  440. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  441. {
  442. size32_t sizeBytes = rtlUtf8Size(chars, val);
  443. addArg(PyUnicode_FromStringAndSize(val, sizeBytes)); // NOTE - requires size in bytes not chars
  444. }
  445. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  446. {
  447. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  448. unsigned unicodeChars;
  449. char *unicode;
  450. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  451. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  452. PyObject *vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  453. checkPythonError();
  454. addArg(vval);
  455. rtlFree(unicode);
  456. }
  457. virtual void importFunction(size32_t lenChars, const char *utf)
  458. {
  459. script.setown(sharedCtx->importFunction(lenChars, utf));
  460. }
  461. virtual void compileEmbeddedScript(size32_t len, const char *text)
  462. {
  463. throwUnexpected();
  464. }
  465. virtual void callFunction()
  466. {
  467. result.setown(PyObject_CallObject(script, args));
  468. checkPythonError();
  469. }
  470. private:
  471. void addArg(PyObject *arg)
  472. {
  473. if (argcount)
  474. _PyTuple_Resize(args.ref(), argcount+1);
  475. else
  476. args.setown(PyTuple_New(1));
  477. PyTuple_SET_ITEM((PyTupleObject *) args.get(), argcount++, arg); // Note - 'steals' the arg reference
  478. }
  479. int argcount;
  480. OwnedPyObject args;
  481. };
  482. class Python27EmbedContext : public CInterfaceOf<IEmbedContext>
  483. {
  484. public:
  485. virtual IEmbedFunctionContext *createFunctionContext(bool isImport, const char *options)
  486. {
  487. if (!threadContext)
  488. {
  489. threadContext = new PythonThreadContext;
  490. threadHookChain = addThreadTermFunc(releaseContext);
  491. }
  492. if (isImport)
  493. return new Python27EmbedImportContext(threadContext, options);
  494. else
  495. return new Python27EmbedScriptContext(threadContext, options);
  496. }
  497. };
  498. extern IEmbedContext* getEmbedContext()
  499. {
  500. return new Python27EmbedContext;
  501. }
  502. extern bool syntaxCheck(const char *script)
  503. {
  504. return true; // MORE
  505. }
  506. } // namespace