1 // Copyright (C) 2007-2019 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";
558 std::wstring libToLoad = Kernel_Utils::utf8_decode_s( impl_name );
560 std::string libToLoad = impl_name;
562 handle = LoadLibrary(libToLoad.c_str() );
565 reason="ImplementationNotFound";
571 _numInstanceMutex.lock();
572 _library_map[impl_name] = handle;
573 _numInstanceMutex.unlock();
581 //=============================================================================
582 //! try to load a Python component implementation
585 * \param componentName name of the component
586 * \param reason explains error when load fails
587 * \return true if loading is successful or already done, false otherwise
589 //=============================================================================
591 Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
593 std::string aCompName(componentName);
595 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
596 if (_library_map.count(aCompName) != 0)
598 _numInstanceMutex.unlock() ;
600 return true; // Python Component, already imported
602 _numInstanceMutex.unlock() ;
604 PyGILState_STATE gstate = PyGILState_Ensure();
605 PyObject *result = PyObject_CallMethod(_pyCont,
606 (char*)"import_component",
607 (char*)"s",componentName);
609 reason=PyUnicode_AsUTF8(result);
612 PyGILState_Release(gstate);
616 //Python component has been loaded (import componentName)
617 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
618 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
619 _numInstanceMutex.unlock() ;
620 MESSAGE("import Python: "<< aCompName <<" OK");
623 else if(reason=="ImplementationNotFound")
625 //Python implementation has not been found. Continue with other implementation
626 reason="ImplementationNotFound";
630 //Python implementation has been found but loading has failed
631 std::cerr << reason << std::endl;
636 //=============================================================================
637 //! try to load a Executable component implementation
640 * \param componentName name of the component
641 * \param reason explains error when load fails
642 * \return true if loading is successful or already done, false otherwise
644 //=============================================================================
646 Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
648 std::string aCompName(componentName);
649 std::string executable=aCompName+".exe";
654 char* p=getenv("PATH");
657 if (findpathof(path, pth, executable))
659 if(checkifexecutable(pth))
661 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
662 _library_map[executable] = (void *)1; // any non O value OK
663 _numInstanceMutex.unlock() ;
664 MESSAGE("import executable: "<< pth <<" OK");
670 reason+=": implementation found ";
672 reason+=" but it is not executable";
673 std::cerr << reason << std::endl;
677 reason="ImplementationNotFound";
682 //=============================================================================
683 //! Create a new component instance
685 * CORBA method: Creates a new servant instance of a component.
686 * The servant registers itself to naming service and Registry.
687 * \param genericRegisterName Name of the component instance to register
688 * in Registry & Name Service (without _inst_n suffix)
689 * \return a loaded component
691 //=============================================================================
692 Engines::EngineComponent_ptr
693 Engines_Container_i::create_component_instance(const char*genericRegisterName)
695 Engines::FieldsDict_var env = new Engines::FieldsDict;
697 Engines::EngineComponent_ptr compo =
698 create_component_instance_env(genericRegisterName, env, reason);
699 CORBA::string_free(reason);
703 //=============================================================================
704 //! Create a new component instance with environment variables specified
706 * CORBA method: Creates a new servant instance of a component.
707 * The servant registers itself to naming service and Registry.
708 * \param genericRegisterName Name of the component instance to register
709 * in Registry & Name Service (without _inst_n suffix)
710 * \param env dict of env variables
711 * \param reason explains error when create_component_instance_env fails
712 * \return a loaded component
714 //=============================================================================
715 Engines::EngineComponent_ptr
716 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
717 const Engines::FieldsDict& env,
718 CORBA::String_out reason)
721 if (_library_map.count(genericRegisterName) != 0)
723 // It's a Python component
724 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, error);
725 reason=CORBA::string_dup(error.c_str());
729 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
730 if (_library_map.count(impl_name) != 0)
732 // It's a C++ component
733 void* handle = _library_map[impl_name];
734 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, error);
735 reason=CORBA::string_dup(error.c_str());
739 impl_name = std::string(genericRegisterName) + ".exe";
740 if (_library_map.count(impl_name) != 0)
742 //It's an executable component
743 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, env, error);
744 reason=CORBA::string_dup(error.c_str());
748 error="load_component_Library has probably not been called for component: ";
749 error += genericRegisterName;
751 reason=CORBA::string_dup(error.c_str());
752 return Engines::EngineComponent::_nil() ;
755 //=============================================================================
756 //! Create a new component instance (Executable implementation)
758 * \param CompName Name of the component instance
759 * \param env dict of env variables
760 * \param reason explains error when creation fails
761 * \return a loaded component
763 * This component is implemented in an executable with name genericRegisterName.exe
764 * It must register itself in Naming Service. The container waits some time (10 s max)
767 //=============================================================================
768 Engines::EngineComponent_ptr
769 Engines_Container_i::createExecutableInstance(std::string CompName,
770 const Engines::FieldsDict& env,
773 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
775 _numInstanceMutex.lock() ; // lock on the instance number
777 int numInstance = _numInstance ;
778 _numInstanceMutex.unlock() ;
781 sprintf( aNumI , "%d" , numInstance ) ;
782 std::string instanceName = CompName + "_inst_" + aNumI ;
783 std::string component_registerName = _containerName + "/" + instanceName;
785 //check if an entry exist in naming service
786 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
787 if ( !CORBA::is_nil(nsobj) )
789 // unregister the registered component
790 _NS->Destroy_Name(component_registerName.c_str());
791 //kill or shutdown it ???
794 // first arg container ior string
795 // second arg container name
796 // third arg instance name
798 Engines::Container_var pCont= _this();
799 CORBA::String_var sior = _orb->object_to_string(pCont);
803 command+=instanceName;
805 command+=instanceName;
810 command+= sior; // container ior string
812 command+=_containerName; //container name
814 command+=instanceName; //instance name
816 MESSAGE("SALOME_Container::create_component_instance command=" << command);
819 // use fork/execl instead of system to get finer control on env variables
822 if(pid == 0) // child
824 for (CORBA::ULong i=0; i < env.length(); i++)
826 if (env[i].value.type()->kind() == CORBA::tk_string)
829 env[i].value >>= value;
830 std::string s(env[i].key);
833 putenv(strdup(s.c_str()));
837 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
840 else if(pid < 0) // failed to fork
849 tpid = wait(&status);
850 } while (tpid != pid);
853 // launch component with a system call
854 int status=system(command.c_str());
859 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
861 return Engines::EngineComponent::_nil();
864 else if (WEXITSTATUS(status) == 217)
866 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
868 return Engines::EngineComponent::_nil();
874 if (getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT") != 0)
876 std::string new_count_str = getenv("TIMEOUT_TO_WAIT_EXE_COMPONENT");
878 std::istringstream ss(new_count_str);
879 if (!(ss >> new_count))
881 INFOS("[Container] TIMEOUT_TO_WAIT_EXE_COMPONENT should be an int");
886 INFOS("[Container] waiting " << count << " second steps exe component ");
887 CORBA::Object_var obj = CORBA::Object::_nil() ;
888 while ( CORBA::is_nil(obj) && count )
896 MESSAGE( count << ". Waiting for component " << CompName);
897 obj = _NS->Resolve(component_registerName.c_str());
900 if(CORBA::is_nil(obj))
902 reason="SALOME_Container::create_component_instance failed";
904 return Engines::EngineComponent::_nil();
908 MESSAGE("SALOME_Container::create_component_instance successful");
909 iobject = Engines::EngineComponent::_narrow(obj);
910 _listInstances_map[instanceName] = iobject;
911 return iobject._retn();
917 //=============================================================================
918 //! Create a new component instance (Python implementation)
920 * \param CompName Name of the component instance
921 * \param reason explains error when creation fails
922 * \return a loaded component
924 //=============================================================================
925 Engines::EngineComponent_ptr
926 Engines_Container_i::createPythonInstance(std::string CompName,
929 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
931 _numInstanceMutex.lock() ; // lock on the instance number
933 int numInstance = _numInstance ;
934 _numInstanceMutex.unlock() ;
937 sprintf( aNumI , "%d" , numInstance ) ;
938 std::string instanceName = CompName + "_inst_" + aNumI ;
939 std::string component_registerName = _containerName + "/" + instanceName;
941 PyGILState_STATE gstate = PyGILState_Ensure();
942 PyObject *result = PyObject_CallMethod(_pyCont,
943 (char*)"create_component_instance",
946 instanceName.c_str());
949 PyArg_ParseTuple(result,"ss", &ior, &error);
950 std::string iors = ior;
953 PyGILState_Release(gstate);
957 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
958 iobject = Engines::EngineComponent::_narrow( obj ) ;
959 _listInstances_map[instanceName] = iobject;
961 return iobject._retn();
965 Engines_Container_i::create_python_service_instance(const char * CompName,
966 CORBA::String_out reason)
968 CORBA::Object_var object = CORBA::Object::_nil();
970 _numInstanceMutex.lock() ; // lock on the instance number
972 int numInstance = _numInstance ;
973 _numInstanceMutex.unlock() ;
976 sprintf( aNumI , "%d" , numInstance ) ;
977 std::string instanceName = std::string(CompName) + "_inst_" + aNumI ;
978 std::string component_registerName = _containerName + "/" + instanceName;
980 PyGILState_STATE gstate = PyGILState_Ensure();
981 PyObject *result = PyObject_CallMethod(_pyCont,
982 (char*)"create_component_instance",
985 instanceName.c_str());
988 PyArg_ParseTuple(result,"ss", &ior, &error);
989 reason = CORBA::string_dup(error);
990 char * _ior = CORBA::string_dup(ior);
992 PyGILState_Release(gstate);
998 //=============================================================================
999 //! Create a new component instance (C++ implementation)
1001 * C++ method: create a servant instance of a component.
1002 * \param genericRegisterName Name of the component instance to register
1003 * in Registry & Name Service,
1004 * (without _inst_n suffix, like "COMPONENT")
1005 * \param handle loaded library handle
1006 * \param reason explains error when creation fails
1007 * \return a loaded component
1009 * example with names:
1010 * - aGenRegisterName = COMPONENT (= first argument)
1011 * - _containerName = /Containers/cli76ce/FactoryServer
1012 * - factoryName = COMPONENTEngine_factory
1013 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1014 * - instanceName = COMPONENT_inst_1
1015 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1017 //=============================================================================
1018 Engines::EngineComponent_ptr
1019 Engines_Container_i::createInstance(std::string genericRegisterName,
1021 std::string& reason)
1023 // --- find the factory
1025 std::string aGenRegisterName = genericRegisterName;
1026 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
1027 SCRUTE(factory_name) ;
1029 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
1030 PortableServer::POA_ptr,
1031 PortableServer::ObjectId *,
1036 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1038 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1041 if ( !Component_factory )
1043 MESSAGE( "Can't resolve symbol: " + factory_name );
1048 return Engines::EngineComponent::_nil() ;
1051 // --- create instance
1053 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1057 _numInstanceMutex.lock() ; // lock on the instance number
1059 int numInstance = _numInstance ;
1060 _numInstanceMutex.unlock() ;
1063 sprintf( aNumI , "%d" , numInstance ) ;
1064 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1065 std::string component_registerName =
1066 _containerName + "/" + instanceName;
1068 // --- Instantiate required CORBA object
1070 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1071 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1072 aGenRegisterName.c_str() ) ;
1075 reason="Can't get ObjectId from factory";
1077 return iobject._retn();
1080 // --- get reference from id
1082 CORBA::Object_var obj = _poa->id_to_reference(*id);
1083 iobject = Engines::EngineComponent::_narrow( obj ) ;
1085 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1086 _listInstances_map[instanceName] = iobject;
1087 _cntInstances_map[aGenRegisterName] += 1;
1088 _numInstanceMutex.unlock() ;
1089 SCRUTE(aGenRegisterName);
1090 SCRUTE(_cntInstances_map[aGenRegisterName]);
1092 // --- register the engine under the name
1093 // containerName(.dir)/instanceName(.object)
1095 _NS->Register( iobject , component_registerName.c_str() ) ;
1096 MESSAGE( component_registerName.c_str() << " bound" ) ;
1100 reason="Container_i::createInstance exception caught";
1103 return iobject._retn();
1106 //=============================================================================
1107 //! Find an existing (in the container) component instance
1109 * CORBA method: Finds a servant instance of a component
1110 * \param registeredName Name of the component in Registry or Name Service,
1111 * without instance suffix number
1112 * \return the first found instance
1114 //=============================================================================
1115 Engines::EngineComponent_ptr
1116 Engines_Container_i::find_component_instance( const char* registeredName)
1118 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1119 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1120 while (itm != _listInstances_map.end())
1122 std::string instance = (*itm).first;
1124 if (instance.find(registeredName) == 0)
1126 anEngine = (*itm).second;
1127 return anEngine._retn();
1131 return anEngine._retn();
1134 //=============================================================================
1135 //! Remove the component instance from container
1137 * CORBA method: Stops the component servant, and deletes all related objects
1138 * \param component_i Component to be removed
1140 //=============================================================================
1142 void Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1144 ASSERT(! CORBA::is_nil(component_i));
1145 std::string instanceName = component_i->instanceName() ;
1146 MESSAGE("unload component " << instanceName);
1147 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1148 _listInstances_map.erase(instanceName);
1149 _numInstanceMutex.unlock() ;
1150 component_i->destroy() ;
1151 _NS->Destroy_Name(instanceName.c_str());
1154 //=============================================================================
1155 //! Unload component libraries from the container
1157 * CORBA method: Discharges unused libraries from the container.
1159 //=============================================================================
1160 void Engines_Container_i::finalize_removal()
1162 MESSAGE("finalize unload : dlclose");
1163 _numInstanceMutex.lock(); // lock to be alone
1164 // (see decInstanceCnt, load_component_Library)
1165 std::map<std::string, void *>::iterator ith;
1166 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1168 void *handle = (*ith).second;
1169 std::string impl_name= (*ith).first;
1174 // dlclose(handle); // SALOME unstable after ...
1175 // _library_map.erase(impl_name);
1178 _toRemove_map.clear();
1179 _numInstanceMutex.unlock();
1182 //=============================================================================
1183 //! Decrement component instance reference count
1187 //=============================================================================
1188 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1190 if(_cntInstances_map.count(genericRegisterName)==0)
1192 std::string aGenRegisterName =genericRegisterName;
1193 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1194 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1195 _numInstanceMutex.lock(); // lock to be alone
1196 // (see finalize_removal, load_component_Library)
1197 _cntInstances_map[aGenRegisterName] -= 1;
1198 SCRUTE(_cntInstances_map[aGenRegisterName]);
1199 if (_cntInstances_map[aGenRegisterName] == 0)
1201 std::string impl_name =
1202 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1204 void* handle = _library_map[impl_name];
1206 _toRemove_map[impl_name] = handle;
1208 _numInstanceMutex.unlock();
1211 //=============================================================================
1212 //! Find or create a new component instance
1214 * CORBA method: find or create an instance of the component (servant),
1215 * load a new component class (dynamic library) if required,
1217 * ---- FOR COMPATIBILITY WITH 2.2 ----
1219 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1221 * The servant registers itself to naming service and Registry.
1222 * \param genericRegisterName Name of the component to register
1223 * in Registry & Name Service
1224 * \param componentName Name of the constructed library of the component
1225 * \return a loaded component
1227 //=============================================================================
1229 Engines::EngineComponent_ptr
1230 Engines_Container_i::load_impl( const char* genericRegisterName,
1231 const char* componentName )
1234 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1235 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1236 if (load_component_Library(genericRegisterName,reason))
1237 iobject = find_or_create_instance(genericRegisterName, impl_name);
1238 CORBA::string_free(reason);
1239 return iobject._retn();
1242 //=============================================================================
1243 //! Finds an already existing component instance or create a new instance
1245 * C++ method: Finds an already existing servant instance of a component, or
1246 * create an instance.
1247 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1248 * \param genericRegisterName Name of the component instance to register
1249 * in Registry & Name Service,
1250 * (without _inst_n suffix, like "COMPONENT")
1251 * \param componentLibraryName like "libCOMPONENTEngine.so"
1252 * \return a loaded component
1254 * example with names:
1255 * - aGenRegisterName = COMPONENT (= first argument)
1256 * - impl_name = libCOMPONENTEngine.so (= second argument)
1257 * - _containerName = /Containers/cli76ce/FactoryServer
1258 * - factoryName = COMPONENTEngine_factory
1259 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1260 * - instanceName = COMPONENT_inst_1
1261 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1263 //=============================================================================
1265 Engines::EngineComponent_ptr
1266 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1267 std::string componentLibraryName)
1269 std::string aGenRegisterName = genericRegisterName;
1270 std::string impl_name = componentLibraryName;
1271 if (_library_map.count(impl_name) == 0)
1273 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1274 return Engines::EngineComponent::_nil() ;
1278 // --- find a registered instance in naming service, or create
1280 void* handle = _library_map[impl_name];
1281 std::string component_registerBase =
1282 _containerName + "/" + aGenRegisterName;
1283 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1287 CORBA::Object_var obj =
1288 _NS->ResolveFirst( component_registerBase.c_str());
1289 if ( CORBA::is_nil( obj ) )
1291 iobject = createInstance(genericRegisterName,
1297 iobject = Engines::EngineComponent::_narrow( obj ) ;
1302 INFOS( "Container_i::load_impl caught" ) ;
1304 return iobject._retn();
1308 //=============================================================================
1309 //! Indicate if container is a python one
1311 * Retrieves only with container naming convention if it is a python container
1313 //=============================================================================
1314 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1317 int len=strlen(ContainerName);
1319 if(strcmp(ContainerName+len-2,"Py")==0)
1324 //=============================================================================
1325 //! Kill the container
1327 * CORBA method: Kill the container process with exit(0).
1328 * To remove : never returns !
1330 //=============================================================================
1331 bool Engines_Container_i::Kill_impl()
1333 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1334 << _containerName.c_str() << " machineName "
1335 << Kernel_Utils::GetHostname().c_str());
1336 INFOS("===============================================================");
1337 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1338 INFOS("===============================================================");
1344 //=============================================================================
1348 //=============================================================================
1349 void ActSigIntHandler()
1352 struct sigaction SigIntAct ;
1353 SigIntAct.sa_sigaction = &SigIntHandler ;
1354 sigemptyset(&SigIntAct.sa_mask);
1355 SigIntAct.sa_flags = SA_SIGINFO ;
1358 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1359 // (SIGINT | SIGUSR1) :
1360 // it must be only one signal ===> one call for SIGINT
1361 // and an other one for SIGUSR1
1364 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1366 perror("SALOME_Container main ") ;
1369 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1371 perror("SALOME_Container main ") ;
1374 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1376 perror("SALOME_Container main ") ;
1380 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1381 // use of streams (and so on) should never be used because :
1382 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1383 // A stream operation may be interrupted by a signal and if the Handler use stream we
1384 // may have a "Dead-Lock" ===HangUp
1385 //==INFOS is commented
1386 // INFOS(pthread_self() << "SigIntHandler activated") ;
1389 signal( SIGINT, SigIntHandler );
1390 // legacy code required to supervisor. Commented in order to avoid problems on Windows
1391 // signal( SIGUSR1, SigIntHandler );
1397 void CallCancelThread() ;
1400 void SigIntHandler(int what ,
1401 siginfo_t * siginfo ,
1404 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1405 // use of streams (and so on) should never be used because :
1406 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1407 // A stream operation may be interrupted by a signal and if the Handler use stream we
1408 // may have a "Dead-Lock" ===HangUp
1409 //==MESSAGE is commented
1410 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1411 // << " si_signo " << siginfo->si_signo << std::endl
1412 // << " si_code " << siginfo->si_code << std::endl
1413 // << " si_pid " << siginfo->si_pid) ;
1418 // MESSAGE("SigIntHandler END sleeping.") ;
1423 ActSigIntHandler() ;
1424 if ( siginfo->si_signo == SIGUSR1 )
1428 else if ( siginfo->si_signo == SIGUSR2 )
1430 CallCancelThread() ;
1435 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1442 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1448 void SigIntHandler( int what )
1451 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1453 MESSAGE( "SigIntHandler what " << what << std::endl );
1458 MESSAGE("SigIntHandler END sleeping.") ;
1463 ActSigIntHandler() ;
1464 if ( what == SIGUSR1 )
1471 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1478 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1485 //=============================================================================
1486 //! Get or create a file reference object associated to a local file (to transfer it)
1488 * CORBA method: get or create a fileRef object associated to a local file
1489 * (a file on the computer on which runs the container server), which stores
1490 * a list of (machine, localFileName) corresponding to copies already done.
1492 * \param origFileName absolute path for a local file to copy on other
1494 * \return a fileRef object associated to the file.
1496 //=============================================================================
1497 Engines::fileRef_ptr
1498 Engines_Container_i::createFileRef(const char* origFileName)
1500 std::string origName(origFileName);
1501 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1503 if (origName[0] != '/')
1505 INFOS("path of file to copy must be an absolute path beginning with '/'");
1506 return Engines::fileRef::_nil();
1509 if (CORBA::is_nil(_fileRef_map[origName]))
1511 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1512 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1513 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1514 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1515 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1516 _fileRef_map[origName] = theFileRef;
1517 _numInstanceMutex.unlock() ;
1520 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1521 ASSERT(! CORBA::is_nil(theFileRef));
1522 return theFileRef._retn();
1525 //=============================================================================
1526 //! Get a fileTransfer reference
1529 * \return a reference to the fileTransfer object
1531 //=============================================================================
1532 Engines::fileTransfer_ptr
1533 Engines_Container_i::getFileTransfer()
1535 Engines::fileTransfer_var aFileTransfer
1536 = Engines::fileTransfer::_duplicate(_fileTransfer);
1537 return aFileTransfer._retn();
1540 //=============================================================================
1541 //! Create a Salome file
1542 //=============================================================================
1543 Engines::Salome_file_ptr
1544 Engines_Container_i::createSalome_file(const char* origFileName)
1546 std::string origName(origFileName);
1547 if (CORBA::is_nil(_Salome_file_map[origName]))
1549 Salome_file_i* aSalome_file = new Salome_file_i();
1550 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1553 aSalome_file->setLocalFile(origFileName);
1554 aSalome_file->recvFiles();
1556 catch (const SALOME::SALOME_Exception& e)
1558 return Engines::Salome_file::_nil();
1561 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1562 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1563 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1564 _Salome_file_map[origName] = theSalome_file;
1565 _numInstanceMutex.unlock() ;
1568 Engines::Salome_file_ptr theSalome_file =
1569 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1570 ASSERT(!CORBA::is_nil(theSalome_file));
1571 return theSalome_file;
1574 //=============================================================================
1575 /*! \brief copy a file from a remote host (container) to the local host
1576 * \param container the remote container
1577 * \param remoteFile the file to copy locally from the remote host into localFile
1578 * \param localFile the local file
1580 //=============================================================================
1581 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1583 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1586 if ((fp = fopen(localFile,"wb")) == NULL)
1588 INFOS("file " << localFile << " cannot be open for writing");
1592 CORBA::Long fileId = fileTransfer->open(remoteFile);
1595 Engines::fileBlock* aBlock;
1602 aBlock = fileTransfer->getBlock(fileId);
1603 toFollow = aBlock->length();
1605 CORBA::Octet *buf = aBlock->get_buffer();
1606 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1610 MESSAGE("end of transfer");
1611 fileTransfer->close(fileId);
1615 INFOS("open reference file for copy impossible");
1619 //=============================================================================
1620 /*! \brief create a PyNode object to execute remote python code
1621 * \param nodeName the name of the node
1622 * \param code the python code to load
1623 * \return the PyNode
1625 //=============================================================================
1626 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1628 Engines::PyNode_var node= Engines::PyNode::_nil();
1630 PyGILState_STATE gstate = PyGILState_Ensure();
1631 PyObject *res = PyObject_CallMethod(_pyCont,
1632 (char*)"create_pynode",
1640 PyGILState_Release(gstate);
1641 SALOME::ExceptionStruct es;
1642 es.type = SALOME::INTERNAL_ERROR;
1643 es.text = "can not create a python node";
1644 throw SALOME::SALOME_Exception(es);
1646 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1647 PyObject* result=PyTuple_GetItem(res,1);
1648 std::string astr=PyUnicode_AsUTF8(result);
1650 PyGILState_Release(gstate);
1653 Utils_Locker lck(&_mutexForDftPy);
1654 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1655 node=Engines::PyNode::_narrow(obj);
1656 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1657 if(it==_dftPyNode.end())
1659 _dftPyNode[nodeName]=node;
1663 Engines::PyNode_var oldNode((*it).second);
1664 if(!CORBA::is_nil(oldNode))
1665 oldNode->UnRegister();
1668 if(!CORBA::is_nil(node))
1670 return node._retn();
1674 SALOME::ExceptionStruct es;
1675 es.type = SALOME::INTERNAL_ERROR;
1676 es.text = astr.c_str();
1677 throw SALOME::SALOME_Exception(es);
1681 //=============================================================================
1682 /*! \brief Retrieves the last created PyNode instance with createPyNode.
1685 //=============================================================================
1686 Engines::PyNode_ptr Engines_Container_i::getDefaultPyNode(const char *nodeName)
1688 Utils_Locker lck(&_mutexForDftPy);
1689 std::map<std::string,Engines::PyNode_var>::iterator it(_dftPyNode.find(nodeName));
1690 if(it==_dftPyNode.end())
1691 return Engines::PyNode::_nil();
1694 Engines::PyNode_var tmpVar((*it).second);
1695 if(!CORBA::is_nil(tmpVar))
1696 return Engines::PyNode::_duplicate(tmpVar);
1698 return Engines::PyNode::_nil();
1702 //=============================================================================
1703 /*! \brief create a PyScriptNode object to execute remote python code
1704 * \param nodeName the name of the node
1705 * \param code the python code to load
1706 * \return the PyScriptNode
1708 //=============================================================================
1709 Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1711 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1713 PyGILState_STATE gstate = PyGILState_Ensure();
1714 PyObject *res = PyObject_CallMethod(_pyCont,
1715 (char*)"create_pyscriptnode",
1723 PyGILState_Release(gstate);
1724 SALOME::ExceptionStruct es;
1725 es.type = SALOME::INTERNAL_ERROR;
1726 es.text = "can not create a python node";
1727 throw SALOME::SALOME_Exception(es);
1729 long ierr=PyLong_AsLong(PyTuple_GetItem(res,0));
1730 PyObject* result=PyTuple_GetItem(res,1);
1731 std::string astr=PyUnicode_AsUTF8(result);
1733 PyGILState_Release(gstate);
1737 Utils_Locker lck(&_mutexForDftPy);
1738 CORBA::Object_var obj=_orb->string_to_object(astr.c_str());
1739 node=Engines::PyScriptNode::_narrow(obj);
1740 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
1741 if(it==_dftPyScriptNode.end())
1743 _dftPyScriptNode[nodeName]=node;
1747 Engines::PyScriptNode_var oldNode((*it).second);
1748 if(!CORBA::is_nil(oldNode))
1749 oldNode->UnRegister();
1752 if(!CORBA::is_nil(node))
1754 return node._retn();
1758 SALOME::ExceptionStruct es;
1759 es.type = SALOME::INTERNAL_ERROR;
1760 es.text = astr.c_str();
1761 throw SALOME::SALOME_Exception(es);
1765 //=============================================================================
1766 /*! \brief Retrieves the last created PyScriptNode instance with createPyScriptNode.
1769 //=============================================================================
1770 Engines::PyScriptNode_ptr Engines_Container_i::getDefaultPyScriptNode(const char *nodeName)
1772 Utils_Locker lck(&_mutexForDftPy);
1773 std::map<std::string,Engines::PyScriptNode_var>::iterator it(_dftPyScriptNode.find(nodeName));
1774 if(it==_dftPyScriptNode.end())
1775 return Engines::PyScriptNode::_nil();
1778 Engines::PyScriptNode_var tmpVar((*it).second);
1779 if(!CORBA::is_nil(tmpVar))
1780 return Engines::PyScriptNode::_duplicate(tmpVar);
1782 return Engines::PyScriptNode::_nil();
1786 //=============================================================================
1787 /* int checkifexecutable(const char *filename)
1789 * Return non-zero if the name is an executable file, and
1790 * zero if it is not executable, or if it does not exist.
1792 //=============================================================================
1793 int checkifexecutable(const std::string& filename)
1796 struct stat statinfo;
1798 result = stat(filename.c_str(), &statinfo);
1799 if (result < 0) return 0;
1800 if (!S_ISREG(statinfo.st_mode)) return 0;
1805 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1806 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1807 return statinfo.st_mode & S_IXOTH;
1812 //=============================================================================
1813 /*! \brief Find a file by searching in a path
1814 * \param filename file name to search
1815 * \param path path to search in
1816 * \param pth the complete file path if found
1817 * \return 1 if found 0 if not
1819 //=============================================================================
1820 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1822 if ( path.size() == 0 ) return 0;
1824 std::string::size_type offset = 0;
1825 std::string::size_type pos = 0;
1827 struct stat statinfo;
1831 pos = path.find( SEP, offset );
1832 pth = path.substr( offset, pos - offset );
1833 if ( pth.size() > 0 )
1835 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1837 int result=stat(pth.c_str(), &statinfo);
1838 if(result == 0) found=1;
1840 if (pos == std::string::npos) break;
1846 void Engines_Container_i::registerTemporaryFile( const std::string& fileName )
1848 _tmp_files.remove( fileName );
1849 _tmp_files.push_back( fileName );
1852 void Engines_Container_i::unregisterTemporaryFile( const std::string& fileName )
1854 _tmp_files.remove( fileName );
1857 void Engines_Container_i::clearTemporaryFiles()
1859 std::list<std::string>::const_iterator it;
1860 for ( it = _tmp_files.begin(); it != _tmp_files.end(); ++it ) {
1862 std::string command = (GetFileAttributes((*it).c_str()) == FILE_ATTRIBUTE_DIRECTORY) ? "rd /Q \"" : "del /F /Q \"";
1864 std::string command = "rm -rf ";
1868 command += "\" 2>NUL";
1870 system( command.c_str() );
1876 std::string Engines_Container_i::AnotherMethodeToReplace_PyString_AsString(PyObject * result)
1878 std::string my_result = "";
1879 if (PyUnicode_Check(result)) {
1880 // Convert string to bytes.
1881 // strdup() bytes into my_result.
1882 PyObject * temp_bytes = PyUnicode_AsEncodedString(result, "ASCII", "strict"); // Owned reference
1883 if (temp_bytes != NULL) {
1884 my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
1885 my_result = strdup(my_result);
1886 Py_DECREF(temp_bytes);
1888 // TODO PY3: Handle encoding error.
1889 Py_DECREF(temp_bytes);
1892 } else if (PyBytes_Check(result)) {
1893 // strdup() bytes into my_result.
1894 my_result = PyBytes_AS_STRING(result); // Borrowed pointer
1895 my_result = strdup(my_result);
1897 // Convert into your favorite string representation.
1898 // Convert string to bytes if it is not already.
1899 // strdup() bytes into my_result.
1900 // TODO PY3: Check if only bytes is ok.
1901 PyObject * temp_bytes = PyObject_Bytes(result); // Owned reference
1902 if (temp_bytes != NULL) {
1903 my_result = PyBytes_AS_STRING(temp_bytes); // Borrowed pointer
1904 my_result = strdup(my_result);
1905 Py_DECREF(temp_bytes);
1907 // TODO PY3: Handle error.
1908 Py_DECREF(temp_bytes);