1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // SALOME Container : implementation of container and engine for Kernel
24 // File : Container_i.cxx
25 // Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
28 //#define private public
33 #include <sys/types.h>
46 #include "utilities.h"
47 #include <SALOMEconfig.h>
48 #include CORBA_SERVER_HEADER(SALOME_Component)
49 #include CORBA_SERVER_HEADER(SALOME_Exception)
50 #include <pthread.h> // must be before Python.h !
51 #include "SALOME_Container_i.hxx"
52 #include "SALOME_Component_i.hxx"
53 #include "SALOME_FileRef_i.hxx"
54 #include "SALOME_FileTransfer_i.hxx"
55 #include "Salome_file_i.hxx"
56 #include "SALOME_NamingService.hxx"
57 #include "Basics_Utils.hxx"
64 #include "Container_init_python.hxx"
66 bool _Sleeping = false ;
68 // // Needed by multi-threaded Python --- Supervision
72 extern "C" {void ActSigIntHandler() ; }
74 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
76 extern "C" {void SigIntHandler( int ) ; }
82 #define ENGINESO "Engine.dylib"
84 #define ENGINESO "Engine.so"
88 #define ENGINESO "Engine.dll"
99 std::map<std::string, int> Engines_Container_i::_cntInstances_map;
100 std::map<std::string, void *> Engines_Container_i::_library_map;
101 std::map<std::string, void *> Engines_Container_i::_toRemove_map;
102 omni_mutex Engines_Container_i::_numInstanceMutex ;
104 static PyObject* _pyCont;
106 int checkifexecutable(const std::string&);
107 int findpathof(const std::string& path, std::string&, const std::string&);
109 /*! \class Engines_Container_i
110 * \brief C++ implementation of Engines::Container interface
115 //=============================================================================
117 * Default constructor, not for use
119 //=============================================================================
121 Engines_Container_i::Engines_Container_i () :
122 _numInstance(0),_id(0),_NS(0)
126 //=============================================================================
130 //=============================================================================
132 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
133 PortableServer::POA_ptr poa,
134 char *containerName ,
135 int argc , char* argv[],
137 bool isServantAloneInProcess
139 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess),_id(0),_NS(0)
141 _pid = (long)getpid();
149 std::string hostname = Kernel_Utils::GetHostname();
151 MESSAGE(hostname << " " << getpid() <<
152 " Engines_Container_i starting argc " <<
153 _argc << " Thread " << pthread_self() ) ;
155 MESSAGE(hostname << " " << _getpid() <<
156 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
162 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
168 INFOS("SALOME_Container usage : SALOME_Container ServerName");
172 _isSupervContainer = false;
174 _orb = CORBA::ORB::_duplicate(orb) ;
175 _poa = PortableServer::POA::_duplicate(poa) ;
177 // Pour les containers paralleles: il ne faut pas enregistrer et activer
178 // le container generique, mais le container specialise
182 _id = _poa->activate_object(this);
183 _NS = new SALOME_NamingService();
184 _NS->init_orb( _orb ) ;
185 CORBA::Object_var obj=_poa->id_to_reference(*_id);
186 Engines::Container_var pCont
187 = Engines::Container::_narrow(obj);
190 _containerName = _NS->BuildContainerNameForNS(containerName,
192 SCRUTE(_containerName);
193 _NS->Register(pCont, _containerName.c_str());
194 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
198 // import SALOME_Container
199 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
201 CORBA::String_var sior = _orb->object_to_string(pCont);
202 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
203 myCommand += _containerName + "','";
208 //[RNV]: Comment the PyEval_AcquireLock() and PyEval_ReleaseLock() because this
209 //approach leads to the deadlock of the main thread of the application on Windows platform
210 //in case if cppContainer runs in the standalone mode. The problem with the PyThreadState
211 //described by ABN seems not reproduced, to be checked carefully later...
212 PyGILState_STATE gstate = PyGILState_Ensure();
214 //// [ABN]: using the PyGILState* API here is unstable. omniORB logic is invoked
215 //// by the Python code executed below, and in some (random) cases, the Python code
216 //// execution ends with a PyThreadState which was not the one we have here.
217 //// (TODO: understand why ...)
218 //// To be on the safe side we get and load the thread state ourselves:
219 //PyEval_AcquireLock(); // get GIL
220 //PyThreadState * mainThreadState = PyThreadState_Get();
221 //PyThreadState_Swap(mainThreadState);
224 // mpv: this is temporary solution: there is a unregular crash if not
227 // first element is the path to Registry.dll, but it's wrong
228 PyRun_SimpleString("import sys\n");
229 PyRun_SimpleString("sys.path = sys.path[1:]\n");
231 PyRun_SimpleString("import SALOME_Container\n");
232 PyRun_SimpleString((char*)myCommand.c_str());
233 PyObject *mainmod = PyImport_AddModule("__main__");
234 PyObject *globals = PyModule_GetDict(mainmod);
235 _pyCont = PyDict_GetItemString(globals, "pyCont");
237 //PyThreadState_Swap(NULL);
238 //PyEval_ReleaseLock();
239 PyGILState_Release(gstate);
241 fileTransfer_i* aFileTransfer = new fileTransfer_i();
242 CORBA::Object_var obref=aFileTransfer->_this();
243 _fileTransfer = Engines::fileTransfer::_narrow(obref);
244 aFileTransfer->_remove_ref();
248 //=============================================================================
252 //=============================================================================
254 Engines_Container_i::~Engines_Container_i()
256 MESSAGE("Container_i::~Container_i()");
261 for(std::map<std::string,Engines::PyNode_var>::iterator it=_dftPyNode.begin();it!=_dftPyNode.end();it++)
263 Engines::PyNode_var tmpVar((*it).second);
264 if(!CORBA::is_nil(tmpVar))
265 tmpVar->UnRegister();
267 for(std::map<std::string,Engines::PyScriptNode_var>::iterator it=_dftPyScriptNode.begin();it!=_dftPyScriptNode.end();it++)
269 Engines::PyScriptNode_var tmpVar((*it).second);
270 if(!CORBA::is_nil(tmpVar))
271 tmpVar->UnRegister();
275 //=============================================================================
276 //! Get container name
278 * CORBA attribute: Container name (see constructor)
280 //=============================================================================
282 char* Engines_Container_i::name()
284 return CORBA::string_dup(_containerName.c_str()) ;
287 //=============================================================================
288 //! Get container working directory
290 * CORBA attribute: Container working directory
292 //=============================================================================
294 char* Engines_Container_i::workingdir()
298 return CORBA::string_dup(wd) ;
301 //=============================================================================
302 //! Get container log file name
304 * CORBA attribute: Container log file name
306 //=============================================================================
308 char* Engines_Container_i::logfilename()
310 return CORBA::string_dup(_logfilename.c_str()) ;
313 //! Set container log file name
314 void Engines_Container_i::logfilename(const char* name)
319 //=============================================================================
320 //! Get container host name
322 * CORBA method: Get the hostName of the Container (without domain extensions)
324 //=============================================================================
326 char* Engines_Container_i::getHostName()
328 std::string s = Kernel_Utils::GetHostname();
329 // MESSAGE("Engines_Container_i::getHostName " << s);
330 return CORBA::string_dup(s.c_str()) ;
333 //=============================================================================
334 //! Get container PID
336 * CORBA method: Get the PID (process identification) of the Container
338 //=============================================================================
340 CORBA::Long Engines_Container_i::getPID()
342 return (CORBA::Long)getpid();
345 //=============================================================================
346 //! Ping the servant to check it is still alive
348 * CORBA method: check if servant is still alive
350 //=============================================================================
351 void Engines_Container_i::ping()
353 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
356 //=============================================================================
357 //! Shutdown the container
359 * CORBA method, oneway: Server shutdown.
360 * - Container name removed from naming service,
361 * - servant deactivation,
362 * - orb shutdown if no other servants in the process
364 //=============================================================================
365 void Engines_Container_i::Shutdown()
367 MESSAGE("Engines_Container_i::Shutdown()");
369 // Clear registered temporary files
370 clearTemporaryFiles();
372 /* For each component contained in this container
373 * tell it to self-destroy
375 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
376 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
380 itm->second->destroy();
382 catch(const CORBA::Exception& e)
384 // ignore this entry and continue
388 // ignore this entry and continue
391 _listInstances_map.clear();
393 _NS->Destroy_FullDirectory(_containerName.c_str());
394 _NS->Destroy_Name(_containerName.c_str());
395 if(_isServantAloneInProcess)
397 MESSAGE("Effective Shutdown of container Begins...");
398 if(!CORBA::is_nil(_orb))
403 //=============================================================================
404 //! load a component implementation
407 * \param componentName component name
408 * \param reason explains error when load fails
409 * \return true if dlopen successful or already done, false otherwise
411 //=============================================================================
413 Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
416 //=================================================================
417 // --- C++ implementation section
418 //=================================================================
420 if(load_component_CppImplementation(componentName,retso))
422 reason=CORBA::string_dup("");
425 else if(retso != "ImplementationNotFound")
427 reason=CORBA::string_dup(retso.c_str());
432 retso+=componentName;
433 retso+=": Can't find C++ implementation ";
434 retso+=std::string(LIB) + componentName + ENGINESO;
436 //=================================================================
437 // --- Python implementation section
438 //=================================================================
440 if(load_component_PythonImplementation(componentName,retpy))
442 reason=CORBA::string_dup("");
445 else if(retpy != "ImplementationNotFound")
447 reason=CORBA::string_dup(retpy.c_str());
452 retpy+=componentName;
453 retpy+=": Can't find python implementation ";
454 retpy+=componentName;
457 //=================================================================
458 // -- Executable implementation section
459 //=================================================================
461 if(load_component_ExecutableImplementation(componentName,retex))
463 reason=CORBA::string_dup("");
466 else if(retex != "ImplementationNotFound")
468 reason=CORBA::string_dup(retex.c_str());
473 retex+=componentName;
474 retex+=": Can't find executable implementation ";
475 retex+=componentName;
478 std::string ret="Component implementation not found: ";
479 ret += componentName ;
485 std::cerr << ret << std::endl;
486 reason=CORBA::string_dup(ret.c_str());
491 //=============================================================================
492 //! try to load a C++ component implementation
495 * \param componentName the name of the component (COMPONENT, for example)
496 * \param reason explains error when load fails
497 * \return true if loading is successful or already done, false otherwise
499 //=============================================================================
501 Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
503 std::string aCompName(componentName);
504 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
507 _numInstanceMutex.lock(); // lock to be alone
508 // (see decInstanceCnt, finalize_removal))
509 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
510 if (_library_map.count(impl_name) != 0)
512 MESSAGE("Library " << impl_name << " already loaded");
513 _numInstanceMutex.unlock();
517 _numInstanceMutex.unlock();
521 handle = dlopen( impl_name.c_str() , RTLD_NOW | RTLD_GLOBAL ) ;
524 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
527 char* p=getenv("DYLD_LIBRARY_PATH");
529 char* p=getenv("LD_LIBRARY_PATH");
532 path=path+SEP+"/usr/lib"+SEP+"/lib";
535 if(findpathof(path, pth, impl_name))
537 //found but not loadable
540 reason+=": C++ implementation found ";
542 reason+=" but it is not loadable. Error:\n";
544 std::cerr << reason << std::endl;
550 //continue with other implementation
551 reason="ImplementationNotFound";
557 handle = LoadLibrary( impl_name.c_str() );
560 reason="ImplementationNotFound";
566 _numInstanceMutex.lock();
567 _library_map[impl_name] = handle;
568 _numInstanceMutex.unlock();
576 //=============================================================================
577 //! try to load a Python component implementation
580 * \param componentName name of the component
581 * \param reason explains error when load fails
582 * \return true if loading is successful or already done, false otherwise
584 //=============================================================================
586 Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
588 std::string aCompName(componentName);
590 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
591 if (_library_map.count(aCompName) != 0)
593 _numInstanceMutex.unlock() ;
595 return true; // Python Component, already imported
597 _numInstanceMutex.unlock() ;
599 PyGILState_STATE gstate = PyGILState_Ensure();
600 PyObject *result = PyObject_CallMethod(_pyCont,
601 (char*)"import_component",
602 (char*)"s",componentName);
604 reason=PyUnicode_AsUTF8(result);
607 PyGILState_Release(gstate);
611 //Python component has been loaded (import componentName)
612 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
613 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
614 _numInstanceMutex.unlock() ;
615 MESSAGE("import Python: "<< aCompName <<" OK");
618 else if(reason=="ImplementationNotFound")
620 //Python implementation has not been found. Continue with other implementation
621 reason="ImplementationNotFound";
625 //Python implementation has been found but loading has failed
626 std::cerr << reason << std::endl;
631 //=============================================================================
632 //! try to load a Executable component implementation
635 * \param componentName name of the component
636 * \param reason explains error when load fails
637 * \return true if loading is successful or already done, false otherwise
639 //=============================================================================
641 Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
643 std::string aCompName(componentName);
644 std::string executable=aCompName+".exe";
649 char* p=getenv("PATH");
652 if (findpathof(path, pth, executable))
654 if(checkifexecutable(pth))
656 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
657 _library_map[executable] = (void *)1; // any non O value OK
658 _numInstanceMutex.unlock() ;
659 MESSAGE("import executable: "<< pth <<" OK");
665 reason+=": implementation found ";
667 reason+=" but it is not executable";
668 std::cerr << reason << std::endl;
672 reason="ImplementationNotFound";
677 //=============================================================================
678 //! Create a new component instance
680 * CORBA method: Creates a new servant instance of a component.
681 * The servant registers itself to naming service and Registry.
682 * \param genericRegisterName Name of the component instance to register
683 * in Registry & Name Service (without _inst_n suffix)
684 * \return a loaded component
686 //=============================================================================
687 Engines::EngineComponent_ptr
688 Engines_Container_i::create_component_instance(const char*genericRegisterName)
690 Engines::FieldsDict_var env = new Engines::FieldsDict;
692 Engines::EngineComponent_ptr compo =
693 create_component_instance_env(genericRegisterName, env, reason);
694 CORBA::string_free(reason);
698 //=============================================================================
699 //! Create a new component instance with environment variables specified
701 * CORBA method: Creates a new servant instance of a component.
702 * The servant registers itself to naming service and Registry.
703 * \param genericRegisterName Name of the component instance to register
704 * in Registry & Name Service (without _inst_n suffix)
705 * \param env dict of env variables
706 * \param reason explains error when create_component_instance_env fails
707 * \return a loaded component
709 //=============================================================================
710 Engines::EngineComponent_ptr
711 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
712 const Engines::FieldsDict& env,
713 CORBA::String_out reason)
716 if (_library_map.count(genericRegisterName) != 0)
718 // It's a Python component
719 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
720 reason=CORBA::string_dup(error.c_str());
724 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
725 if (_library_map.count(impl_name) != 0)
727 // It's a C++ component
728 void* handle = _library_map[impl_name];
729 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
730 reason=CORBA::string_dup(error.c_str());
734 impl_name = std::string(genericRegisterName) + ".exe";
735 if (_library_map.count(impl_name) != 0)
737 //It's an executable component
738 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
739 reason=CORBA::string_dup(error.c_str());
743 error="load_component_Library has probably not been called for component: ";
744 error += genericRegisterName;
746 reason=CORBA::string_dup(error.c_str());
747 return Engines::EngineComponent::_nil() ;
750 //=============================================================================
751 //! Create a new component instance (Executable implementation)
753 * \param CompName Name of the component instance
754 * \param env dict of env variables
755 * \param reason explains error when creation fails
756 * \return a loaded component
758 * This component is implemented in an executable with name genericRegisterName.exe
759 * It must register itself in Naming Service. The container waits some time (10 s max)
762 //=============================================================================
763 Engines::EngineComponent_ptr
764 Engines_Container_i::createExecutableInstance(std::string CompName,
765 const Engines::FieldsDict& env,
768 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
770 _numInstanceMutex.lock() ; // lock on the instance number
772 int numInstance = _numInstance ;
773 _numInstanceMutex.unlock() ;
776 sprintf( aNumI , "%d" , numInstance ) ;
777 std::string instanceName = CompName + "_inst_" + aNumI ;
778 std::string component_registerName = _containerName + "/" + instanceName;
780 //check if an entry exist in naming service
781 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
782 if ( !CORBA::is_nil(nsobj) )
784 // unregister the registered component
785 _NS->Destroy_Name(component_registerName.c_str());
786 //kill or shutdown it ???
789 // first arg container ior string
790 // second arg container name
791 // third arg instance name
793 Engines::Container_var pCont= _this();
794 CORBA::String_var sior = _orb->object_to_string(pCont);
798 command+=instanceName;
800 command+=instanceName;
805 command+= sior; // container ior string
807 command+=_containerName; //container name
809 command+=instanceName; //instance name
811 MESSAGE("SALOME_Container::create_component_instance command=" << command);
814 // use fork/execl instead of system to get finer control on env variables
817 if(pid == 0) // child
819 for (CORBA::ULong i=0; i < env.length(); i++)
821 if (env[i].value.type()->kind() == CORBA::tk_string)
824 env[i].value >>= value;
825 std::string s(env[i].key);
828 putenv(strdup(s.c_str()));
832 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
835 else if(pid < 0) // failed to fork
844 tpid = wait(&status);
845 } while (tpid != pid);
848 // launch component with a system call
849 int status=system(command.c_str());
854 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
856 return Engines::EngineComponent::_nil();
859 else if (WEXITSTATUS(status) == 217)
861 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
863 return Engines::EngineComponent::_nil();
869 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
871 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
873 std::istringstream ss(new_count_str);
874 if (!(ss >> new_count))
876 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
881 INFOS("[Container] waiting " << count << " second steps exe component ");
882 CORBA::Object_var obj = CORBA::Object::_nil() ;
883 while ( CORBA::is_nil(obj) && count )
891 MESSAGE( count << ". Waiting for component " << CompName);
892 obj = _NS->Resolve(component_registerName.c_str());
895 if(CORBA::is_nil(obj))
897 reason="SALOME_Container::create_component_instance failed";
899 return Engines::EngineComponent::_nil();
903 MESSAGE("SALOME_Container::create_component_instance successful");
904 iobject = Engines::EngineComponent::_narrow(obj);
905 _listInstances_map[instanceName] = iobject;
906 return iobject._retn();
912 //=============================================================================
913 //! Create a new component instance (Python implementation)
915 * \param CompName Name of the component instance
916 * \param reason explains error when creation fails
917 * \return a loaded component
919 //=============================================================================
920 Engines::EngineComponent_ptr
921 Engines_Container_i::createPythonInstance(std::string CompName,
924 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
926 _numInstanceMutex.lock() ; // lock on the instance number
928 int numInstance = _numInstance ;
929 _numInstanceMutex.unlock() ;
932 sprintf( aNumI , "%d" , numInstance ) ;
933 std::string instanceName = CompName + "_inst_" + aNumI ;
934 std::string component_registerName = _containerName + "/" + instanceName;
936 PyGILState_STATE gstate = PyGILState_Ensure();
937 PyObject *result = PyObject_CallMethod(_pyCont,
938 (char*)"create_component_instance",
941 instanceName.c_str());
944 PyArg_ParseTuple(result,"ss", &ior, &error);
945 std::string iors = ior;
948 PyGILState_Release(gstate);
952 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
953 iobject = Engines::EngineComponent::_narrow( obj ) ;
954 _listInstances_map[instanceName] = iobject;
956 return iobject._retn();
960 Engines_Container_i::create_python_service_instance(const char * CompName,
961 CORBA::String_out reason)
963 CORBA::Object_var object = CORBA::Object::_nil();
965 _numInstanceMutex.lock() ; // lock on the instance number
967 int numInstance = _numInstance ;
968 _numInstanceMutex.unlock() ;
971 sprintf( aNumI , "%d" , numInstance ) ;
972 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
973 std::string component_registerName = _containerName + "/" + instanceName;
975 PyGILState_STATE gstate = PyGILState_Ensure();
976 PyObject *result = PyObject_CallMethod(_pyCont,
977 (char*)"create_component_instance",
980 instanceName.c_str());
983 PyArg_ParseTuple(result,"ss", &ior, &error);
984 reason = CORBA::string_dup(error);
985 char * _ior = CORBA::string_dup(ior);
987 PyGILState_Release(gstate);
993 //=============================================================================
994 //! Create a new component instance (C++ implementation)
996 * C++ method: create a servant instance of a component.
997 * \param genericRegisterName Name of the component instance to register
998 * in Registry & Name Service,
999 * (without _inst_n suffix, like "COMPONENT")
1000 * \param handle loaded library handle
1001 * \param reason explains error when creation fails
1002 * \return a loaded component
1004 * example with names:
1005 * - aGenRegisterName = COMPONENT (= first argument)
1006 * - _containerName = /Containers/cli76ce/FactoryServer
1007 * - factoryName = COMPONENTEngine_factory
1008 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1009 * - instanceName = COMPONENT_inst_1
1010 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1012 //=============================================================================
1013 Engines::EngineComponent_ptr
1014 Engines_Container_i::createInstance(std::string genericRegisterName,
1016 std::string& reason)
1018 // --- find the factory
1020 std::string aGenRegisterName = genericRegisterName;
1021 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1022 SCRUTE(factory_name) ;
1024 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1025 PortableServer::POA_ptr,
1026 PortableServer::ObjectId *,
1031 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1033 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1036 if ( !Component_factory )
1038 MESSAGE( "Can't resolve symbol: " + factory_name );
1043 return Engines::EngineComponent::_nil() ;
1046 // --- create instance
1048 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1052 _numInstanceMutex.lock() ; // lock on the instance number
1054 int numInstance = _numInstance ;
1055 _numInstanceMutex.unlock() ;
1058 sprintf( aNumI , "%d" , numInstance ) ;
1059 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1060 std::string component_registerName =
1061 _containerName + "/" + instanceName;
1063 // --- Instantiate required CORBA object
1065 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1066 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1067 aGenRegisterName.c_str() ) ;
1070 reason="Can't get ObjectId from factory";
1072 return iobject._retn();
1075 // --- get reference from id
1077 CORBA::Object_var obj = _poa->id_to_reference(*id);
1078 iobject = Engines::EngineComponent::_narrow( obj ) ;
1080 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1081 _listInstances_map[instanceName] = iobject;
1082 _cntInstances_map[aGenRegisterName] += 1;
1083 _numInstanceMutex.unlock() ;
1084 SCRUTE(aGenRegisterName);
1085 SCRUTE(_cntInstances_map[aGenRegisterName]);
1087 // --- register the engine under the name
1088 // containerName(.dir)/instanceName(.object)
1090 _NS->Register( iobject , component_registerName.c_str() ) ;
1091 MESSAGE( component_registerName.c_str() << " bound" ) ;
1095 reason="Container_i::createInstance exception caught";
1098 return iobject._retn();
1101 //=============================================================================
1102 //! Find an existing (in the container) component instance
1104 * CORBA method: Finds a servant instance of a component
1105 * \param registeredName Name of the component in Registry or Name Service,
1106 * without instance suffix number
1107 * \return the first found instance
1109 //=============================================================================
1110 Engines::EngineComponent_ptr
1111 Engines_Container_i::find_component_instance( const char* registeredName)
1113 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1114 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1115 while (itm != _listInstances_map.end())
1117 std::string instance = (*itm).first;
1119 if (instance.find(registeredName) == 0)
1121 anEngine = (*itm).second;
1122 return anEngine._retn();
1126 return anEngine._retn();
1129 //=============================================================================
1130 //! Remove the component instance from container
1132 * CORBA method: Stops the component servant, and deletes all related objects
1133 * \param component_i Component to be removed
1135 //=============================================================================
1137 void Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1139 ASSERT(! CORBA::is_nil(component_i));
1140 std::string instanceName = component_i->instanceName() ;
1141 MESSAGE("unload component " << instanceName);
1142 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1143 _listInstances_map.erase(instanceName);
1144 _numInstanceMutex.unlock() ;
1145 component_i->destroy() ;
1146 _NS->Destroy_Name(instanceName.c_str());
1149 //=============================================================================
1150 //! Unload component libraries from the container
1152 * CORBA method: Discharges unused libraries from the container.
1154 //=============================================================================
1155 void Engines_Container_i::finalize_removal()
1157 MESSAGE("finalize unload : dlclose");
1158 _numInstanceMutex.lock(); // lock to be alone
1159 // (see decInstanceCnt, load_component_Library)
1160 std::map<std::string, void *>::iterator ith;
1161 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1163 void *handle = (*ith).second;
1164 std::string impl_name= (*ith).first;
1169 // dlclose(handle); // SALOME unstable after ...
1170 // _library_map.erase(impl_name);
1173 _toRemove_map.clear();
1174 _numInstanceMutex.unlock();
1177 //=============================================================================
1178 //! Decrement component instance reference count
1182 //=============================================================================
1183 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1185 if(_cntInstances_map.count(genericRegisterName)==0)
1187 std::string aGenRegisterName =genericRegisterName;
1188 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1189 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1190 _numInstanceMutex.lock(); // lock to be alone
1191 // (see finalize_removal, load_component_Library)
1192 _cntInstances_map[aGenRegisterName] -= 1;
1193 SCRUTE(_cntInstances_map[aGenRegisterName]);
1194 if (_cntInstances_map[aGenRegisterName] == 0)
1196 std::string impl_name =
1197 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1199 void* handle = _library_map[impl_name];
1201 _toRemove_map[impl_name] = handle;
1203 _numInstanceMutex.unlock();
1206 //=============================================================================
1207 //! Find or create a new component instance
1209 * CORBA method: find or create an instance of the component (servant),
1210 * load a new component class (dynamic library) if required,
1212 * ---- FOR COMPATIBILITY WITH 2.2 ----
1214 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1216 * The servant registers itself to naming service and Registry.
1217 * \param genericRegisterName Name of the component to register
1218 * in Registry & Name Service
1219 * \param componentName Name of the constructed library of the component
1220 * \return a loaded component
1222 //=============================================================================
1224 Engines::EngineComponent_ptr
1225 Engines_Container_i::load_impl( const char* genericRegisterName,
1226 const char* componentName )
1229 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1230 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1231 if (load_component_Library(genericRegisterName,reason))
1232 iobject = find_or_create_instance(genericRegisterName, impl_name);
1233 CORBA::string_free(reason);
1234 return iobject._retn();
1237 //=============================================================================
1238 //! Finds an already existing component instance or create a new instance
1240 * C++ method: Finds an already existing servant instance of a component, or
1241 * create an instance.
1242 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1243 * \param genericRegisterName Name of the component instance to register
1244 * in Registry & Name Service,
1245 * (without _inst_n suffix, like "COMPONENT")
1246 * \param componentLibraryName like "libCOMPONENTEngine.so"
1247 * \return a loaded component
1249 * example with names:
1250 * - aGenRegisterName = COMPONENT (= first argument)
1251 * - impl_name = libCOMPONENTEngine.so (= second argument)
1252 * - _containerName = /Containers/cli76ce/FactoryServer
1253 * - factoryName = COMPONENTEngine_factory
1254 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1255 * - instanceName = COMPONENT_inst_1
1256 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1258 //=============================================================================
1260 Engines::EngineComponent_ptr
1261 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1262 std::string componentLibraryName)
1264 std::string aGenRegisterName = genericRegisterName;
1265 std::string impl_name = componentLibraryName;
1266 if (_library_map.count(impl_name) == 0)
1268 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1269 return Engines::EngineComponent::_nil() ;
1273 // --- find a registered instance in naming service, or create
1275 void* handle = _library_map[impl_name];
1276 std::string component_registerBase =
1277 _containerName + "/" + aGenRegisterName;
1278 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1282 CORBA::Object_var obj =
1283 _NS->ResolveFirst( component_registerBase.c_str());
1284 if ( CORBA::is_nil( obj ) )
1286 iobject = createInstance(genericRegisterName,
1292 iobject = Engines::EngineComponent::_narrow( obj ) ;
1297 INFOS( "Container_i::load_impl caught" ) ;
1299 return iobject._retn();
1303 //=============================================================================
1304 //! Indicate if container is a python one
1306 * Retrieves only with container naming convention if it is a python container
1308 //=============================================================================
1309 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1312 int len=strlen(ContainerName);
1314 if(strcmp(ContainerName+len-2,"Py")==0)
1319 //=============================================================================
1320 //! Kill the container
1322 * CORBA method: Kill the container process with exit(0).
1323 * To remove : never returns !
1325 //=============================================================================
1326 bool Engines_Container_i::Kill_impl()
1328 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1329 << _containerName.c_str() << " machineName "
1330 << Kernel_Utils::GetHostname().c_str());
1331 INFOS("===============================================================");
1332 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1333 INFOS("===============================================================");
1339 //=============================================================================
1343 //=============================================================================
1344 void ActSigIntHandler()
1347 struct sigaction SigIntAct ;
1348 SigIntAct.sa_sigaction = &SigIntHandler ;
1349 sigemptyset(&SigIntAct.sa_mask);
1350 SigIntAct.sa_flags = SA_SIGINFO ;
1353 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1354 // (SIGINT | SIGUSR1) :
1355 // it must be only one signal ===> one call for SIGINT
1356 // and an other one for SIGUSR1
1359 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1361 perror("SALOME_Container main ") ;
1364 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1366 perror("SALOME_Container main ") ;
1369 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1371 perror("SALOME_Container main ") ;
1375 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1376 // use of streams (and so on) should never be used because :
1377 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1378 // A stream operation may be interrupted by a signal and if the Handler use stream we
1379 // may have a "Dead-Lock" ===HangUp
1380 //==INFOS is commented
1381 // INFOS(pthread_self() << "SigIntHandler activated") ;
1384 signal( SIGINT, SigIntHandler );
1385 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1386 // signal( SIGUSR1, SigIntHandler );
1392 void CallCancelThread() ;
1395 void SigIntHandler(int what ,
1396 siginfo_t * siginfo ,
1399 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1400 // use of streams (and so on) should never be used because :
1401 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1402 // A stream operation may be interrupted by a signal and if the Handler use stream we
1403 // may have a "Dead-Lock" ===HangUp
1404 //==MESSAGE is commented
1405 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1406 // << " si_signo " << siginfo->si_signo << std::endl
1407 // << " si_code " << siginfo->si_code << std::endl
1408 // << " si_pid " << siginfo->si_pid) ;
1413 // MESSAGE("SigIntHandler END sleeping.") ;
1418 ActSigIntHandler() ;
1419 if ( siginfo->si_signo == SIGUSR1 )
1423 else if ( siginfo->si_signo == SIGUSR2 )
1425 CallCancelThread() ;
1430 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1437 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1443 void SigIntHandler( int what )
1446 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1448 MESSAGE( "SigIntHandler what " << what << std::endl );
1453 MESSAGE("SigIntHandler END sleeping.") ;
1458 ActSigIntHandler() ;
1459 if ( what == SIGUSR1 )
1466 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1473 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1480 //=============================================================================
1481 //! Get or create a file reference object associated to a local file (to transfer it)
1483 * CORBA method: get or create a fileRef object associated to a local file
1484 * (a file on the computer on which runs the container server), which stores
1485 * a list of (machine, localFileName) corresponding to copies already done.
1487 * \param origFileName absolute path for a local file to copy on other
1489 * \return a fileRef object associated to the file.
1491 //=============================================================================
1492 Engines::fileRef_ptr
1493 Engines_Container_i::createFileRef(const char* origFileName)
1495 std::string origName(origFileName);
1496 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1498 if (origName[0] != '/')
1500 INFOS("path of file to copy must be an absolute path beginning with '/'");
1501 return Engines::fileRef::_nil();
1504 if (CORBA::is_nil(_fileRef_map[origName]))
1506 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1507 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1508 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1509 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1510 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1511 _fileRef_map[origName] = theFileRef;
1512 _numInstanceMutex.unlock() ;
1515 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1516 ASSERT(! CORBA::is_nil(theFileRef));
1517 return theFileRef._retn();
1520 //=============================================================================
1521 //! Get a fileTransfer reference
1524 * \return a reference to the fileTransfer object
1526 //=============================================================================
1527 Engines::fileTransfer_ptr
1528 Engines_Container_i::getFileTransfer()
1530 Engines::fileTransfer_var aFileTransfer
1531 = Engines::fileTransfer::_duplicate(_fileTransfer);
1532 return aFileTransfer._retn();
1535 //=============================================================================
1536 //! Create a Salome file
1537 //=============================================================================
1538 Engines::Salome_file_ptr
1539 Engines_Container_i::createSalome_file(const char* origFileName)
1541 std::string origName(origFileName);
1542 if (CORBA::is_nil(_Salome_file_map[origName]))
1544 Salome_file_i* aSalome_file = new Salome_file_i();
1545 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1548 aSalome_file->setLocalFile(origFileName);
1549 aSalome_file->recvFiles();
1551 catch (const SALOME::SALOME_Exception& e)
1553 return Engines::Salome_file::_nil();
1556 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1557 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1558 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1559 _Salome_file_map[origName] = theSalome_file;
1560 _numInstanceMutex.unlock() ;
1563 Engines::Salome_file_ptr theSalome_file =
1564 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1565 ASSERT(!CORBA::is_nil(theSalome_file));
1566 return theSalome_file;
1569 //=============================================================================
1570 /*! \brief copy a file from a remote host (container) to the local host
1571 * \param container the remote container
1572 * \param remoteFile the file to copy locally from the remote host into localFile
1573 * \param localFile the local file
1575 //=============================================================================
1576 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1578 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1581 if ((fp = fopen(localFile,"wb")) == NULL)
1583 INFOS("file " << localFile << " cannot be open for writing");
1587 CORBA::Long fileId = fileTransfer->open(remoteFile);
1590 Engines::fileBlock* aBlock;
1597 aBlock = fileTransfer->getBlock(fileId);
1598 toFollow = aBlock->length();
1600 CORBA::Octet *buf = aBlock->get_buffer();
1601 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1605 MESSAGE("end of transfer");
1606 fileTransfer->close(fileId);
1610 INFOS("open reference file for copy impossible");
1614 //=============================================================================
1615 /*! \brief create a PyNode object to execute remote python code
1616 * \param nodeName the name of the node
1617 * \param code the python code to load
1618 * \return the PyNode
1620 //=============================================================================
1621 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1623 Engines::PyNode_var node= Engines::PyNode::_nil();
1625 PyGILState_STATE gstate = PyGILState_Ensure();
1626 PyObject *res = PyObject_CallMethod(_pyCont,
1627 (char*)"create_pynode",
1635 PyGILState_Release(gstate);
1636 SALOME::ExceptionStruct es;
1637 es.type = SALOME::INTERNAL_ERROR;
1638 es.text = "can not create a python node";
1639 throw SALOME::SALOME_Exception(es);
1641 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1642 PyObject* result=PyTuple_GetItem(res,1);
1643 std::string astr=PyUnicode_AsUTF8(result);
1645 PyGILState_Release(gstate);
1648 Utils_Locker lck(&_mutexForDftPy);
1649 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1650 node=Engines::PyNode::_narrow(obj);
1651 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1652 if(it==_dftPyNode.end())
1654 _dftPyNode[nodeName]=node;
1658 Engines::PyNode_var oldNode((*it).second);
1659 if(!CORBA::is_nil(oldNode))
1660 oldNode->UnRegister();
1663 if(!CORBA::is_nil(node))
1665 return node._retn();
1669 SALOME::ExceptionStruct es;
1670 es.type = SALOME::INTERNAL_ERROR;
1671 es.text = astr.c_str();
1672 throw SALOME::SALOME_Exception(es);
1676 //=============================================================================
1677 /*! \brief Retrieves the last created PyNode instance with createPyNode.
1680 //=============================================================================
1681 Engines::PyNode_ptr Engines_Container_i::getDefaultPyNode(const char *nodeName)
1683 Utils_Locker lck(&_mutexForDftPy);
1684 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1685 if(it==_dftPyNode.end())
1686 return Engines::PyNode::_nil();
1689 Engines::PyNode_var tmpVar((*it).second);
1690 if(!CORBA::is_nil(tmpVar))
1691 return Engines::PyNode::_duplicate(tmpVar);
1693 return Engines::PyNode::_nil();
1697 //=============================================================================
1698 /*! \brief create a PyScriptNode object to execute remote python code
1699 * \param nodeName the name of the node
1700 * \param code the python code to load
1701 * \return the PyScriptNode
1703 //=============================================================================
1704 Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1706 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1708 PyGILState_STATE gstate = PyGILState_Ensure();
1709 PyObject *res = PyObject_CallMethod(_pyCont,
1710 (char*)"create_pyscriptnode",
1718 PyGILState_Release(gstate);
1719 SALOME::ExceptionStruct es;
1720 es.type = SALOME::INTERNAL_ERROR;
1721 es.text = "can not create a python node";
1722 throw SALOME::SALOME_Exception(es);
1724 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1725 PyObject* result=PyTuple_GetItem(res,1);
1726 std::string astr=PyUnicode_AsUTF8(result);
1728 PyGILState_Release(gstate);
1732 Utils_Locker lck(&_mutexForDftPy);
1733 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1734 node=Engines::PyScriptNode::_narrow(obj);
1735 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
1736 if(it==_dftPyScriptNode.end())
1738 _dftPyScriptNode[nodeName]=node;
1742 Engines::PyScriptNode_var oldNode((*it).second);
1743 if(!CORBA::is_nil(oldNode))
1744 oldNode->UnRegister();
1747 if(!CORBA::is_nil(node))
1749 return node._retn();
1753 SALOME::ExceptionStruct es;
1754 es.type = SALOME::INTERNAL_ERROR;
1755 es.text = astr.c_str();
1756 throw SALOME::SALOME_Exception(es);
1760 //=============================================================================
1761 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
1764 //=============================================================================
1765 Engines::PyScriptNode_ptr Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
1767 Utils_Locker lck(&_mutexForDftPy);
1768 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
1769 if(it==_dftPyScriptNode.end())
1770 return Engines::PyScriptNode::_nil();
1773 Engines::PyScriptNode_var tmpVar((*it).second);
1774 if(!CORBA::is_nil(tmpVar))
1775 return Engines::PyScriptNode::_duplicate(tmpVar);
1777 return Engines::PyScriptNode::_nil();
1781 //=============================================================================
1782 /* int checkifexecutable(const char *filename)
1784 * Return non-zero if the name is an executable file, and
1785 * zero if it is not executable, or if it does not exist.
1787 //=============================================================================
1788 int checkifexecutable(const std::string& filename)
1791 struct stat statinfo;
1793 result = stat(filename.c_str(), &statinfo);
1794 if (result < 0) return 0;
1795 if (!S_ISREG(statinfo.st_mode)) return 0;
1800 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1801 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1802 return statinfo.st_mode & S_IXOTH;
1807 //=============================================================================
1808 /*! \brief Find a file by searching in a path
1809 * \param filename file name to search
1810 * \param path path to search in
1811 * \param pth the complete file path if found
1812 * \return 1 if found 0 if not
1814 //=============================================================================
1815 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1817 if ( path.size() == 0 ) return 0;
1819 std::string::size_type offset = 0;
1820 std::string::size_type pos = 0;
1822 struct stat statinfo;
1826 pos = path.find( SEP, offset );
1827 pth = path.substr( offset, pos - offset );
1828 if ( pth.size() > 0 )
1830 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1832 int result=stat(pth.c_str(), &statinfo);
1833 if(result == 0) found=1;
1835 if (pos == std::string::npos) break;
1841 void Engines_Container_i::registerTemporaryFile( const std::string& fileName )
1843 _tmp_files.remove( fileName );
1844 _tmp_files.push_back( fileName );
1847 void Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
1849 _tmp_files.remove( fileName );
1852 void Engines_Container_i::clearTemporaryFiles()
1854 std::list<std::string>::const_iterator it;
1855 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
1857 std::string command = "del /F /P";
1859 std::string command = "rm -rf ";
1862 system( command.c_str() );
1868 std::string Engines_Container_i::AnotherMethodeToReplace_PyString_AsString(PyObject * result)
1870 std::string my_result = "";
1871 if (PyUnicode_Check(result)) {
1872 // Convert string to bytes.
1873 // strdup() bytes into my_result.
1874 PyObject * temp_bytes = PyUnicode_AsEncodedString(result, "ASCII", "strict"); // Owned reference
1875 if (temp_bytes != NULL) {
1876 my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
1877 my_result = strdup(my_result);
1878 Py_DECREF(temp_bytes);
1880 // TODO PY3: Handle encoding error.
1881 Py_DECREF(temp_bytes);
1884 } else if (PyBytes_Check(result)) {
1885 // strdup() bytes into my_result.
1886 my_result = PyBytes_AS_STRING(result); // Borrowed pointer
1887 my_result = strdup(my_result);
1889 // Convert into your favorite string representation.
1890 // Convert string to bytes if it is not already.
1891 // strdup() bytes into my_result.
1892 // TODO PY3: Check if only bytes is ok.
1893 PyObject * temp_bytes = PyObject_Bytes(result); // Owned reference
1894 if (temp_bytes != NULL) {
1895 my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
1896 my_result = strdup(my_result);
1897 Py_DECREF(temp_bytes);
1899 // TODO PY3: Handle error.
1900 Py_DECREF(temp_bytes);