1 // Copyright (C) 2007-2010 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.
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"
60 #include "Container_init_python.hxx"
62 bool _Sleeping = false ;
64 // // Needed by multi-threaded Python --- Supervision
68 extern "C" {void ActSigIntHandler() ; }
70 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
72 extern "C" {void SigIntHandler( int ) ; }
77 #define ENGINESO "Engine.so"
80 #define ENGINESO "Engine.dll"
91 std::map<std::string, int> Engines_Container_i::_cntInstances_map;
92 std::map<std::string, void *> Engines_Container_i::_library_map;
93 std::map<std::string, void *> Engines_Container_i::_toRemove_map;
94 omni_mutex Engines_Container_i::_numInstanceMutex ;
96 static PyObject* _pyCont;
98 int checkifexecutable(const std::string&);
99 int findpathof(const std::string& path, std::string&, const std::string&);
101 /*! \class Engines_Container_i
102 * \brief C++ implementation of Engines::Container interface
107 //=============================================================================
109 * Default constructor, not for use
111 //=============================================================================
113 Engines_Container_i::Engines_Container_i () :
114 _numInstance(0),_id(0),_NS(0)
118 //=============================================================================
122 //=============================================================================
124 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
125 PortableServer::POA_ptr poa,
126 char *containerName ,
127 int argc , char* argv[],
129 bool isServantAloneInProcess
131 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess),_id(0),_NS(0)
133 _pid = (long)getpid();
141 std::string hostname = Kernel_Utils::GetHostname();
143 MESSAGE(hostname << " " << getpid() <<
144 " Engines_Container_i starting argc " <<
145 _argc << " Thread " << pthread_self() ) ;
147 MESSAGE(hostname << " " << _getpid() <<
148 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
154 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
160 INFOS("SALOME_Container usage : SALOME_Container ServerName");
164 _isSupervContainer = false;
166 _orb = CORBA::ORB::_duplicate(orb) ;
167 _poa = PortableServer::POA::_duplicate(poa) ;
169 // Pour les containers paralleles: il ne faut pas enregistrer et activer
170 // le container generique, mais le container specialise
174 _id = _poa->activate_object(this);
175 _NS = new SALOME_NamingService();
176 _NS->init_orb( _orb ) ;
177 CORBA::Object_var obj=_poa->id_to_reference(*_id);
178 Engines::Container_var pCont
179 = Engines::Container::_narrow(obj);
182 _containerName = _NS->BuildContainerNameForNS(containerName,
184 SCRUTE(_containerName);
185 _NS->Register(pCont, _containerName.c_str());
186 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
190 // import SALOME_Container
191 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
193 CORBA::String_var sior = _orb->object_to_string(pCont);
194 std::string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
195 myCommand += _containerName + "','";
200 PyGILState_STATE gstate = PyGILState_Ensure();
203 // mpv: this is temporary solution: there is a unregular crash if not
206 // first element is the path to Registry.dll, but it's wrong
207 PyRun_SimpleString("import sys\n");
208 PyRun_SimpleString("sys.path = sys.path[1:]\n");
210 PyRun_SimpleString("import SALOME_Container\n");
211 PyRun_SimpleString((char*)myCommand.c_str());
212 PyObject *mainmod = PyImport_AddModule("__main__");
213 PyObject *globals = PyModule_GetDict(mainmod);
214 _pyCont = PyDict_GetItemString(globals, "pyCont");
216 PyGILState_Release(gstate);
218 fileTransfer_i* aFileTransfer = new fileTransfer_i();
219 CORBA::Object_var obref=aFileTransfer->_this();
220 _fileTransfer = Engines::fileTransfer::_narrow(obref);
221 aFileTransfer->_remove_ref();
225 //=============================================================================
229 //=============================================================================
231 Engines_Container_i::~Engines_Container_i()
233 MESSAGE("Container_i::~Container_i()");
240 //=============================================================================
241 //! Get container name
243 * CORBA attribute: Container name (see constructor)
245 //=============================================================================
247 char* Engines_Container_i::name()
249 return CORBA::string_dup(_containerName.c_str()) ;
252 //=============================================================================
253 //! Get container working directory
255 * CORBA attribute: Container working directory
257 //=============================================================================
259 char* Engines_Container_i::workingdir()
263 return CORBA::string_dup(wd) ;
266 //=============================================================================
267 //! Get container log file name
269 * CORBA attribute: Container log file name
271 //=============================================================================
273 char* Engines_Container_i::logfilename()
275 return CORBA::string_dup(_logfilename.c_str()) ;
278 //! Set container log file name
279 void Engines_Container_i::logfilename(const char* name)
284 //=============================================================================
285 //! Get container host name
287 * CORBA method: Get the hostName of the Container (without domain extensions)
289 //=============================================================================
291 char* Engines_Container_i::getHostName()
293 std::string s = Kernel_Utils::GetHostname();
294 // MESSAGE("Engines_Container_i::getHostName " << s);
295 return CORBA::string_dup(s.c_str()) ;
298 //=============================================================================
299 //! Get container PID
301 * CORBA method: Get the PID (process identification) of the Container
303 //=============================================================================
305 CORBA::Long Engines_Container_i::getPID()
307 return (CORBA::Long)getpid();
310 //=============================================================================
311 //! Ping the servant to check it is still alive
313 * CORBA method: check if servant is still alive
315 //=============================================================================
316 void Engines_Container_i::ping()
318 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
321 //=============================================================================
322 //! Shutdown the container
324 * CORBA method, oneway: Server shutdown.
325 * - Container name removed from naming service,
326 * - servant deactivation,
327 * - orb shutdown if no other servants in the process
329 //=============================================================================
330 void Engines_Container_i::Shutdown()
332 MESSAGE("Engines_Container_i::Shutdown()");
334 /* For each component contained in this container
335 * tell it to self-destroy
337 std::map<std::string, Engines::EngineComponent_var>::iterator itm;
338 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
342 itm->second->destroy();
344 catch(const CORBA::Exception& e)
346 // ignore this entry and continue
350 // ignore this entry and continue
353 _listInstances_map.clear();
355 _NS->Destroy_FullDirectory(_containerName.c_str());
356 _NS->Destroy_Name(_containerName.c_str());
357 if(_isServantAloneInProcess)
359 MESSAGE("Effective Shutdown of container Begins...");
360 if(!CORBA::is_nil(_orb))
365 //=============================================================================
366 //! load a component implementation
369 * \param componentName component name
370 * \param reason explains error when load fails
371 * \return true if dlopen successfull or already done, false otherwise
373 //=============================================================================
375 Engines_Container_i::load_component_Library(const char* componentName, CORBA::String_out reason)
378 //=================================================================
379 // --- C++ implementation section
380 //=================================================================
382 if(load_component_CppImplementation(componentName,retso))
384 reason=CORBA::string_dup("");
387 else if(retso != "ImplementationNotFound")
389 reason=CORBA::string_dup(retso.c_str());
394 retso+=componentName;
395 retso+=": Can't find C++ implementation ";
396 retso+=std::string(LIB) + componentName + ENGINESO;
398 //=================================================================
399 // --- Python implementation section
400 //=================================================================
402 if(load_component_PythonImplementation(componentName,retpy))
404 reason=CORBA::string_dup("");
407 else if(retpy != "ImplementationNotFound")
409 reason=CORBA::string_dup(retpy.c_str());
414 retpy+=componentName;
415 retpy+=": Can't find python implementation ";
416 retpy+=componentName;
419 //=================================================================
420 // -- Executable implementation section
421 //=================================================================
423 if(load_component_ExecutableImplementation(componentName,retex))
425 reason=CORBA::string_dup("");
428 else if(retex != "ImplementationNotFound")
430 reason=CORBA::string_dup(retex.c_str());
435 retex+=componentName;
436 retex+=": Can't find executable implementation ";
437 retex+=componentName;
440 std::string ret="Component implementation not found: ";
441 ret += componentName ;
447 std::cerr << ret << std::endl;
448 reason=CORBA::string_dup(ret.c_str());
453 //=============================================================================
454 //! try to load a C++ component implementation
457 * \param componentName the name of the component (COMPONENT, for example)
458 * \param reason explains error when load fails
459 * \return true if loading is successfull or already done, false otherwise
461 //=============================================================================
463 Engines_Container_i::load_component_CppImplementation(const char* componentName, std::string& reason)
465 std::string aCompName(componentName);
466 std::string impl_name = std::string(LIB) + aCompName + ENGINESO;
469 _numInstanceMutex.lock(); // lock to be alone
470 // (see decInstanceCnt, finalize_removal))
471 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
472 if (_library_map.count(impl_name) != 0)
474 MESSAGE("Library " << impl_name << " already loaded");
475 _numInstanceMutex.unlock();
479 _numInstanceMutex.unlock();
483 handle = dlopen( impl_name.c_str() , RTLD_NOW ) ;
486 //not loadable. Try to find the lib file in LD_LIBRARY_PATH
488 char* p=getenv("LD_LIBRARY_PATH");
490 path=path+SEP+"/usr/lib"+SEP+"/lib";
493 if(findpathof(path, pth, impl_name))
495 //found but not loadable
498 reason+=": C++ implementation found ";
500 reason+=" but it is not loadable. Error:\n";
502 std::cerr << reason << std::endl;
508 //continue with other implementation
509 reason="ImplementationNotFound";
515 handle = LoadLibrary( impl_name.c_str() );
518 reason="ImplementationNotFound";
524 _numInstanceMutex.lock();
525 _library_map[impl_name] = handle;
526 _numInstanceMutex.unlock();
534 //=============================================================================
535 //! try to load a Python component implementation
538 * \param componentName name of the component
539 * \param reason explains error when load fails
540 * \return true if loading is successfull or already done, false otherwise
542 //=============================================================================
544 Engines_Container_i::load_component_PythonImplementation(const char* componentName, std::string& reason)
546 std::string aCompName(componentName);
548 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
549 if (_library_map.count(aCompName) != 0)
551 _numInstanceMutex.unlock() ;
553 return true; // Python Component, already imported
555 _numInstanceMutex.unlock() ;
557 PyGILState_STATE gstate = PyGILState_Ensure();
558 PyObject *result = PyObject_CallMethod(_pyCont,
559 (char*)"import_component",
560 (char*)"s",componentName);
562 reason=PyString_AsString(result);
565 PyGILState_Release(gstate);
569 //Python component has been loaded (import componentName)
570 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
571 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
572 _numInstanceMutex.unlock() ;
573 MESSAGE("import Python: "<< aCompName <<" OK");
576 else if(reason=="ImplementationNotFound")
578 //Python implementation has not been found. Continue with other implementation
579 reason="ImplementationNotFound";
583 //Python implementation has been found but loading has failed
584 std::cerr << reason << std::endl;
589 //=============================================================================
590 //! try to load a Executable component implementation
593 * \param componentName name of the component
594 * \param reason explains error when load fails
595 * \return true if loading is successfull or already done, false otherwise
597 //=============================================================================
599 Engines_Container_i::load_component_ExecutableImplementation(const char* componentName, std::string& reason)
601 std::string aCompName(componentName);
602 std::string executable=aCompName+".exe";
607 char* p=getenv("PATH");
610 if (findpathof(path, pth, executable))
612 if(checkifexecutable(pth))
614 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
615 _library_map[executable] = (void *)1; // any non O value OK
616 _numInstanceMutex.unlock() ;
617 MESSAGE("import executable: "<< pth <<" OK");
623 reason+=": implementation found ";
625 reason+=" but it is not executable";
626 std::cerr << reason << std::endl;
630 reason="ImplementationNotFound";
635 //=============================================================================
636 //! Create a new component instance
638 * CORBA method: Creates a new servant instance of a component.
639 * The servant registers itself to naming service and Registry.
640 * \param genericRegisterName Name of the component instance to register
641 * in Registry & Name Service (without _inst_n suffix)
642 * \param studyId 0 for multiStudy instance,
643 * study Id (>0) otherwise
644 * \return a loaded component
646 //=============================================================================
647 Engines::EngineComponent_ptr
648 Engines_Container_i::create_component_instance(const char*genericRegisterName,
651 Engines::FieldsDict_var env = new Engines::FieldsDict;
653 Engines::EngineComponent_ptr compo =
654 create_component_instance_env(genericRegisterName, studyId, env, reason);
655 CORBA::string_free(reason);
659 //=============================================================================
660 //! Create a new component instance with environment variables specified
662 * CORBA method: Creates a new servant instance of a component.
663 * The servant registers itself to naming service and Registry.
664 * \param genericRegisterName Name of the component instance to register
665 * in Registry & Name Service (without _inst_n suffix)
666 * \param studyId 0 for multiStudy instance,
667 * study Id (>0) otherwise
668 * \param env dict of env variables
669 * \param reason explains error when create_component_instance_env fails
670 * \return a loaded component
672 //=============================================================================
673 Engines::EngineComponent_ptr
674 Engines_Container_i::create_component_instance_env(const char*genericRegisterName,
676 const Engines::FieldsDict& env,
677 CORBA::String_out reason)
681 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
682 reason=CORBA::string_dup("studyId must be > 0 for mono study instance, =0 for multiStudy");
683 return Engines::EngineComponent::_nil() ;
687 if (_library_map.count(genericRegisterName) != 0)
689 // It's a Python component
690 Engines::EngineComponent_ptr compo = createPythonInstance(genericRegisterName, studyId, error);
691 reason=CORBA::string_dup(error.c_str());
695 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
696 if (_library_map.count(impl_name) != 0)
698 // It's a C++ component
699 void* handle = _library_map[impl_name];
700 Engines::EngineComponent_ptr compo = createInstance(genericRegisterName, handle, studyId, error);
701 reason=CORBA::string_dup(error.c_str());
705 impl_name = std::string(genericRegisterName) + ".exe";
706 if (_library_map.count(impl_name) != 0)
708 //It's an executable component
709 Engines::EngineComponent_ptr compo = createExecutableInstance(genericRegisterName, studyId, env, error);
710 reason=CORBA::string_dup(error.c_str());
714 error="load_component_Library has probably not been called for component: ";
715 error += genericRegisterName;
717 reason=CORBA::string_dup(error.c_str());
718 return Engines::EngineComponent::_nil() ;
721 //=============================================================================
722 //! Create a new component instance (Executable implementation)
724 * \param CompName Name of the component instance
725 * \param studyId 0 for multiStudy instance,
726 * study Id (>0) otherwise
727 * \param env dict of env variables
728 * \param reason explains error when creation fails
729 * \return a loaded component
731 * This component is implemented in an executable with name genericRegisterName.exe
732 * It must register itself in Naming Service. The container waits some time (10 s max)
735 //=============================================================================
736 Engines::EngineComponent_ptr
737 Engines_Container_i::createExecutableInstance(std::string CompName, int studyId,
738 const Engines::FieldsDict& env,
741 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
743 _numInstanceMutex.lock() ; // lock on the instance number
745 int numInstance = _numInstance ;
746 _numInstanceMutex.unlock() ;
749 sprintf( aNumI , "%d" , numInstance ) ;
750 std::string instanceName = CompName + "_inst_" + aNumI ;
751 std::string component_registerName = _containerName + "/" + instanceName;
753 //check if an entry exist in naming service
754 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
755 if ( !CORBA::is_nil(nsobj) )
757 // unregister the registered component
758 _NS->Destroy_Name(component_registerName.c_str());
759 //kill or shutdown it ???
762 // first arg container ior string
763 // second arg container name
764 // third arg instance name
766 Engines::Container_var pCont= _this();
767 CORBA::String_var sior = _orb->object_to_string(pCont);
771 command+=instanceName;
773 command+=instanceName;
778 command+= sior; // container ior string
780 command+=_containerName; //container name
782 command+=instanceName; //instance name
784 MESSAGE("SALOME_Container::create_component_instance command=" << command);
787 // use fork/execl instead of system to get finer control on env variables
790 if(pid == 0) // child
792 for (CORBA::ULong i=0; i < env.length(); i++)
794 if (env[i].value.type()->kind() == CORBA::tk_string)
797 env[i].value >>= value;
798 std::string s(env[i].key);
801 putenv(strdup(s.c_str()));
805 execl("/bin/sh", "sh", "-c", command.c_str() , (char *)0);
808 else if(pid < 0) // failed to fork
817 tpid = wait(&status);
818 } while (tpid != pid);
821 // launch component with a system call
822 int status=system(command.c_str());
827 reason="SALOME_Container::create_component_instance system failed (system command status -1)";
829 return Engines::EngineComponent::_nil();
832 else if (WEXITSTATUS(status) == 217)
834 reason="SALOME_Container::create_component_instance system failed (system command status 217)";
836 return Engines::EngineComponent::_nil();
842 CORBA::Object_var obj = CORBA::Object::_nil() ;
843 while ( CORBA::is_nil(obj) && count )
851 MESSAGE( count << ". Waiting for component " << CompName);
852 obj = _NS->Resolve(component_registerName.c_str());
855 if(CORBA::is_nil(obj))
857 reason="SALOME_Container::create_component_instance failed";
859 return Engines::EngineComponent::_nil();
863 MESSAGE("SALOME_Container::create_component_instance successful");
864 iobject = Engines::EngineComponent::_narrow(obj);
865 _listInstances_map[instanceName] = iobject;
866 return iobject._retn();
872 //=============================================================================
873 //! Create a new component instance (Python implementation)
875 * \param CompName Name of the component instance
876 * \param studyId 0 for multiStudy instance,
877 * study Id (>0) otherwise
878 * \param reason explains error when creation fails
879 * \return a loaded component
881 //=============================================================================
882 Engines::EngineComponent_ptr
883 Engines_Container_i::createPythonInstance(std::string CompName, int studyId,
886 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
888 _numInstanceMutex.lock() ; // lock on the instance number
890 int numInstance = _numInstance ;
891 _numInstanceMutex.unlock() ;
894 sprintf( aNumI , "%d" , numInstance ) ;
895 std::string instanceName = CompName + "_inst_" + aNumI ;
896 std::string component_registerName = _containerName + "/" + instanceName;
898 PyGILState_STATE gstate = PyGILState_Ensure();
899 PyObject *result = PyObject_CallMethod(_pyCont,
900 (char*)"create_component_instance",
903 instanceName.c_str(),
907 PyArg_ParseTuple(result,"ss", &ior, &error);
908 std::string iors = ior;
911 PyGILState_Release(gstate);
915 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
916 iobject = Engines::EngineComponent::_narrow( obj ) ;
917 _listInstances_map[instanceName] = iobject;
919 return iobject._retn();
922 //=============================================================================
923 //! Create a new component instance (C++ implementation)
925 * C++ method: create a servant instance of a component.
926 * \param genericRegisterName Name of the component instance to register
927 * in Registry & Name Service,
928 * (without _inst_n suffix, like "COMPONENT")
929 * \param handle loaded library handle
930 * \param studyId 0 for multiStudy instance,
931 * study Id (>0) otherwise
932 * \param reason explains error when creation fails
933 * \return a loaded component
935 * example with names:
936 * - aGenRegisterName = COMPONENT (= first argument)
937 * - _containerName = /Containers/cli76ce/FactoryServer
938 * - factoryName = COMPONENTEngine_factory
939 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
940 * - instanceName = COMPONENT_inst_1
941 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
943 //=============================================================================
944 Engines::EngineComponent_ptr
945 Engines_Container_i::createInstance(std::string genericRegisterName,
950 // --- find the factory
952 std::string aGenRegisterName = genericRegisterName;
953 std::string factory_name = aGenRegisterName + std::string("Engine_factory");
954 SCRUTE(factory_name) ;
956 typedef PortableServer::ObjectId* (*FACTORY_FUNCTION) (CORBA::ORB_ptr,
957 PortableServer::POA_ptr,
958 PortableServer::ObjectId *,
963 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
965 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
968 if ( !Component_factory )
970 INFOS( "Can't resolve symbol: " + factory_name );
975 return Engines::EngineComponent::_nil() ;
978 // --- create instance
980 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
984 _numInstanceMutex.lock() ; // lock on the instance number
986 int numInstance = _numInstance ;
987 _numInstanceMutex.unlock() ;
990 sprintf( aNumI , "%d" , numInstance ) ;
991 std::string instanceName = aGenRegisterName + "_inst_" + aNumI ;
992 std::string component_registerName =
993 _containerName + "/" + instanceName;
995 // --- Instanciate required CORBA object
997 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
998 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
999 aGenRegisterName.c_str() ) ;
1002 reason="Can't get ObjectId from factory";
1004 return iobject._retn();
1007 // --- get reference & servant from id
1009 CORBA::Object_var obj = _poa->id_to_reference(*id);
1010 iobject = Engines::EngineComponent::_narrow( obj ) ;
1012 Engines_Component_i *servant =
1013 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1015 //SCRUTE(servant->_refcount_value());
1016 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1017 _listInstances_map[instanceName] = iobject;
1018 _cntInstances_map[aGenRegisterName] += 1;
1019 _numInstanceMutex.unlock() ;
1020 SCRUTE(aGenRegisterName);
1021 SCRUTE(_cntInstances_map[aGenRegisterName]);
1022 servant->setStudyId(studyId);
1023 servant->_remove_ref(); // do not need servant any more (remove ref from reference_to_servant)
1024 //SCRUTE(servant->_refcount_value());
1026 // --- register the engine under the name
1027 // containerName(.dir)/instanceName(.object)
1029 _NS->Register( iobject , component_registerName.c_str() ) ;
1030 MESSAGE( component_registerName.c_str() << " bound" ) ;
1034 reason="Container_i::createInstance exception catched";
1037 return iobject._retn();
1040 //=============================================================================
1041 //! Find an existing (in the container) component instance
1043 * CORBA method: Finds a servant instance of a component
1044 * \param registeredName Name of the component in Registry or Name Service,
1045 * without instance suffix number
1046 * \param studyId 0 if instance is not associated to a study,
1047 * >0 otherwise (== study id)
1048 * \return the first instance found with same studyId
1050 //=============================================================================
1051 Engines::EngineComponent_ptr
1052 Engines_Container_i::find_component_instance( const char* registeredName,
1053 CORBA::Long studyId)
1055 Engines::EngineComponent_var anEngine = Engines::EngineComponent::_nil();
1056 std::map<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
1057 while (itm != _listInstances_map.end())
1059 std::string instance = (*itm).first;
1061 if (instance.find(registeredName) == 0)
1063 anEngine = (*itm).second;
1064 if (studyId == anEngine->getStudyId())
1066 return anEngine._retn();
1071 return anEngine._retn();
1074 //=============================================================================
1075 //! Remove the component instance from container
1077 * CORBA method: Stops the component servant, and deletes all related objects
1078 * \param component_i Component to be removed
1080 //=============================================================================
1082 void Engines_Container_i::remove_impl(Engines::EngineComponent_ptr component_i)
1084 ASSERT(! CORBA::is_nil(component_i));
1085 std::string instanceName = component_i->instanceName() ;
1086 MESSAGE("unload component " << instanceName);
1087 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1088 _listInstances_map.erase(instanceName);
1089 _numInstanceMutex.unlock() ;
1090 component_i->destroy() ;
1091 _NS->Destroy_Name(instanceName.c_str());
1094 //=============================================================================
1095 //! Unload component libraries from the container
1097 * CORBA method: Discharges unused libraries from the container.
1099 //=============================================================================
1100 void Engines_Container_i::finalize_removal()
1102 MESSAGE("finalize unload : dlclose");
1103 _numInstanceMutex.lock(); // lock to be alone
1104 // (see decInstanceCnt, load_component_Library)
1105 std::map<std::string, void *>::iterator ith;
1106 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
1108 void *handle = (*ith).second;
1109 std::string impl_name= (*ith).first;
1114 // dlclose(handle); // SALOME unstable after ...
1115 // _library_map.erase(impl_name);
1118 _toRemove_map.clear();
1119 _numInstanceMutex.unlock();
1122 //=============================================================================
1123 //! Decrement component instance reference count
1127 //=============================================================================
1128 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1130 if(_cntInstances_map.count(genericRegisterName)==0)
1132 std::string aGenRegisterName =genericRegisterName;
1133 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1134 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1135 _numInstanceMutex.lock(); // lock to be alone
1136 // (see finalize_removal, load_component_Library)
1137 _cntInstances_map[aGenRegisterName] -= 1;
1138 SCRUTE(_cntInstances_map[aGenRegisterName]);
1139 if (_cntInstances_map[aGenRegisterName] == 0)
1141 std::string impl_name =
1142 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1144 void* handle = _library_map[impl_name];
1146 _toRemove_map[impl_name] = handle;
1148 _numInstanceMutex.unlock();
1151 //=============================================================================
1152 //! Find or create a new component instance
1154 * CORBA method: find or create an instance of the component (servant),
1155 * load a new component class (dynamic library) if required,
1157 * ---- FOR COMPATIBILITY WITH 2.2 ----
1159 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1161 * The servant registers itself to naming service and Registry.
1162 * \param genericRegisterName Name of the component to register
1163 * in Registry & Name Service
1164 * \param componentName Name of the constructed library of the component
1165 * \return a loaded component
1167 //=============================================================================
1169 Engines::EngineComponent_ptr
1170 Engines_Container_i::load_impl( const char* genericRegisterName,
1171 const char* componentName )
1174 std::string impl_name = std::string(LIB) + genericRegisterName + ENGINESO;
1175 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1176 if (load_component_Library(genericRegisterName,reason))
1177 iobject = find_or_create_instance(genericRegisterName, impl_name);
1178 CORBA::string_free(reason);
1179 return iobject._retn();
1182 //=============================================================================
1183 //! Finds an already existing component instance or create a new instance
1185 * C++ method: Finds an already existing servant instance of a component, or
1186 * create an instance.
1187 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
1188 * \param genericRegisterName Name of the component instance to register
1189 * in Registry & Name Service,
1190 * (without _inst_n suffix, like "COMPONENT")
1191 * \param componentLibraryName like "libCOMPONENTEngine.so"
1192 * \return a loaded component
1194 * example with names:
1195 * - aGenRegisterName = COMPONENT (= first argument)
1196 * - impl_name = libCOMPONENTEngine.so (= second argument)
1197 * - _containerName = /Containers/cli76ce/FactoryServer
1198 * - factoryName = COMPONENTEngine_factory
1199 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1200 * - instanceName = COMPONENT_inst_1
1201 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1203 //=============================================================================
1205 Engines::EngineComponent_ptr
1206 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1207 std::string componentLibraryName)
1209 std::string aGenRegisterName = genericRegisterName;
1210 std::string impl_name = componentLibraryName;
1211 if (_library_map.count(impl_name) == 0)
1213 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1214 return Engines::EngineComponent::_nil() ;
1218 // --- find a registered instance in naming service, or create
1220 void* handle = _library_map[impl_name];
1221 std::string component_registerBase =
1222 _containerName + "/" + aGenRegisterName;
1223 Engines::EngineComponent_var iobject = Engines::EngineComponent::_nil() ;
1227 CORBA::Object_var obj =
1228 _NS->ResolveFirst( component_registerBase.c_str());
1229 if ( CORBA::is_nil( obj ) )
1231 iobject = createInstance(genericRegisterName,
1234 reason); // force multiStudy instance here !
1238 iobject = Engines::EngineComponent::_narrow( obj ) ;
1239 Engines_Component_i *servant =
1240 dynamic_cast<Engines_Component_i*>
1241 (_poa->reference_to_servant(iobject));
1243 int studyId = servant->getStudyId();
1244 ASSERT (studyId >= 0);
1245 if (studyId == 0) // multiStudy instance, OK
1248 MESSAGE(component_registerBase.c_str()<<" already bound");
1250 else // monoStudy instance: NOK
1252 iobject = Engines::EngineComponent::_nil();
1253 INFOS("load_impl & find_component_instance methods "
1254 << "NOT SUITABLE for mono study components");
1260 INFOS( "Container_i::load_impl catched" ) ;
1262 return iobject._retn();
1266 //=============================================================================
1267 //! Indicate if container is a python one
1269 * Retrieves only with container naming convention if it is a python container
1271 //=============================================================================
1272 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1275 int len=strlen(ContainerName);
1277 if(strcmp(ContainerName+len-2,"Py")==0)
1282 //=============================================================================
1283 //! Kill the container
1285 * CORBA method: Kill the container process with exit(0).
1286 * To remove : never returns !
1288 //=============================================================================
1289 bool Engines_Container_i::Kill_impl()
1291 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
1292 << _containerName.c_str() << " machineName "
1293 << Kernel_Utils::GetHostname().c_str());
1294 INFOS("===============================================================");
1295 INFOS("= REMOVE calls to Kill_impl in C++ container =");
1296 INFOS("===============================================================");
1302 //=============================================================================
1306 //=============================================================================
1307 void ActSigIntHandler()
1310 struct sigaction SigIntAct ;
1311 SigIntAct.sa_sigaction = &SigIntHandler ;
1312 sigemptyset(&SigIntAct.sa_mask);
1313 SigIntAct.sa_flags = SA_SIGINFO ;
1316 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1317 // (SIGINT | SIGUSR1) :
1318 // it must be only one signal ===> one call for SIGINT
1319 // and an other one for SIGUSR1
1322 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1324 perror("SALOME_Container main ") ;
1327 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1329 perror("SALOME_Container main ") ;
1332 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1334 perror("SALOME_Container main ") ;
1338 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1339 // use of streams (and so on) should never be used because :
1340 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1341 // A stream operation may be interrupted by a signal and if the Handler use stream we
1342 // may have a "Dead-Lock" ===HangUp
1343 //==INFOS is commented
1344 // INFOS(pthread_self() << "SigIntHandler activated") ;
1347 signal( SIGINT, SigIntHandler );
1348 signal( SIGUSR1, SigIntHandler );
1354 void CallCancelThread() ;
1357 void SigIntHandler(int what ,
1358 siginfo_t * siginfo ,
1361 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1362 // use of streams (and so on) should never be used because :
1363 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1364 // A stream operation may be interrupted by a signal and if the Handler use stream we
1365 // may have a "Dead-Lock" ===HangUp
1366 //==MESSAGE is commented
1367 // MESSAGE(pthread_self() << "SigIntHandler what " << what << std::endl
1368 // << " si_signo " << siginfo->si_signo << std::endl
1369 // << " si_code " << siginfo->si_code << std::endl
1370 // << " si_pid " << siginfo->si_pid) ;
1375 // MESSAGE("SigIntHandler END sleeping.") ;
1380 ActSigIntHandler() ;
1381 if ( siginfo->si_signo == SIGUSR1 )
1385 else if ( siginfo->si_signo == SIGUSR2 )
1387 CallCancelThread() ;
1392 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1399 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1405 void SigIntHandler( int what )
1408 MESSAGE( pthread_self() << "SigIntHandler what " << what << std::endl );
1410 MESSAGE( "SigIntHandler what " << what << std::endl );
1415 MESSAGE("SigIntHandler END sleeping.") ;
1420 ActSigIntHandler() ;
1421 if ( what == SIGUSR1 )
1428 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1435 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1442 //=============================================================================
1443 //! Get or create a file reference object associated to a local file (to transfer it)
1445 * CORBA method: get or create a fileRef object associated to a local file
1446 * (a file on the computer on which runs the container server), which stores
1447 * a list of (machine, localFileName) corresponding to copies already done.
1449 * \param origFileName absolute path for a local file to copy on other
1451 * \return a fileRef object associated to the file.
1453 //=============================================================================
1454 Engines::fileRef_ptr
1455 Engines_Container_i::createFileRef(const char* origFileName)
1457 std::string origName(origFileName);
1458 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
1460 if (origName[0] != '/')
1462 INFOS("path of file to copy must be an absolute path begining with '/'");
1463 return Engines::fileRef::_nil();
1466 if (CORBA::is_nil(_fileRef_map[origName]))
1468 CORBA::Object_var obj=_poa->id_to_reference(*_id);
1469 Engines::Container_var pCont = Engines::Container::_narrow(obj);
1470 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
1471 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
1472 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1473 _fileRef_map[origName] = theFileRef;
1474 _numInstanceMutex.unlock() ;
1477 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
1478 ASSERT(! CORBA::is_nil(theFileRef));
1479 return theFileRef._retn();
1482 //=============================================================================
1483 //! Get a fileTransfer reference
1486 * \return a reference to the fileTransfer object
1488 //=============================================================================
1489 Engines::fileTransfer_ptr
1490 Engines_Container_i::getFileTransfer()
1492 Engines::fileTransfer_var aFileTransfer
1493 = Engines::fileTransfer::_duplicate(_fileTransfer);
1494 return aFileTransfer._retn();
1497 //=============================================================================
1498 //! Create a Salome file
1499 //=============================================================================
1500 Engines::Salome_file_ptr
1501 Engines_Container_i::createSalome_file(const char* origFileName)
1503 std::string origName(origFileName);
1504 if (CORBA::is_nil(_Salome_file_map[origName]))
1506 Salome_file_i* aSalome_file = new Salome_file_i();
1507 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
1510 aSalome_file->setLocalFile(origFileName);
1511 aSalome_file->recvFiles();
1513 catch (const SALOME::SALOME_Exception& e)
1515 return Engines::Salome_file::_nil();
1518 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
1519 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
1520 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1521 _Salome_file_map[origName] = theSalome_file;
1522 _numInstanceMutex.unlock() ;
1525 Engines::Salome_file_ptr theSalome_file =
1526 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
1527 ASSERT(!CORBA::is_nil(theSalome_file));
1528 return theSalome_file;
1531 //=============================================================================
1532 /*! \brief copy a file from a remote host (container) to the local host
1533 * \param container the remote container
1534 * \param remoteFile the file to copy locally from the remote host into localFile
1535 * \param localFile the local file
1537 //=============================================================================
1538 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1540 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1543 if ((fp = fopen(localFile,"wb")) == NULL)
1545 INFOS("file " << localFile << " cannot be open for writing");
1549 CORBA::Long fileId = fileTransfer->open(remoteFile);
1552 Engines::fileBlock* aBlock;
1559 aBlock = fileTransfer->getBlock(fileId);
1560 toFollow = aBlock->length();
1562 CORBA::Octet *buf = aBlock->get_buffer();
1563 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1567 MESSAGE("end of transfer");
1568 fileTransfer->close(fileId);
1572 INFOS("open reference file for copy impossible");
1576 //=============================================================================
1577 /*! \brief create a PyNode object to execute remote python code
1578 * \param nodeName the name of the node
1579 * \param code the python code to load
1580 * \return the PyNode
1582 //=============================================================================
1583 Engines::PyNode_ptr Engines_Container_i::createPyNode(const char* nodeName, const char* code)
1585 Engines::PyNode_var node= Engines::PyNode::_nil();
1587 PyGILState_STATE gstate = PyGILState_Ensure();
1588 PyObject *res = PyObject_CallMethod(_pyCont,
1589 (char*)"create_pynode",
1597 PyGILState_Release(gstate);
1598 SALOME::ExceptionStruct es;
1599 es.type = SALOME::INTERNAL_ERROR;
1600 es.text = "can not create a python node";
1601 throw SALOME::SALOME_Exception(es);
1603 long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1604 PyObject* result=PyTuple_GetItem(res,1);
1605 std::string astr=PyString_AsString(result);
1607 PyGILState_Release(gstate);
1611 CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1612 node = Engines::PyNode::_narrow(obj);
1613 return node._retn();
1617 SALOME::ExceptionStruct es;
1618 es.type = SALOME::INTERNAL_ERROR;
1619 es.text = astr.c_str();
1620 throw SALOME::SALOME_Exception(es);
1625 //=============================================================================
1626 /*! \brief create a PyScriptNode object to execute remote python code
1627 * \param nodeName the name of the node
1628 * \param code the python code to load
1629 * \return the PyScriptNode
1631 //=============================================================================
1632 Engines::PyScriptNode_ptr Engines_Container_i::createPyScriptNode(const char* nodeName, const char* code)
1634 Engines::PyScriptNode_var node= Engines::PyScriptNode::_nil();
1636 PyGILState_STATE gstate = PyGILState_Ensure();
1637 PyObject *res = PyObject_CallMethod(_pyCont,
1638 (char*)"create_pyscriptnode",
1646 PyGILState_Release(gstate);
1647 SALOME::ExceptionStruct es;
1648 es.type = SALOME::INTERNAL_ERROR;
1649 es.text = "can not create a python node";
1650 throw SALOME::SALOME_Exception(es);
1652 long ierr=PyInt_AsLong(PyTuple_GetItem(res,0));
1653 PyObject* result=PyTuple_GetItem(res,1);
1654 std::string astr=PyString_AsString(result);
1656 PyGILState_Release(gstate);
1660 CORBA::Object_var obj = _orb->string_to_object(astr.c_str());
1661 node = Engines::PyScriptNode::_narrow(obj);
1662 return node._retn();
1666 SALOME::ExceptionStruct es;
1667 es.type = SALOME::INTERNAL_ERROR;
1668 es.text = astr.c_str();
1669 throw SALOME::SALOME_Exception(es);
1673 //=============================================================================
1674 /* int checkifexecutable(const char *filename)
1676 * Return non-zero if the name is an executable file, and
1677 * zero if it is not executable, or if it does not exist.
1679 //=============================================================================
1680 int checkifexecutable(const std::string& filename)
1683 struct stat statinfo;
1685 result = stat(filename.c_str(), &statinfo);
1686 if (result < 0) return 0;
1687 if (!S_ISREG(statinfo.st_mode)) return 0;
1692 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
1693 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
1694 return statinfo.st_mode & S_IXOTH;
1699 //=============================================================================
1700 /*! \brief Find a file by searching in a path
1701 * \param filename file name to search
1702 * \param path path to search in
1703 * \param pth the complete file path if found
1704 * \return 1 if found 0 if not
1706 //=============================================================================
1707 int findpathof(const std::string& path, std::string& pth, const std::string& filename)
1709 if ( path.size() == 0 ) return 0;
1711 std::string::size_type offset = 0;
1712 std::string::size_type pos = 0;
1714 struct stat statinfo;
1718 pos = path.find( SEP, offset );
1719 pth = path.substr( offset, pos - offset );
1720 if ( pth.size() > 0 )
1722 if( pth[pth.size()-1] != SLASH ) pth += SLASH;
1724 int result=stat(pth.c_str(), &statinfo);
1725 if(result == 0) found=1;
1727 if (pos == std::string::npos) break;