Salome HOME
2720bc308c9f010c2e5466281828a336991fb618
[modules/shaper.git] / src / Config / Config_ModuleReader.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <pyconfig.h>
21
22 #include <Config_Keywords.h>
23 #include <Config_Common.h>
24 #include <Config_ModuleReader.h>
25 #include <Config_FeatureReader.h>
26 #include <Config_PluginMessage.h>
27 #include <Events_InfoMessage.h>
28
29 #include <libxml/parser.h>
30 #include <libxml/tree.h>
31
32 // Have to be included before std headers
33 #include <Python.h>
34
35 //Necessary for cerr
36 #include <iostream>
37 #include <algorithm>
38
39 #ifdef WIN32
40 #include <windows.h>
41 #pragma warning(disable : 4996) // for getenv
42 #else
43 #include <dlfcn.h>
44 #endif
45
46 std::map<std::string, Config_ModuleReader::PluginType> Config_ModuleReader::myPluginTypes;
47 std::set<std::string> Config_ModuleReader::myDependencyModules;
48
49 Config_ModuleReader::Config_ModuleReader(const char* theEventGenerated)
50     : Config_XMLReader(PLUGIN_FILE),
51       myEventGenerated(theEventGenerated)
52 {
53 }
54
55 Config_ModuleReader::~Config_ModuleReader()
56 {
57 }
58
59 const std::map<std::string, std::string>& Config_ModuleReader::featuresInFiles() const
60 {
61   return myFeaturesInFiles;
62 }
63
64 const std::set<std::string>& Config_ModuleReader::modulePluginFiles() const
65 {
66   return myPluginFiles;
67 }
68
69 /*!
70  * Get module name from plugins.xml
71  * (property "module")
72  */
73 std::string Config_ModuleReader::getModuleName()
74 {
75   xmlNodePtr aRoot = findRoot();
76   return getProperty(aRoot, PLUGINS_MODULE);
77 }
78
79
80 void Config_ModuleReader::addFeature(const std::string& theFeatureName,
81                                      const std::string& thePluginConfig)
82 {
83   if (myFeaturesInFiles.count(theFeatureName)) {
84     std::string anErrorMsg = "Can not register feature '%1' in plugin '%2'."
85       " There is a feature with the same ID.";
86     Events_InfoMessage("Config_ModuleReader", anErrorMsg)
87       .arg(theFeatureName).arg(thePluginConfig).send();
88     return;
89   }
90
91   myFeaturesInFiles[theFeatureName] = thePluginConfig;
92 }
93
94 void Config_ModuleReader::processNode(xmlNodePtr theNode)
95 {
96   if (isNode(theNode, NODE_PLUGIN, NULL)) {
97     if (!hasRequiredModules(theNode))
98       return;
99     std::string aPluginConf = getProperty(theNode, PLUGIN_CONFIG);
100     if (!aPluginConf.empty())
101       myPluginFiles.insert(aPluginConf);
102     std::string aPluginLibrary = getProperty(theNode, PLUGIN_LIBRARY);
103     std::string aPluginScript = getProperty(theNode, PLUGIN_SCRIPT);
104     std::string aPluginName = addPlugin(aPluginLibrary, aPluginScript, aPluginConf);
105     std::string aUsesPlugin = getProperty(theNode, PLUGIN_USES);
106     if (!aUsesPlugin.empty()) { // send information about the plugin dependencies
107       std::shared_ptr<Config_PluginMessage> aMess(new Config_PluginMessage(
108         Events_Loop::loop()->eventByName(Config_PluginMessage::EVENT_ID()), aPluginName));
109       aMess->setUses(aUsesPlugin);
110       Events_Loop::loop()->send(aMess);
111     }
112
113     std::list<std::string> aFeatures = importPlugin(aPluginName, aPluginConf);
114     std::list<std::string>::iterator it = aFeatures.begin();
115     for (; it != aFeatures.end(); it++) {
116       addFeature(*it, aPluginConf);
117     }
118   }
119 }
120
121 bool Config_ModuleReader::processChildren(xmlNodePtr theNode)
122 {
123   return isNode(theNode, NODE_PLUGINS, NULL);
124 }
125
126 bool Config_ModuleReader::hasRequiredModules(xmlNodePtr theNode) const
127 {
128   std::string aRequiredModule = normalize(getProperty(theNode, PLUGIN_DEPENDENCY));
129   if(aRequiredModule.empty())
130     return true;
131   std::set<std::string>::iterator it = myDependencyModules.begin();
132   for ( ; it != myDependencyModules.end(); it++ ) {
133     if (*it == aRequiredModule) return true;
134   }
135   return false;
136 }
137
138 std::list<std::string> Config_ModuleReader::importPlugin(const std::string& thePluginLibrary,
139                                                          const std::string& thePluginXmlConf)
140 {
141   if (thePluginXmlConf.empty()) {  //probably a third party library
142     loadLibrary(thePluginLibrary);
143     return std::list<std::string>();
144   }
145
146   Config_FeatureReader aReader = Config_FeatureReader(thePluginXmlConf,
147                                                       thePluginLibrary,
148                                                       myEventGenerated);
149   aReader.readAll();
150   return aReader.features();
151 }
152
153 std::string Config_ModuleReader::addPlugin(const std::string& aPluginLibrary,
154                                            const std::string& aPluginScript,
155                                            const std::string& aPluginConf)
156 {
157   PluginType aType = Config_ModuleReader::Binary;
158   std::string aPluginName;
159   if (!aPluginLibrary.empty()) {
160     aPluginName = aPluginLibrary;
161     if (aPluginConf.empty()) {
162       aType = Config_ModuleReader::Intrenal;
163     }
164   } else if (!aPluginScript.empty()) {
165     aPluginName = aPluginScript;
166     aType = Config_ModuleReader::Python;
167   }
168   if(!aPluginName.empty()) {
169     myPluginTypes[aPluginName] = aType;
170   }
171   addDependencyModule(aPluginName);
172   return aPluginName;
173 }
174
175 void Config_ModuleReader::loadPlugin(const std::string& thePluginName)
176 {
177   // informs model that plugin loading is started
178   static const Events_ID kEVENT_ID =
179     Events_Loop::loop()->eventByName(Config_PluginMessage::EVENT_ID());
180   std::shared_ptr<Config_PluginMessage> aMess(new Config_PluginMessage(kEVENT_ID, thePluginName));
181   Events_Loop::loop()->send(aMess);
182
183   PluginType aType = Config_ModuleReader::Binary;
184   if(myPluginTypes.find(thePluginName) != myPluginTypes.end()) {
185     aType = myPluginTypes.at(thePluginName);
186   }
187   switch (aType) {
188     case Config_ModuleReader::Python:
189       loadScript(thePluginName);
190       break;
191     case Config_ModuleReader::Binary:
192     case Config_ModuleReader::Intrenal:
193     default:
194       loadLibrary(thePluginName);
195       break;
196   }
197 }
198
199 void Config_ModuleReader::loadScript(const std::string& theFileName, bool theSendErr)
200 {
201   /* acquire python thread */
202   PyGILState_STATE gstate = PyGILState_Ensure();
203
204   PyObject* module = PyImport_ImportModule(theFileName.c_str());
205   if (!module) {
206     std::string anErrorMsg = "An error occurred while importing " + theFileName;
207     //Get detailed error message:
208     if (PyErr_Occurred()) {
209       PyObject *pstr, *ptype, *pvalue, *ptraceback;
210       PyErr_Fetch(&ptype, &pvalue, &ptraceback);
211       PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
212       pstr = PyObject_Str(pvalue);
213       std::string aPyError = std::string(PyUnicode_AsUTF8(pstr));
214       if (!aPyError.empty()) {
215         anErrorMsg += ":\n" + aPyError;
216       }
217       Py_XDECREF(pstr);
218       Py_XDECREF(ptype);
219       Py_XDECREF(pvalue);
220       Py_XDECREF(ptraceback);
221     }
222     if (theSendErr)
223       Events_InfoMessage("Config_ModuleReader", anErrorMsg).send();
224   }
225
226   /* release python thread */
227   PyGILState_Release(gstate);
228 }
229
230 void Config_ModuleReader::loadLibrary(const std::string& theLibName)
231 {
232   std::string aFileName = library(theLibName);
233   if (aFileName.empty())
234     return;
235
236   #ifdef WIN32
237   HINSTANCE aModLib = ::LoadLibraryA(aFileName.c_str());
238   #else
239   void* aModLib = dlopen( aFileName.c_str(), RTLD_LAZY | RTLD_GLOBAL );
240   #endif
241   if(!aModLib && theLibName != "DFBrowser") { // don't show error for internal debugging tool
242 // LCOV_EXCL_START
243     std::string anErrorMsg = "Failed to load " + aFileName;
244     #ifdef WIN32
245     DWORD   dwLastError = ::GetLastError();
246     LPSTR messageBuffer = NULL;
247     size_t size = ::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
248                                    FORMAT_MESSAGE_FROM_SYSTEM |
249                                    FORMAT_MESSAGE_IGNORE_INSERTS,
250                                    NULL,
251                                    dwLastError,
252                                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
253                                    (LPSTR)&messageBuffer, 0, NULL);
254     anErrorMsg += ": " +  std::string(messageBuffer, size);
255     #else
256     anErrorMsg += ": " + std::string(dlerror());
257     #endif
258     std::cerr << anErrorMsg << std::endl;
259     Events_InfoMessage("Config_ModuleReader", anErrorMsg).send();
260 // LCOV_EXCL_STOP
261   }
262 }
263
264 void Config_ModuleReader::addDependencyModule(const std::string& theModuleName)
265 {
266   myDependencyModules.insert(normalize(theModuleName));
267 }
268