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 () :
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)
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()");
237 //=============================================================================
238 //! Get container name
240 * CORBA attribute: Container name (see constructor)
242 //=============================================================================
244 char* Engines_Container_i::name()
246 return CORBA::string_dup(_containerName.c_str()) ;
249 //=============================================================================
250 //! Get container working directory
252 * CORBA attribute: Container working directory
254 //=============================================================================
256 char* Engines_Container_i::workingdir()
260 return CORBA::string_dup(wd) ;
263 //=============================================================================
264 //! Get container log file name
266 * CORBA attribute: Container log file name
268 //=============================================================================
270 char* Engines_Container_i::logfilename()
272 return CORBA::string_dup(_logfilename.c_str()) ;
275 //! Set container log file name
276 void Engines_Container_i::logfilename(const char* name)
281 //=============================================================================
282 //! Get container host name
284 * CORBA method: Get the hostName of the Container (without domain extensions)
286 //=============================================================================
288 char* Engines_Container_i::getHostName()
290 string s = Kernel_Utils::GetHostname();
291 // MESSAGE("Engines_Container_i::getHostName " << s);
292 return CORBA::string_dup(s.c_str()) ;
295 //=============================================================================
296 //! Get container PID
298 * CORBA method: Get the PID (process identification) of the Container
300 //=============================================================================
302 CORBA::Long Engines_Container_i::getPID()
304 return (CORBA::Long)getpid();
307 //=============================================================================
308 //! Ping the servant to check it is still alive
310 * CORBA method: check if servant is still alive
312 //=============================================================================
314 void Engines_Container_i::ping()
316 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
319 //=============================================================================
320 //! Shutdown the container
322 * CORBA method, oneway: Server shutdown.
323 * - Container name removed from naming service,
324 * - servant deactivation,
325 * - orb shutdown if no other servants in the process
327 //=============================================================================
329 void Engines_Container_i::Shutdown()
331 MESSAGE("Engines_Container_i::Shutdown()");
333 /* For each component contained in this container
334 * tell it to self-destroy
336 std::map<std::string, Engines::Component_var>::iterator itm;
337 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
341 itm->second->destroy();
343 catch(const CORBA::Exception& e)
345 // ignore this entry and continue
349 // ignore this entry and continue
353 _NS->Destroy_FullDirectory(_containerName.c_str());
354 _NS->Destroy_Name(_containerName.c_str());
356 //_poa->deactivate_object(*_id);
357 if(_isServantAloneInProcess)
359 MESSAGE("Effective Shutdown of container Begins...");
360 if(!CORBA::is_nil(_orb))
365 /* int checkifexecutable(const char *filename)
367 * Return non-zero if the name is an executable file, and
368 * zero if it is not executable, or if it does not exist.
371 int checkifexecutable(const string& filename)
374 struct stat statinfo;
376 result = stat(filename.c_str(), &statinfo);
377 if (result < 0) return 0;
378 if (!S_ISREG(statinfo.st_mode)) return 0;
383 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
384 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
385 return statinfo.st_mode & S_IXOTH;
390 /* int findpathof(char *pth, const char *exe)
392 * Find executable by searching the PATH environment variable.
394 * const char *exe - executable name to search for.
395 * char *pth - the path found is stored here, space
396 * needs to be available.
398 * If a path is found, returns non-zero, and the path is stored
399 * in pth. If exe is not found returns 0, with pth undefined.
402 int findpathof(string& pth, const string& exe)
404 string path( getenv("PATH") );
405 if ( path.size() == 0 )
425 while(!stop && !found)
427 int pos = path.find( path_spr, offset );
428 if (pos == string::npos)
431 pth = path.substr( offset, pos - offset );
432 if ( pth.size() > 0 )
434 if( pth[pth.size()-1] != dir_spr )
437 found = checkifexecutable(pth.c_str());
448 if (strchr(exe, separator) != NULL) {
450 if (realpath(exe, pth) == NULL) return 0;
452 return checkifexecutable(pth);
455 searchpath = getenv("PATH");
456 if (searchpath == NULL) return 0;
457 if (strlen(searchpath) <= 0) return 0;
459 string env_path(searchpath);
464 end = strchr(beg, ':');
467 strncpy(pth, beg, PATH_MAX);
470 strncpy(pth, beg, end - beg);
471 pth[end - beg] = '\0';
474 if (pth[len - 1] != '/') strncat(pth, "/", 1);
475 strncat(pth, exe, PATH_MAX - len);
476 found = checkifexecutable(pth);
477 if (!stop) beg = end + 1;
478 } while (!stop && !found);
485 //=============================================================================
486 //! load a new component class
488 * CORBA method: load a new component class (Python or C++ implementation)
489 * \param componentName like COMPONENT
490 * try to make a Python import of COMPONENT,
491 * then a lib open of libCOMPONENTEngine.so
492 * \return true if dlopen successfull or already done, false otherwise
494 //=============================================================================
497 Engines_Container_i::load_component_Library(const char* componentName)
500 string aCompName = componentName;
502 // --- try dlopen C++ component
505 string impl_name = string ("lib") + aCompName + string("Engine.so");
507 string impl_name = aCompName + string("Engine.dll");
511 _numInstanceMutex.lock(); // lock to be alone
512 // (see decInstanceCnt, finalize_removal))
513 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
514 if (_library_map.count(impl_name) != 0)
516 MESSAGE("Library " << impl_name << " already loaded");
517 _numInstanceMutex.unlock();
523 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
526 handle = LoadLibrary( impl_name.c_str() );
531 _library_map[impl_name] = handle;
532 _numInstanceMutex.unlock();
535 _numInstanceMutex.unlock();
537 // --- try import Python component
539 INFOS("try import Python component "<<componentName);
540 if (_isSupervContainer)
542 INFOS("Supervision Container does not support Python Component Engines");
545 if (_library_map.count(aCompName) != 0)
547 return true; // Python Component, already imported
551 Py_ACQUIRE_NEW_THREAD;
552 PyObject *mainmod = PyImport_AddModule("__main__");
553 PyObject *globals = PyModule_GetDict(mainmod);
554 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
555 PyObject *result = PyObject_CallMethod(pyCont,
556 (char*)"import_component",
557 (char*)"s",componentName);
558 int ret= PyInt_AsLong(result);
561 Py_RELEASE_NEW_THREAD;
563 if (ret) // import possible: Python component
565 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
566 _library_map[aCompName] = (void *)pyCont; // any non O value OK
567 _numInstanceMutex.unlock() ;
568 MESSAGE("import Python: "<<aCompName<<" OK");
572 // Try to find an executable
573 std::string executable=aCompName+".exe";
575 if (findpathof(path, executable))
578 INFOS( "Impossible to load component: " << componentName );
579 INFOS( "Can't load shared library: " << impl_name );
580 INFOS( "Can't import Python module: " << componentName );
581 INFOS( "Can't execute program: " << executable );
585 //=============================================================================
586 //! Create a new component instance
588 * CORBA method: Creates a new servant instance of a component.
589 * The servant registers itself to naming service and Registry.
590 * \param genericRegisterName Name of the component instance to register
591 * in Registry & Name Service (without _inst_n suffix)
592 * \param studyId 0 for multiStudy instance,
593 * study Id (>0) otherwise
594 * \return a loaded component
596 //=============================================================================
598 Engines::Component_ptr
599 Engines_Container_i::create_component_instance(const char*genericRegisterName,
604 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
605 return Engines::Component::_nil() ;
608 Engines::Component_var iobject = Engines::Component::_nil() ;
610 string aCompName = genericRegisterName;
611 if (_library_map.count(aCompName) != 0) // Python component
613 if (_isSupervContainer)
615 INFOS("Supervision Container does not support Python Component Engines");
616 return Engines::Component::_nil();
618 _numInstanceMutex.lock() ; // lock on the instance number
620 int numInstance = _numInstance ;
621 _numInstanceMutex.unlock() ;
624 sprintf( aNumI , "%d" , numInstance ) ;
625 string instanceName = aCompName + "_inst_" + aNumI ;
626 string component_registerName =
627 _containerName + "/" + instanceName;
629 Py_ACQUIRE_NEW_THREAD;
630 PyObject *mainmod = PyImport_AddModule("__main__");
631 PyObject *globals = PyModule_GetDict(mainmod);
632 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
633 PyObject *result = PyObject_CallMethod(pyCont,
634 (char*)"create_component_instance",
637 instanceName.c_str(),
639 string iors = PyString_AsString(result);
642 Py_RELEASE_NEW_THREAD;
646 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
647 iobject = Engines::Component::_narrow( obj ) ;
648 _listInstances_map[instanceName] = iobject;
650 return iobject._retn();
656 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
658 string impl_name = genericRegisterName +string("Engine.dll");
660 if (_library_map.count(impl_name) != 0) // C++ component
662 void* handle = _library_map[impl_name];
663 iobject = createInstance(genericRegisterName,
666 return iobject._retn();
669 // If it's not a Python or a C++ component try to launch a standalone component
670 // in a sub directory
671 // This component is implemented in an executable with name genericRegisterName.exe
672 // It must register itself in Naming Service. The container waits some time (10 s max)
673 // it's registration.
675 _numInstanceMutex.lock() ; // lock on the instance number
677 int numInstance = _numInstance ;
678 _numInstanceMutex.unlock() ;
681 sprintf( aNumI , "%d" , numInstance ) ;
682 string instanceName = aCompName + "_inst_" + aNumI ;
683 string component_registerName = _containerName + "/" + instanceName;
685 //check if an entry exist in naming service
686 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
687 if ( !CORBA::is_nil(nsobj) )
689 // unregister the registered component
690 _NS->Destroy_Name(component_registerName.c_str());
691 //kill or shutdown it ???
694 // first arg container ior string
695 // second arg container name
696 // third arg instance name
698 Engines::Container_var pCont= _this();
699 CORBA::String_var sior = _orb->object_to_string(pCont);
703 command+=instanceName;
705 command+=instanceName;
707 command+=genericRegisterName ;
710 command+= sior; // container ior string
712 command+=_containerName; //container name
714 command+=instanceName; //instance name
716 MESSAGE("SALOME_Container::create_component_instance command=" << command);
717 // launch component with a system call
718 int status=system(command.c_str());
722 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status -1)");
723 return Engines::Component::_nil();
726 else if (WEXITSTATUS(status) == 217)
728 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status 217)");
729 return Engines::Component::_nil();
735 CORBA::Object_var obj = CORBA::Object::_nil() ;
736 while ( CORBA::is_nil(obj) && count )
744 MESSAGE( count << ". Waiting for component " << genericRegisterName);
745 obj = _NS->Resolve(component_registerName.c_str());
748 if(CORBA::is_nil(obj))
750 MESSAGE("SALOME_Container::create_component_instance failed");
751 return Engines::Component::_nil();
755 MESSAGE("SALOME_Container::create_component_instance successful");
756 iobject=Engines::Component::_narrow(obj);
757 _listInstances_map[instanceName] = iobject;
758 return iobject._retn();
763 //=============================================================================
764 //! Find an existing (in the container) component instance
766 * CORBA method: Finds a servant instance of a component
767 * \param registeredName Name of the component in Registry or Name Service,
768 * without instance suffix number
769 * \param studyId 0 if instance is not associated to a study,
770 * >0 otherwise (== study id)
771 * \return the first instance found with same studyId
773 //=============================================================================
775 Engines::Component_ptr
776 Engines_Container_i::find_component_instance( const char* registeredName,
779 Engines::Component_var anEngine = Engines::Component::_nil();
780 map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
781 while (itm != _listInstances_map.end())
783 string instance = (*itm).first;
785 if (instance.find(registeredName) == 0)
787 anEngine = (*itm).second;
788 if (studyId == anEngine->getStudyId())
790 return anEngine._retn();
795 return anEngine._retn();
798 //=============================================================================
799 //! Find or create a new component instance
801 * CORBA method: find or create an instance of the component (servant),
802 * load a new component class (dynamic library) if required,
804 * ---- FOR COMPATIBILITY WITH 2.2 ----
806 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
808 * The servant registers itself to naming service and Registry.
809 * \param genericRegisterName Name of the component to register
810 * in Registry & Name Service
811 * \param componentName Name of the constructed library of the component
812 * \return a loaded component
814 //=============================================================================
816 Engines::Component_ptr
817 Engines_Container_i::load_impl( const char* genericRegisterName,
818 const char* componentName )
820 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
821 Engines::Component_var iobject = Engines::Component::_nil() ;
822 if (load_component_Library(genericRegisterName))
823 iobject = find_or_create_instance(genericRegisterName, impl_name);
824 return iobject._retn();
828 //=============================================================================
829 //! Remove the component instance from container
831 * CORBA method: Stops the component servant, and deletes all related objects
832 * \param component_i Component to be removed
834 //=============================================================================
836 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
838 ASSERT(! CORBA::is_nil(component_i));
839 string instanceName = component_i->instanceName() ;
840 MESSAGE("unload component " << instanceName);
841 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
842 _listInstances_map.erase(instanceName);
843 _numInstanceMutex.unlock() ;
844 component_i->destroy() ;
845 _NS->Destroy_Name(instanceName.c_str());
848 //=============================================================================
849 //! Unload component libraries from the container
851 * CORBA method: Discharges unused libraries from the container.
853 //=============================================================================
855 void Engines_Container_i::finalize_removal()
857 MESSAGE("finalize unload : dlclose");
858 _numInstanceMutex.lock(); // lock to be alone
859 // (see decInstanceCnt, load_component_Library)
860 map<string, void *>::iterator ith;
861 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
863 void *handle = (*ith).second;
864 string impl_name= (*ith).first;
869 // dlclose(handle); // SALOME unstable after ...
870 // _library_map.erase(impl_name);
873 _toRemove_map.clear();
874 _numInstanceMutex.unlock();
877 //=============================================================================
878 //! Kill the container
880 * CORBA method: Kill the container process with exit(0).
881 * To remove : never returns !
883 //=============================================================================
885 bool Engines_Container_i::Kill_impl()
887 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
888 << _containerName.c_str() << " machineName "
889 << Kernel_Utils::GetHostname().c_str());
890 INFOS("===============================================================");
891 INFOS("= REMOVE calls to Kill_impl in C++ container =");
892 INFOS("===============================================================");
898 //=============================================================================
899 //! Get or create a file reference object associated to a local file (to transfer it)
901 * CORBA method: get or create a fileRef object associated to a local file
902 * (a file on the computer on which runs the container server), which stores
903 * a list of (machine, localFileName) corresponding to copies already done.
905 * \param origFileName absolute path for a local file to copy on other
907 * \return a fileRef object associated to the file.
909 //=============================================================================
912 Engines_Container_i::createFileRef(const char* origFileName)
914 string origName(origFileName);
915 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
917 if (origName[0] != '/')
919 INFOS("path of file to copy must be an absolute path begining with '/'");
920 return Engines::fileRef::_nil();
923 if (CORBA::is_nil(_fileRef_map[origName]))
925 CORBA::Object_var obj=_poa->id_to_reference(*_id);
926 Engines::Container_var pCont = Engines::Container::_narrow(obj);
927 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
928 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
929 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
930 _fileRef_map[origName] = theFileRef;
931 _numInstanceMutex.unlock() ;
934 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
935 ASSERT(! CORBA::is_nil(theFileRef));
936 return theFileRef._retn();
939 //=============================================================================
940 //! Get a fileTransfer reference
943 * \return a reference to the fileTransfer object
945 //=============================================================================
947 Engines::fileTransfer_ptr
948 Engines_Container_i::getFileTransfer()
950 Engines::fileTransfer_var aFileTransfer
951 = Engines::fileTransfer::_duplicate(_fileTransfer);
952 return aFileTransfer._retn();
956 //! Create a Salome file
957 Engines::Salome_file_ptr
958 Engines_Container_i::createSalome_file(const char* origFileName)
960 string origName(origFileName);
961 if (CORBA::is_nil(_Salome_file_map[origName]))
963 Salome_file_i* aSalome_file = new Salome_file_i();
964 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
967 aSalome_file->setLocalFile(origFileName);
968 aSalome_file->recvFiles();
970 catch (const SALOME::SALOME_Exception& e)
972 return Engines::Salome_file::_nil();
975 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
976 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
977 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
978 _Salome_file_map[origName] = theSalome_file;
979 _numInstanceMutex.unlock() ;
982 Engines::Salome_file_ptr theSalome_file =
983 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
984 ASSERT(!CORBA::is_nil(theSalome_file));
985 return theSalome_file;
987 //=============================================================================
988 //! Finds an already existing component instance or create a new instance
990 * C++ method: Finds an already existing servant instance of a component, or
991 * create an instance.
992 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
993 * \param genericRegisterName Name of the component instance to register
994 * in Registry & Name Service,
995 * (without _inst_n suffix, like "COMPONENT")
996 * \param componentLibraryName like "libCOMPONENTEngine.so"
997 * \return a loaded component
999 * example with names:
1000 * - aGenRegisterName = COMPONENT (= first argument)
1001 * - impl_name = libCOMPONENTEngine.so (= second argument)
1002 * - _containerName = /Containers/cli76ce/FactoryServer
1003 * - factoryName = COMPONENTEngine_factory
1004 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1005 * - instanceName = COMPONENT_inst_1
1006 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1008 //=============================================================================
1010 Engines::Component_ptr
1011 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1012 std::string componentLibraryName)
1014 string aGenRegisterName = genericRegisterName;
1015 string impl_name = componentLibraryName;
1016 if (_library_map.count(impl_name) == 0)
1018 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1019 return Engines::Component::_nil() ;
1023 // --- find a registered instance in naming service, or create
1025 void* handle = _library_map[impl_name];
1026 string component_registerBase =
1027 _containerName + "/" + aGenRegisterName;
1028 Engines::Component_var iobject = Engines::Component::_nil() ;
1031 CORBA::Object_var obj =
1032 _NS->ResolveFirst( component_registerBase.c_str());
1033 if ( CORBA::is_nil( obj ) )
1035 iobject = createInstance(genericRegisterName,
1037 0); // force multiStudy instance here !
1041 iobject = Engines::Component::_narrow( obj ) ;
1042 Engines_Component_i *servant =
1043 dynamic_cast<Engines_Component_i*>
1044 (_poa->reference_to_servant(iobject));
1046 int studyId = servant->getStudyId();
1047 ASSERT (studyId >= 0);
1048 if (studyId == 0) // multiStudy instance, OK
1051 MESSAGE(component_registerBase.c_str()<<" already bound");
1053 else // monoStudy instance: NOK
1055 iobject = Engines::Component::_nil();
1056 INFOS("load_impl & find_component_instance methods "
1057 << "NOT SUITABLE for mono study components");
1063 INFOS( "Container_i::load_impl catched" ) ;
1065 return iobject._retn();
1069 //=============================================================================
1070 //! Create a new component instance
1072 * C++ method: create a servant instance of a component.
1073 * \param genericRegisterName Name of the component instance to register
1074 * in Registry & Name Service,
1075 * (without _inst_n suffix, like "COMPONENT")
1076 * \param handle loaded library handle
1077 * \param studyId 0 for multiStudy instance,
1078 * study Id (>0) otherwise
1079 * \return a loaded component
1081 * example with names:
1082 * - aGenRegisterName = COMPONENT (= first argument)
1083 * - _containerName = /Containers/cli76ce/FactoryServer
1084 * - factoryName = COMPONENTEngine_factory
1085 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1086 * - instanceName = COMPONENT_inst_1
1087 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1089 //=============================================================================
1091 Engines::Component_ptr
1092 Engines_Container_i::createInstance(std::string genericRegisterName,
1096 // --- find the factory
1098 string aGenRegisterName = genericRegisterName;
1099 string factory_name = aGenRegisterName + string("Engine_factory");
1100 SCRUTE(factory_name) ;
1102 typedef PortableServer::ObjectId * (*FACTORY_FUNCTION)
1104 PortableServer::POA_ptr,
1105 PortableServer::ObjectId *,
1110 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1112 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1115 if ( !Component_factory )
1117 INFOS( "Can't resolve symbol: " + factory_name );
1119 SCRUTE( dlerror() );
1121 return Engines::Component::_nil() ;
1124 // --- create instance
1126 Engines::Component_var iobject = Engines::Component::_nil() ;
1130 _numInstanceMutex.lock() ; // lock on the instance number
1132 int numInstance = _numInstance ;
1133 _numInstanceMutex.unlock() ;
1136 sprintf( aNumI , "%d" , numInstance ) ;
1137 string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1138 string component_registerName =
1139 _containerName + "/" + instanceName;
1141 // --- Instanciate required CORBA object
1143 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1144 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1145 aGenRegisterName.c_str() ) ;
1147 return iobject._retn();
1149 // --- get reference & servant from id
1151 CORBA::Object_var obj = _poa->id_to_reference(*id);
1152 iobject = Engines::Component::_narrow( obj ) ;
1154 Engines_Component_i *servant =
1155 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1157 //SCRUTE(servant->pd_refCount);
1158 servant->_remove_ref(); // compensate previous id_to_reference
1159 //SCRUTE(servant->pd_refCount);
1160 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1161 _listInstances_map[instanceName] = iobject;
1162 _cntInstances_map[aGenRegisterName] += 1;
1163 _numInstanceMutex.unlock() ;
1164 SCRUTE(aGenRegisterName);
1165 SCRUTE(_cntInstances_map[aGenRegisterName]);
1166 //SCRUTE(servant->pd_refCount);
1167 #if defined(_DEBUG_) || defined(_DEBUG)
1168 bool ret_studyId = servant->setStudyId(studyId);
1169 ASSERT(ret_studyId);
1171 servant->setStudyId(studyId);
1174 // --- register the engine under the name
1175 // containerName(.dir)/instanceName(.object)
1177 _NS->Register( iobject , component_registerName.c_str() ) ;
1178 MESSAGE( component_registerName.c_str() << " bound" ) ;
1182 INFOS( "Container_i::createInstance exception catched" ) ;
1184 return iobject._retn();
1187 //=============================================================================
1188 //! Decrement component instance reference count
1192 //=============================================================================
1194 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1196 if(_cntInstances_map.count(genericRegisterName)==0)
1198 string aGenRegisterName =genericRegisterName;
1199 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1200 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1201 _numInstanceMutex.lock(); // lock to be alone
1202 // (see finalize_removal, load_component_Library)
1203 _cntInstances_map[aGenRegisterName] -= 1;
1204 SCRUTE(_cntInstances_map[aGenRegisterName]);
1205 if (_cntInstances_map[aGenRegisterName] == 0)
1208 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1210 void* handle = _library_map[impl_name];
1212 _toRemove_map[impl_name] = handle;
1214 _numInstanceMutex.unlock();
1217 //=============================================================================
1218 //! Indicate if container is a python one
1220 * Retrieves only with container naming convention if it is a python container
1222 //=============================================================================
1224 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1227 int len=strlen(ContainerName);
1229 if(strcmp(ContainerName+len-2,"Py")==0)
1234 //=============================================================================
1238 //=============================================================================
1240 void ActSigIntHandler()
1243 struct sigaction SigIntAct ;
1244 SigIntAct.sa_sigaction = &SigIntHandler ;
1245 SigIntAct.sa_flags = SA_SIGINFO ;
1248 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1249 // (SIGINT | SIGUSR1) :
1250 // it must be only one signal ===> one call for SIGINT
1251 // and an other one for SIGUSR1
1254 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1256 perror("SALOME_Container main ") ;
1259 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1261 perror("SALOME_Container main ") ;
1264 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1266 perror("SALOME_Container main ") ;
1270 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1271 // use of streams (and so on) should never be used because :
1272 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1273 // A stream operation may be interrupted by a signal and if the Handler use stream we
1274 // may have a "Dead-Lock" ===HangUp
1275 //==INFOS is commented
1276 // INFOS(pthread_self() << "SigIntHandler activated") ;
1279 signal( SIGINT, SigIntHandler );
1280 signal( SIGUSR1, SigIntHandler );
1286 void CallCancelThread() ;
1289 void SigIntHandler(int what ,
1290 siginfo_t * siginfo ,
1293 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1294 // use of streams (and so on) should never be used because :
1295 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1296 // A stream operation may be interrupted by a signal and if the Handler use stream we
1297 // may have a "Dead-Lock" ===HangUp
1298 //==MESSAGE is commented
1299 // MESSAGE(pthread_self() << "SigIntHandler what " << what << endl
1300 // << " si_signo " << siginfo->si_signo << endl
1301 // << " si_code " << siginfo->si_code << endl
1302 // << " si_pid " << siginfo->si_pid) ;
1307 // MESSAGE("SigIntHandler END sleeping.") ;
1312 ActSigIntHandler() ;
1313 if ( siginfo->si_signo == SIGUSR1 )
1317 else if ( siginfo->si_signo == SIGUSR2 )
1319 CallCancelThread() ;
1324 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1331 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1337 void SigIntHandler( int what )
1340 MESSAGE( pthread_self() << "SigIntHandler what " << what << endl );
1342 MESSAGE( "SigIntHandler what " << what << endl );
1347 MESSAGE("SigIntHandler END sleeping.") ;
1352 ActSigIntHandler() ;
1353 if ( what == SIGUSR1 )
1360 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1367 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;