pyembed.cpp 18 KB

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