1 // Copyright (C) 2007-2008 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
22 // SALOME Container : implementation of container and engine for Kernel
23 // File : Container_i.cxx
24 // Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
27 //#define private public
43 #include "utilities.h"
44 #include <SALOMEconfig.h>
45 #include CORBA_SERVER_HEADER(SALOME_Component)
46 #include CORBA_SERVER_HEADER(SALOME_Exception)
47 #include <pthread.h> // must be before Python.h !
48 #include "SALOME_Container_i.hxx"
49 #include "SALOME_Component_i.hxx"
50 #include "SALOME_FileRef_i.hxx"
51 #include "SALOME_FileTransfer_i.hxx"
52 #include "Salome_file_i.hxx"
53 #include "SALOME_NamingService.hxx"
54 #include "Basics_Utils.hxx"
57 #include "Container_init_python.hxx"
61 bool _Sleeping = false ;
63 // // Needed by multi-threaded Python --- Supervision
67 extern "C" {void ActSigIntHandler() ; }
69 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
71 extern "C" {void SigIntHandler( int ) ; }
75 # define separator '\\'
77 # define separator '/'
81 map<std::string, int> Engines_Container_i::_cntInstances_map;
82 map<std::string, void *> Engines_Container_i::_library_map;
83 map<std::string, void *> Engines_Container_i::_toRemove_map;
84 omni_mutex Engines_Container_i::_numInstanceMutex ;
86 /*! \class Engines_Container_i
87 * \brief C++ implementation of Engines::Container interface
92 //=============================================================================
94 * Default constructor, not for use
96 //=============================================================================
98 Engines_Container_i::Engines_Container_i () :
99 _numInstance(0),_id(0),_NS(0)
103 //=============================================================================
107 //=============================================================================
109 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
110 PortableServer::POA_ptr poa,
111 char *containerName ,
112 int argc , char* argv[],
114 bool isServantAloneInProcess
116 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess),_id(0),_NS(0)
118 _pid = (long)getpid();
126 string hostname = Kernel_Utils::GetHostname();
128 MESSAGE(hostname << " " << getpid() <<
129 " Engines_Container_i starting argc " <<
130 _argc << " Thread " << pthread_self() ) ;
132 MESSAGE(hostname << " " << _getpid() <<
133 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
139 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
145 INFOS("SALOME_Container usage : SALOME_Container ServerName");
149 _isSupervContainer = false;
150 if (strcmp(argv[1],"SuperVisionContainer") == 0) _isSupervContainer = true;
152 if (_isSupervContainer)
158 _orb = CORBA::ORB::_duplicate(orb) ;
159 _poa = PortableServer::POA::_duplicate(poa) ;
161 // Pour les containers paralleles: il ne faut pas enregistrer et activer
162 // le container generique, mais le container specialise
166 _id = _poa->activate_object(this);
167 _NS = new SALOME_NamingService();
168 _NS->init_orb( _orb ) ;
169 CORBA::Object_var obj=_poa->id_to_reference(*_id);
170 Engines::Container_var pCont
171 = Engines::Container::_narrow(obj);
174 _containerName = _NS->BuildContainerNameForNS(containerName,
176 SCRUTE(_containerName);
177 _NS->Register(pCont, _containerName.c_str());
178 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
182 // import SALOME_Container
183 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
185 CORBA::String_var sior = _orb->object_to_string(pCont);
186 string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
187 myCommand += _containerName + "','";
192 if (!_isSupervContainer)
196 PyEval_AcquireLock();
197 PyThreadState *myTstate = PyThreadState_New(KERNEL_PYTHON::_interp);
198 PyThreadState *myoldTstate = PyThreadState_Swap(myTstate);
200 Py_ACQUIRE_NEW_THREAD;
204 // mpv: this is temporary solution: there is a unregular crash if not
207 // first element is the path to Registry.dll, but it's wrong
208 PyRun_SimpleString("import sys\n");
209 PyRun_SimpleString("sys.path = sys.path[1:]\n");
211 PyRun_SimpleString("import SALOME_Container\n");
212 PyRun_SimpleString((char*)myCommand.c_str());
213 Py_RELEASE_NEW_THREAD;
216 fileTransfer_i* aFileTransfer = new fileTransfer_i();
217 CORBA::Object_var obref=aFileTransfer->_this();
218 _fileTransfer = Engines::fileTransfer::_narrow(obref);
219 aFileTransfer->_remove_ref();
223 //=============================================================================
227 //=============================================================================
229 Engines_Container_i::~Engines_Container_i()
231 MESSAGE("Container_i::~Container_i()");
238 //=============================================================================
239 //! Get container name
241 * CORBA attribute: Container name (see constructor)
243 //=============================================================================
245 char* Engines_Container_i::name()
247 return CORBA::string_dup(_containerName.c_str()) ;
250 //=============================================================================
251 //! Get container working directory
253 * CORBA attribute: Container working directory
255 //=============================================================================
257 char* Engines_Container_i::workingdir()
261 return CORBA::string_dup(wd) ;
264 //=============================================================================
265 //! Get container log file name
267 * CORBA attribute: Container log file name
269 //=============================================================================
271 char* Engines_Container_i::logfilename()
273 return CORBA::string_dup(_logfilename.c_str()) ;
276 //! Set container log file name
277 void Engines_Container_i::logfilename(const char* name)
282 //=============================================================================
283 //! Get container host name
285 * CORBA method: Get the hostName of the Container (without domain extensions)
287 //=============================================================================
289 char* Engines_Container_i::getHostName()
291 string s = Kernel_Utils::GetHostname();
292 // MESSAGE("Engines_Container_i::getHostName " << s);
293 return CORBA::string_dup(s.c_str()) ;
296 //=============================================================================
297 //! Get container PID
299 * CORBA method: Get the PID (process identification) of the Container
301 //=============================================================================
303 CORBA::Long Engines_Container_i::getPID()
305 return (CORBA::Long)getpid();
308 //=============================================================================
309 //! Ping the servant to check it is still alive
311 * CORBA method: check if servant is still alive
313 //=============================================================================
315 void Engines_Container_i::ping()
317 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
320 //=============================================================================
321 //! Shutdown the container
323 * CORBA method, oneway: Server shutdown.
324 * - Container name removed from naming service,
325 * - servant deactivation,
326 * - orb shutdown if no other servants in the process
328 //=============================================================================
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::Component_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
354 _NS->Destroy_FullDirectory(_containerName.c_str());
355 _NS->Destroy_Name(_containerName.c_str());
357 //_poa->deactivate_object(*_id);
358 if(_isServantAloneInProcess)
360 MESSAGE("Effective Shutdown of container Begins...");
361 if(!CORBA::is_nil(_orb))
366 /* int checkifexecutable(const char *filename)
368 * Return non-zero if the name is an executable file, and
369 * zero if it is not executable, or if it does not exist.
372 int checkifexecutable(const string& filename)
375 struct stat statinfo;
377 result = stat(filename.c_str(), &statinfo);
378 if (result < 0) return 0;
379 if (!S_ISREG(statinfo.st_mode)) return 0;
384 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
385 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
386 return statinfo.st_mode & S_IXOTH;
391 /* int findpathof(char *pth, const char *exe)
393 * Find executable by searching the PATH environment variable.
395 * const char *exe - executable name to search for.
396 * char *pth - the path found is stored here, space
397 * needs to be available.
399 * If a path is found, returns non-zero, and the path is stored
400 * in pth. If exe is not found returns 0, with pth undefined.
403 int findpathof(string& pth, const string& exe)
405 string path( getenv("PATH") );
406 if ( path.size() == 0 )
426 while(!stop && !found)
428 int pos = path.find( path_spr, offset );
429 if (pos == string::npos)
432 pth = path.substr( offset, pos - offset );
433 if ( pth.size() > 0 )
435 if( pth[pth.size()-1] != dir_spr )
438 found = checkifexecutable(pth.c_str());
449 if (strchr(exe, separator) != NULL) {
451 if (realpath(exe, pth) == NULL) return 0;
453 return checkifexecutable(pth);
456 searchpath = getenv("PATH");
457 if (searchpath == NULL) return 0;
458 if (strlen(searchpath) <= 0) return 0;
460 string env_path(searchpath);
465 end = strchr(beg, ':');
468 strncpy(pth, beg, PATH_MAX);
471 strncpy(pth, beg, end - beg);
472 pth[end - beg] = '\0';
475 if (pth[len - 1] != '/') strncat(pth, "/", 1);
476 strncat(pth, exe, PATH_MAX - len);
477 found = checkifexecutable(pth);
478 if (!stop) beg = end + 1;
479 } while (!stop && !found);
486 //=============================================================================
487 //! load a new component class
489 * CORBA method: load a new component class (Python or C++ implementation)
490 * \param componentName like COMPONENT
491 * try to make a Python import of COMPONENT,
492 * then a lib open of libCOMPONENTEngine.so
493 * \return true if dlopen successfull or already done, false otherwise
495 //=============================================================================
498 Engines_Container_i::load_component_Library(const char* componentName)
501 string aCompName = componentName;
503 // --- try dlopen C++ component
506 string impl_name = string ("lib") + aCompName + string("Engine.so");
508 string impl_name = aCompName + string("Engine.dll");
512 _numInstanceMutex.lock(); // lock to be alone
513 // (see decInstanceCnt, finalize_removal))
514 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
515 if (_library_map.count(impl_name) != 0)
517 MESSAGE("Library " << impl_name << " already loaded");
518 _numInstanceMutex.unlock();
524 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
527 handle = LoadLibrary( impl_name.c_str() );
532 _library_map[impl_name] = handle;
533 _numInstanceMutex.unlock();
536 _numInstanceMutex.unlock();
538 // --- try import Python component
540 INFOS("try import Python component "<<componentName);
541 if (_isSupervContainer)
543 INFOS("Supervision Container does not support Python Component Engines");
546 if (_library_map.count(aCompName) != 0)
548 return true; // Python Component, already imported
552 Py_ACQUIRE_NEW_THREAD;
553 PyObject *mainmod = PyImport_AddModule("__main__");
554 PyObject *globals = PyModule_GetDict(mainmod);
555 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
556 PyObject *result = PyObject_CallMethod(pyCont,
557 (char*)"import_component",
558 (char*)"s",componentName);
559 int ret= PyInt_AsLong(result);
562 Py_RELEASE_NEW_THREAD;
564 if (ret) // import possible: Python component
566 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
567 _library_map[aCompName] = (void *)pyCont; // any non O value OK
568 _numInstanceMutex.unlock() ;
569 MESSAGE("import Python: "<<aCompName<<" OK");
573 // Try to find an executable
574 std::string executable=aCompName+".exe";
576 if (findpathof(path, executable))
579 INFOS( "Impossible to load component: " << componentName );
580 INFOS( "Can't load shared library: " << impl_name );
581 INFOS( "Can't import Python module: " << componentName );
582 INFOS( "Can't execute program: " << executable );
586 //=============================================================================
587 //! Create a new component instance
589 * CORBA method: Creates a new servant instance of a component.
590 * The servant registers itself to naming service and Registry.
591 * \param genericRegisterName Name of the component instance to register
592 * in Registry & Name Service (without _inst_n suffix)
593 * \param studyId 0 for multiStudy instance,
594 * study Id (>0) otherwise
595 * \return a loaded component
597 //=============================================================================
599 Engines::Component_ptr
600 Engines_Container_i::create_component_instance(const char*genericRegisterName,
605 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
606 return Engines::Component::_nil() ;
609 Engines::Component_var iobject = Engines::Component::_nil() ;
611 string aCompName = genericRegisterName;
612 if (_library_map.count(aCompName) != 0) // Python component
614 if (_isSupervContainer)
616 INFOS("Supervision Container does not support Python Component Engines");
617 return Engines::Component::_nil();
619 _numInstanceMutex.lock() ; // lock on the instance number
621 int numInstance = _numInstance ;
622 _numInstanceMutex.unlock() ;
625 sprintf( aNumI , "%d" , numInstance ) ;
626 string instanceName = aCompName + "_inst_" + aNumI ;
627 string component_registerName =
628 _containerName + "/" + instanceName;
630 Py_ACQUIRE_NEW_THREAD;
631 PyObject *mainmod = PyImport_AddModule("__main__");
632 PyObject *globals = PyModule_GetDict(mainmod);
633 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
634 PyObject *result = PyObject_CallMethod(pyCont,
635 (char*)"create_component_instance",
638 instanceName.c_str(),
640 string iors = PyString_AsString(result);
643 Py_RELEASE_NEW_THREAD;
647 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
648 iobject = Engines::Component::_narrow( obj ) ;
649 _listInstances_map[instanceName] = iobject;
651 return iobject._retn();
657 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
659 string impl_name = genericRegisterName +string("Engine.dll");
661 if (_library_map.count(impl_name) != 0) // C++ component
663 void* handle = _library_map[impl_name];
664 iobject = createInstance(genericRegisterName,
667 return iobject._retn();
670 // If it's not a Python or a C++ component try to launch a standalone component
671 // in a sub directory
672 // This component is implemented in an executable with name genericRegisterName.exe
673 // It must register itself in Naming Service. The container waits some time (10 s max)
674 // it's registration.
676 _numInstanceMutex.lock() ; // lock on the instance number
678 int numInstance = _numInstance ;
679 _numInstanceMutex.unlock() ;
682 sprintf( aNumI , "%d" , numInstance ) ;
683 string instanceName = aCompName + "_inst_" + aNumI ;
684 string component_registerName = _containerName + "/" + instanceName;
686 //check if an entry exist in naming service
687 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
688 if ( !CORBA::is_nil(nsobj) )
690 // unregister the registered component
691 _NS->Destroy_Name(component_registerName.c_str());
692 //kill or shutdown it ???
695 // first arg container ior string
696 // second arg container name
697 // third arg instance name
699 Engines::Container_var pCont= _this();
700 CORBA::String_var sior = _orb->object_to_string(pCont);
704 command+=instanceName;
706 command+=instanceName;
708 command+=genericRegisterName ;
711 command+= sior; // container ior string
713 command+=_containerName; //container name
715 command+=instanceName; //instance name
717 MESSAGE("SALOME_Container::create_component_instance command=" << command);
718 // launch component with a system call
719 int status=system(command.c_str());
723 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status -1)");
724 return Engines::Component::_nil();
727 else if (WEXITSTATUS(status) == 217)
729 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status 217)");
730 return Engines::Component::_nil();
736 CORBA::Object_var obj = CORBA::Object::_nil() ;
737 while ( CORBA::is_nil(obj) && count )
745 MESSAGE( count << ". Waiting for component " << genericRegisterName);
746 obj = _NS->Resolve(component_registerName.c_str());
749 if(CORBA::is_nil(obj))
751 MESSAGE("SALOME_Container::create_component_instance failed");
752 return Engines::Component::_nil();
756 MESSAGE("SALOME_Container::create_component_instance successful");
757 iobject=Engines::Component::_narrow(obj);
758 _listInstances_map[instanceName] = iobject;
759 return iobject._retn();
764 //=============================================================================
765 //! Find an existing (in the container) component instance
767 * CORBA method: Finds a servant instance of a component
768 * \param registeredName Name of the component in Registry or Name Service,
769 * without instance suffix number
770 * \param studyId 0 if instance is not associated to a study,
771 * >0 otherwise (== study id)
772 * \return the first instance found with same studyId
774 //=============================================================================
776 Engines::Component_ptr
777 Engines_Container_i::find_component_instance( const char* registeredName,
780 Engines::Component_var anEngine = Engines::Component::_nil();
781 map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
782 while (itm != _listInstances_map.end())
784 string instance = (*itm).first;
786 if (instance.find(registeredName) == 0)
788 anEngine = (*itm).second;
789 if (studyId == anEngine->getStudyId())
791 return anEngine._retn();
796 return anEngine._retn();
799 //=============================================================================
800 //! Find or create a new component instance
802 * CORBA method: find or create an instance of the component (servant),
803 * load a new component class (dynamic library) if required,
805 * ---- FOR COMPATIBILITY WITH 2.2 ----
807 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
809 * The servant registers itself to naming service and Registry.
810 * \param genericRegisterName Name of the component to register
811 * in Registry & Name Service
812 * \param componentName Name of the constructed library of the component
813 * \return a loaded component
815 //=============================================================================
817 Engines::Component_ptr
818 Engines_Container_i::load_impl( const char* genericRegisterName,
819 const char* componentName )
821 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
822 Engines::Component_var iobject = Engines::Component::_nil() ;
823 if (load_component_Library(genericRegisterName))
824 iobject = find_or_create_instance(genericRegisterName, impl_name);
825 return iobject._retn();
829 //=============================================================================
830 //! Remove the component instance from container
832 * CORBA method: Stops the component servant, and deletes all related objects
833 * \param component_i Component to be removed
835 //=============================================================================
837 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
839 ASSERT(! CORBA::is_nil(component_i));
840 string instanceName = component_i->instanceName() ;
841 MESSAGE("unload component " << instanceName);
842 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
843 _listInstances_map.erase(instanceName);
844 _numInstanceMutex.unlock() ;
845 component_i->destroy() ;
846 _NS->Destroy_Name(instanceName.c_str());
849 //=============================================================================
850 //! Unload component libraries from the container
852 * CORBA method: Discharges unused libraries from the container.
854 //=============================================================================
856 void Engines_Container_i::finalize_removal()
858 MESSAGE("finalize unload : dlclose");
859 _numInstanceMutex.lock(); // lock to be alone
860 // (see decInstanceCnt, load_component_Library)
861 map<string, void *>::iterator ith;
862 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
864 void *handle = (*ith).second;
865 string impl_name= (*ith).first;
870 // dlclose(handle); // SALOME unstable after ...
871 // _library_map.erase(impl_name);
874 _toRemove_map.clear();
875 _numInstanceMutex.unlock();
878 //=============================================================================
879 //! Kill the container
881 * CORBA method: Kill the container process with exit(0).
882 * To remove : never returns !
884 //=============================================================================
886 bool Engines_Container_i::Kill_impl()
888 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
889 << _containerName.c_str() << " machineName "
890 << Kernel_Utils::GetHostname().c_str());
891 INFOS("===============================================================");
892 INFOS("= REMOVE calls to Kill_impl in C++ container =");
893 INFOS("===============================================================");
899 //=============================================================================
900 //! Get or create a file reference object associated to a local file (to transfer it)
902 * CORBA method: get or create a fileRef object associated to a local file
903 * (a file on the computer on which runs the container server), which stores
904 * a list of (machine, localFileName) corresponding to copies already done.
906 * \param origFileName absolute path for a local file to copy on other
908 * \return a fileRef object associated to the file.
910 //=============================================================================
913 Engines_Container_i::createFileRef(const char* origFileName)
915 string origName(origFileName);
916 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
918 if (origName[0] != '/')
920 INFOS("path of file to copy must be an absolute path begining with '/'");
921 return Engines::fileRef::_nil();
924 if (CORBA::is_nil(_fileRef_map[origName]))
926 CORBA::Object_var obj=_poa->id_to_reference(*_id);
927 Engines::Container_var pCont = Engines::Container::_narrow(obj);
928 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
929 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
930 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
931 _fileRef_map[origName] = theFileRef;
932 _numInstanceMutex.unlock() ;
935 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
936 ASSERT(! CORBA::is_nil(theFileRef));
937 return theFileRef._retn();
940 //=============================================================================
941 //! Get a fileTransfer reference
944 * \return a reference to the fileTransfer object
946 //=============================================================================
948 Engines::fileTransfer_ptr
949 Engines_Container_i::getFileTransfer()
951 Engines::fileTransfer_var aFileTransfer
952 = Engines::fileTransfer::_duplicate(_fileTransfer);
953 return aFileTransfer._retn();
957 //! Create a Salome file
958 Engines::Salome_file_ptr
959 Engines_Container_i::createSalome_file(const char* origFileName)
961 string origName(origFileName);
962 if (CORBA::is_nil(_Salome_file_map[origName]))
964 Salome_file_i* aSalome_file = new Salome_file_i();
965 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
968 aSalome_file->setLocalFile(origFileName);
969 aSalome_file->recvFiles();
971 catch (const SALOME::SALOME_Exception& e)
973 return Engines::Salome_file::_nil();
976 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
977 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
978 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
979 _Salome_file_map[origName] = theSalome_file;
980 _numInstanceMutex.unlock() ;
983 Engines::Salome_file_ptr theSalome_file =
984 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
985 ASSERT(!CORBA::is_nil(theSalome_file));
986 return theSalome_file;
988 //=============================================================================
989 //! Finds an already existing component instance or create a new instance
991 * C++ method: Finds an already existing servant instance of a component, or
992 * create an instance.
993 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
994 * \param genericRegisterName Name of the component instance to register
995 * in Registry & Name Service,
996 * (without _inst_n suffix, like "COMPONENT")
997 * \param componentLibraryName like "libCOMPONENTEngine.so"
998 * \return a loaded component
1000 * example with names:
1001 * - aGenRegisterName = COMPONENT (= first argument)
1002 * - impl_name = libCOMPONENTEngine.so (= second argument)
1003 * - _containerName = /Containers/cli76ce/FactoryServer
1004 * - factoryName = COMPONENTEngine_factory
1005 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1006 * - instanceName = COMPONENT_inst_1
1007 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1009 //=============================================================================
1011 Engines::Component_ptr
1012 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1013 std::string componentLibraryName)
1015 string aGenRegisterName = genericRegisterName;
1016 string impl_name = componentLibraryName;
1017 if (_library_map.count(impl_name) == 0)
1019 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1020 return Engines::Component::_nil() ;
1024 // --- find a registered instance in naming service, or create
1026 void* handle = _library_map[impl_name];
1027 string component_registerBase =
1028 _containerName + "/" + aGenRegisterName;
1029 Engines::Component_var iobject = Engines::Component::_nil() ;
1032 CORBA::Object_var obj =
1033 _NS->ResolveFirst( component_registerBase.c_str());
1034 if ( CORBA::is_nil( obj ) )
1036 iobject = createInstance(genericRegisterName,
1038 0); // force multiStudy instance here !
1042 iobject = Engines::Component::_narrow( obj ) ;
1043 Engines_Component_i *servant =
1044 dynamic_cast<Engines_Component_i*>
1045 (_poa->reference_to_servant(iobject));
1047 int studyId = servant->getStudyId();
1048 ASSERT (studyId >= 0);
1049 if (studyId == 0) // multiStudy instance, OK
1052 MESSAGE(component_registerBase.c_str()<<" already bound");
1054 else // monoStudy instance: NOK
1056 iobject = Engines::Component::_nil();
1057 INFOS("load_impl & find_component_instance methods "
1058 << "NOT SUITABLE for mono study components");
1064 INFOS( "Container_i::load_impl catched" ) ;
1066 return iobject._retn();
1070 //=============================================================================
1071 //! Create a new component instance
1073 * C++ method: create a servant instance of a component.
1074 * \param genericRegisterName Name of the component instance to register
1075 * in Registry & Name Service,
1076 * (without _inst_n suffix, like "COMPONENT")
1077 * \param handle loaded library handle
1078 * \param studyId 0 for multiStudy instance,
1079 * study Id (>0) otherwise
1080 * \return a loaded component
1082 * example with names:
1083 * - aGenRegisterName = COMPONENT (= first argument)
1084 * - _containerName = /Containers/cli76ce/FactoryServer
1085 * - factoryName = COMPONENTEngine_factory
1086 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1087 * - instanceName = COMPONENT_inst_1
1088 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1090 //=============================================================================
1092 Engines::Component_ptr
1093 Engines_Container_i::createInstance(std::string genericRegisterName,
1097 // --- find the factory
1099 string aGenRegisterName = genericRegisterName;
1100 string factory_name = aGenRegisterName + string("Engine_factory");
1101 SCRUTE(factory_name) ;
1103 typedef PortableServer::ObjectId * (*FACTORY_FUNCTION)
1105 PortableServer::POA_ptr,
1106 PortableServer::ObjectId *,
1111 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1113 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1116 if ( !Component_factory )
1118 INFOS( "Can't resolve symbol: " + factory_name );
1120 SCRUTE( dlerror() );
1122 return Engines::Component::_nil() ;
1125 // --- create instance
1127 Engines::Component_var iobject = Engines::Component::_nil() ;
1131 _numInstanceMutex.lock() ; // lock on the instance number
1133 int numInstance = _numInstance ;
1134 _numInstanceMutex.unlock() ;
1137 sprintf( aNumI , "%d" , numInstance ) ;
1138 string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1139 string component_registerName =
1140 _containerName + "/" + instanceName;
1142 // --- Instanciate required CORBA object
1144 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1145 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1146 aGenRegisterName.c_str() ) ;
1148 return iobject._retn();
1150 // --- get reference & servant from id
1152 CORBA::Object_var obj = _poa->id_to_reference(*id);
1153 iobject = Engines::Component::_narrow( obj ) ;
1155 Engines_Component_i *servant =
1156 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1158 //SCRUTE(servant->pd_refCount);
1159 servant->_remove_ref(); // compensate previous id_to_reference
1160 //SCRUTE(servant->pd_refCount);
1161 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1162 _listInstances_map[instanceName] = iobject;
1163 _cntInstances_map[aGenRegisterName] += 1;
1164 _numInstanceMutex.unlock() ;
1165 SCRUTE(aGenRegisterName);
1166 SCRUTE(_cntInstances_map[aGenRegisterName]);
1167 //SCRUTE(servant->pd_refCount);
1168 #if defined(_DEBUG_) || defined(_DEBUG)
1169 bool ret_studyId = servant->setStudyId(studyId);
1170 ASSERT(ret_studyId);
1172 servant->setStudyId(studyId);
1175 // --- register the engine under the name
1176 // containerName(.dir)/instanceName(.object)
1178 _NS->Register( iobject , component_registerName.c_str() ) ;
1179 MESSAGE( component_registerName.c_str() << " bound" ) ;
1183 INFOS( "Container_i::createInstance exception catched" ) ;
1185 return iobject._retn();
1188 //=============================================================================
1189 //! Decrement component instance reference count
1193 //=============================================================================
1195 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1197 if(_cntInstances_map.count(genericRegisterName)==0)
1199 string aGenRegisterName =genericRegisterName;
1200 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1201 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1202 _numInstanceMutex.lock(); // lock to be alone
1203 // (see finalize_removal, load_component_Library)
1204 _cntInstances_map[aGenRegisterName] -= 1;
1205 SCRUTE(_cntInstances_map[aGenRegisterName]);
1206 if (_cntInstances_map[aGenRegisterName] == 0)
1209 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1211 void* handle = _library_map[impl_name];
1213 _toRemove_map[impl_name] = handle;
1215 _numInstanceMutex.unlock();
1218 //=============================================================================
1219 //! Indicate if container is a python one
1221 * Retrieves only with container naming convention if it is a python container
1223 //=============================================================================
1225 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1228 int len=strlen(ContainerName);
1230 if(strcmp(ContainerName+len-2,"Py")==0)
1235 //=============================================================================
1239 //=============================================================================
1241 void ActSigIntHandler()
1244 struct sigaction SigIntAct ;
1245 SigIntAct.sa_sigaction = &SigIntHandler ;
1246 SigIntAct.sa_flags = SA_SIGINFO ;
1249 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1250 // (SIGINT | SIGUSR1) :
1251 // it must be only one signal ===> one call for SIGINT
1252 // and an other one for SIGUSR1
1255 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1257 perror("SALOME_Container main ") ;
1260 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1262 perror("SALOME_Container main ") ;
1265 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1267 perror("SALOME_Container main ") ;
1271 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1272 // use of streams (and so on) should never be used because :
1273 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1274 // A stream operation may be interrupted by a signal and if the Handler use stream we
1275 // may have a "Dead-Lock" ===HangUp
1276 //==INFOS is commented
1277 // INFOS(pthread_self() << "SigIntHandler activated") ;
1280 signal( SIGINT, SigIntHandler );
1281 signal( SIGUSR1, SigIntHandler );
1287 void CallCancelThread() ;
1290 void SigIntHandler(int what ,
1291 siginfo_t * siginfo ,
1294 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1295 // use of streams (and so on) should never be used because :
1296 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1297 // A stream operation may be interrupted by a signal and if the Handler use stream we
1298 // may have a "Dead-Lock" ===HangUp
1299 //==MESSAGE is commented
1300 // MESSAGE(pthread_self() << "SigIntHandler what " << what << endl
1301 // << " si_signo " << siginfo->si_signo << endl
1302 // << " si_code " << siginfo->si_code << endl
1303 // << " si_pid " << siginfo->si_pid) ;
1308 // MESSAGE("SigIntHandler END sleeping.") ;
1313 ActSigIntHandler() ;
1314 if ( siginfo->si_signo == SIGUSR1 )
1318 else if ( siginfo->si_signo == SIGUSR2 )
1320 CallCancelThread() ;
1325 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1332 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1338 void SigIntHandler( int what )
1341 MESSAGE( pthread_self() << "SigIntHandler what " << what << endl );
1343 MESSAGE( "SigIntHandler what " << what << endl );
1348 MESSAGE("SigIntHandler END sleeping.") ;
1353 ActSigIntHandler() ;
1354 if ( what == SIGUSR1 )
1361 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1368 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;