1 // SALOME Container : implementation of container and engine for Kernel
3 // Copyright (C) 2003 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
24 // File : Container_i.cxx
25 // Author : Paul RASCLE, EDF - MARC TAJCHMAN, CEA
29 //#define private public
43 #include "utilities.h"
44 #include <SALOMEconfig.h>
46 #include CORBA_SERVER_HEADER(SALOME_Component)
47 #include CORBA_SERVER_HEADER(SALOME_Exception)
49 //#include <SALOME_Component.hh>
51 #include <pthread.h> // must be before Python.h !
52 #include "SALOME_Container_i.hxx"
53 #include "SALOME_Component_i.hxx"
54 #include "SALOME_FileRef_i.hxx"
55 #include "SALOME_FileTransfer_i.hxx"
56 #include "Salome_file_i.hxx"
57 #include "SALOME_NamingService.hxx"
61 #include "Container_init_python.hxx"
65 bool _Sleeping = false ;
67 // // Needed by multi-threaded Python --- Supervision
72 // Containers with name FactoryServer are started via rsh in LifeCycleCORBA
73 // Other Containers are started via start_impl of FactoryServer
75 extern "C" {void ActSigIntHandler() ; }
77 extern "C" {void SigIntHandler(int, siginfo_t *, void *) ; }
79 extern "C" {void SigIntHandler( int ) ; }
83 map<std::string, int> Engines_Container_i::_cntInstances_map;
84 map<std::string, void *> Engines_Container_i::_library_map;
85 map<std::string, void *> Engines_Container_i::_toRemove_map;
86 omni_mutex Engines_Container_i::_numInstanceMutex ;
88 //=============================================================================
90 * Default constructor, not for use
92 //=============================================================================
94 Engines_Container_i::Engines_Container_i () :
99 //=============================================================================
103 //=============================================================================
105 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
106 PortableServer::POA_ptr poa,
107 char *containerName ,
108 int argc , char* argv[],
110 bool isServantAloneInProcess
112 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess)
114 _pid = (long)getpid();
122 string hostname = GetHostname();
124 MESSAGE(hostname << " " << getpid() <<
125 " Engines_Container_i starting argc " <<
126 _argc << " Thread " << pthread_self() ) ;
128 MESSAGE(hostname << " " << _getpid() <<
129 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
135 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
141 INFOS("SALOME_Container usage : SALOME_Container ServerName");
145 _isSupervContainer = false;
146 if (strcmp(argv[1],"SuperVisionContainer") == 0) _isSupervContainer = true;
148 if (_isSupervContainer)
154 _orb = CORBA::ORB::_duplicate(orb) ;
155 _poa = PortableServer::POA::_duplicate(poa) ;
157 // Pour les containers paralleles: il ne faut pas enregistrer et activer
158 // le container generique, mais le container specialise
162 _id = _poa->activate_object(this);
163 _NS = new SALOME_NamingService();
164 _NS->init_orb( _orb ) ;
165 CORBA::Object_var obj=_poa->id_to_reference(*_id);
166 Engines::Container_var pCont
167 = Engines::Container::_narrow(obj);
170 _containerName = _NS->BuildContainerNameForNS(containerName,
172 SCRUTE(_containerName);
173 _NS->Register(pCont, _containerName.c_str());
174 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
178 // import SALOME_Container
179 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
181 CORBA::String_var sior = _orb->object_to_string(pCont);
182 string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
183 myCommand += _containerName + "','";
188 if (!_isSupervContainer)
192 PyEval_AcquireLock();
193 PyThreadState *myTstate = PyThreadState_New(KERNEL_PYTHON::_interp);
194 PyThreadState *myoldTstate = PyThreadState_Swap(myTstate);
196 Py_ACQUIRE_NEW_THREAD;
200 // mpv: this is temporary solution: there is a unregular crash if not
203 // first element is the path to Registry.dll, but it's wrong
204 PyRun_SimpleString("import sys\n");
205 PyRun_SimpleString("sys.path = sys.path[1:]\n");
207 PyRun_SimpleString("import SALOME_Container\n");
208 PyRun_SimpleString((char*)myCommand.c_str());
209 Py_RELEASE_NEW_THREAD;
212 fileTransfer_i* aFileTransfer = new fileTransfer_i();
213 CORBA::Object_var obref=aFileTransfer->_this();
214 _fileTransfer = Engines::fileTransfer::_narrow(obref);
215 aFileTransfer->_remove_ref();
219 //=============================================================================
223 //=============================================================================
225 Engines_Container_i::~Engines_Container_i()
227 MESSAGE("Container_i::~Container_i()");
233 //=============================================================================
235 * CORBA attribute: Container name (see constructor)
237 //=============================================================================
239 char* Engines_Container_i::name()
241 return CORBA::string_dup(_containerName.c_str()) ;
244 //=============================================================================
246 * CORBA attribute: Container working directory
248 //=============================================================================
250 char* Engines_Container_i::workingdir()
254 return CORBA::string_dup(wd) ;
257 //=============================================================================
259 * CORBA attribute: Container log file name
261 //=============================================================================
263 char* Engines_Container_i::logfilename()
265 return CORBA::string_dup(_logfilename.c_str()) ;
268 void Engines_Container_i::logfilename(const char* name)
273 //=============================================================================
275 * CORBA method: Get the hostName of the Container (without domain extensions)
277 //=============================================================================
279 char* Engines_Container_i::getHostName()
281 string s = GetHostname();
282 // MESSAGE("Engines_Container_i::getHostName " << s);
283 return CORBA::string_dup(s.c_str()) ;
286 //=============================================================================
288 * CORBA method: Get the PID (process identification) of the Container
290 //=============================================================================
292 CORBA::Long Engines_Container_i::getPID()
294 return (CORBA::Long)getpid();
297 //=============================================================================
299 * CORBA method: check if servant is still alive
301 //=============================================================================
303 void Engines_Container_i::ping()
305 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
308 //=============================================================================
310 * CORBA method, oneway: Server shutdown.
311 * - Container name removed from naming service,
312 * - servant deactivation,
313 * - orb shutdown if no other servants in the process
315 //=============================================================================
317 void Engines_Container_i::Shutdown()
319 MESSAGE("Engines_Container_i::Shutdown()");
321 /* For each component contained in this container
322 * tell it to self-destroy
324 std::map<std::string, Engines::Component_var>::iterator itm;
325 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
326 itm->second->destroy();
328 _NS->Destroy_FullDirectory(_containerName.c_str());
329 _NS->Destroy_Name(_containerName.c_str());
331 //_poa->deactivate_object(*_id);
332 if(_isServantAloneInProcess)
334 MESSAGE("Effective Shutdown of container Begins...");
335 if(!CORBA::is_nil(_orb))
340 /* int checkifexecutable(const char *filename)
342 * Return non-zero if the name is an executable file, and
343 * zero if it is not executable, or if it does not exist.
346 int checkifexecutable(const char *filename)
349 struct stat statinfo;
351 result = stat(filename, &statinfo);
352 if (result < 0) return 0;
353 if (!S_ISREG(statinfo.st_mode)) return 0;
355 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
356 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
357 return statinfo.st_mode & S_IXOTH;
361 /* int findpathof(char *pth, const char *exe)
363 * Find executable by searching the PATH environment variable.
365 * const char *exe - executable name to search for.
366 * char *pth - the path found is stored here, space
367 * needs to be available.
369 * If a path is found, returns non-zero, and the path is stored
370 * in pth. If exe is not found returns 0, with pth undefined.
373 int findpathof(char *pth, const char *exe)
380 if (strchr(exe, '/') != NULL) {
381 if (realpath(exe, pth) == NULL) return 0;
382 return checkifexecutable(pth);
385 searchpath = getenv("PATH");
386 if (searchpath == NULL) return 0;
387 if (strlen(searchpath) <= 0) return 0;
392 end = strchr(beg, ':');
395 strncpy(pth, beg, PATH_MAX);
398 strncpy(pth, beg, end - beg);
399 pth[end - beg] = '\0';
402 if (pth[len - 1] != '/') strncat(pth, "/", 1);
403 strncat(pth, exe, PATH_MAX - len);
404 found = checkifexecutable(pth);
405 if (!stop) beg = end + 1;
406 } while (!stop && !found);
413 //=============================================================================
415 * CORBA method: load a new component class (Python or C++ implementation)
416 * \param componentName like COMPONENT
417 * try to make a Python import of COMPONENT,
418 * then a lib open of libCOMPONENTEngine.so
419 * \return true if dlopen successfull or already done, false otherwise
421 //=============================================================================
424 Engines_Container_i::load_component_Library(const char* componentName)
427 string aCompName = componentName;
429 // --- try dlopen C++ component
432 string impl_name = string ("lib") + aCompName + string("Engine.so");
434 string impl_name = aCompName + string("Engine.dll");
438 _numInstanceMutex.lock(); // lock to be alone
439 // (see decInstanceCnt, finalize_removal))
440 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
441 if (_library_map.count(impl_name) != 0)
443 MESSAGE("Library " << impl_name << " already loaded");
444 _numInstanceMutex.unlock();
450 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
453 handle = LoadLibrary( impl_name.c_str() );
458 _library_map[impl_name] = handle;
459 _numInstanceMutex.unlock();
462 _numInstanceMutex.unlock();
464 // --- try import Python component
466 INFOS("try import Python component "<<componentName);
467 if (_isSupervContainer)
469 INFOS("Supervision Container does not support Python Component Engines");
472 if (_library_map.count(aCompName) != 0)
474 return true; // Python Component, already imported
478 Py_ACQUIRE_NEW_THREAD;
479 PyObject *mainmod = PyImport_AddModule("__main__");
480 PyObject *globals = PyModule_GetDict(mainmod);
481 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
482 PyObject *result = PyObject_CallMethod(pyCont,
485 int ret= PyInt_AsLong(result);
488 Py_RELEASE_NEW_THREAD;
490 if (ret) // import possible: Python component
492 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
493 _library_map[aCompName] = (void *)pyCont; // any non O value OK
494 _numInstanceMutex.unlock() ;
495 MESSAGE("import Python: "<<aCompName<<" OK");
499 // Try to find an executable
500 std::string executable=aCompName+".exe";
501 char path[PATH_MAX+1];
502 if (findpathof(path, executable.c_str()))
505 INFOS( "Impossible to load component: " << componentName );
506 INFOS( "Can't load shared library: " << impl_name );
507 INFOS( "Can't import Python module: " << componentName );
508 INFOS( "Can't execute program: " << executable );
512 //=============================================================================
514 * CORBA method: Creates a new servant instance of a component.
515 * The servant registers itself to naming service and Registry.
516 * \param genericRegisterName Name of the component instance to register
517 * in Registry & Name Service (without _inst_n suffix)
518 * \param studyId 0 for multiStudy instance,
519 * study Id (>0) otherwise
520 * \return a loaded component
522 //=============================================================================
524 Engines::Component_ptr
525 Engines_Container_i::create_component_instance(const char*genericRegisterName,
530 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
531 return Engines::Component::_nil() ;
534 Engines::Component_var iobject = Engines::Component::_nil() ;
536 string aCompName = genericRegisterName;
537 if (_library_map.count(aCompName) != 0) // Python component
539 if (_isSupervContainer)
541 INFOS("Supervision Container does not support Python Component Engines");
542 return Engines::Component::_nil();
544 _numInstanceMutex.lock() ; // lock on the instance number
546 int numInstance = _numInstance ;
547 _numInstanceMutex.unlock() ;
550 sprintf( aNumI , "%d" , numInstance ) ;
551 string instanceName = aCompName + "_inst_" + aNumI ;
552 string component_registerName =
553 _containerName + "/" + instanceName;
555 Py_ACQUIRE_NEW_THREAD;
556 PyObject *mainmod = PyImport_AddModule("__main__");
557 PyObject *globals = PyModule_GetDict(mainmod);
558 PyObject *pyCont = PyDict_GetItemString(globals, "pyCont");
559 PyObject *result = PyObject_CallMethod(pyCont,
560 "create_component_instance",
563 instanceName.c_str(),
565 string iors = PyString_AsString(result);
568 Py_RELEASE_NEW_THREAD;
572 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
573 iobject = Engines::Component::_narrow( obj ) ;
574 _listInstances_map[instanceName] = iobject;
576 return iobject._retn();
582 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
584 string impl_name = genericRegisterName +string("Engine.dll");
586 if (_library_map.count(impl_name) != 0) // C++ component
588 void* handle = _library_map[impl_name];
589 iobject = createInstance(genericRegisterName,
592 return iobject._retn();
595 // If it's not a Python or a C++ component try to launch a standalone component
596 // in a sub directory
597 // This component is implemented in an executable with name genericRegisterName.exe
598 // It must register itself in Naming Service. The container waits some time (10 s max)
599 // it's registration.
601 _numInstanceMutex.lock() ; // lock on the instance number
603 int numInstance = _numInstance ;
604 _numInstanceMutex.unlock() ;
607 sprintf( aNumI , "%d" , numInstance ) ;
608 string instanceName = aCompName + "_inst_" + aNumI ;
609 string component_registerName = _containerName + "/" + instanceName;
611 //check if an entry exist in naming service
612 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
613 if ( !CORBA::is_nil(nsobj) )
615 // unregister the registered component
616 _NS->Destroy_Name(component_registerName.c_str());
617 //kill or shutdown it ???
620 // first arg container ior string
621 // second arg container name
622 // third arg instance name
624 Engines::Container_var pCont= _this();
625 CORBA::String_var sior = _orb->object_to_string(pCont);
629 command+=instanceName;
631 command+=instanceName;
633 command+=genericRegisterName ;
636 command+= sior; // container ior string
638 command+=_containerName; //container name
640 command+=instanceName; //instance name
642 MESSAGE("SALOME_Container::create_component_instance command=" << command);
643 // launch component with a system call
644 int status=system(command.c_str());
648 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status -1)");
649 return Engines::Component::_nil();
651 else if (WEXITSTATUS(status) == 217)
653 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status 217)");
654 return Engines::Component::_nil();
659 CORBA::Object_var obj = CORBA::Object::_nil() ;
660 while ( CORBA::is_nil(obj) && count )
668 MESSAGE( count << ". Waiting for component " << genericRegisterName);
669 obj = _NS->Resolve(component_registerName.c_str());
672 if(CORBA::is_nil(obj))
674 MESSAGE("SALOME_Container::create_component_instance failed");
675 return Engines::Component::_nil();
679 MESSAGE("SALOME_Container::create_component_instance successful");
680 iobject=Engines::Component::_narrow(obj);
681 _listInstances_map[instanceName] = iobject;
682 return iobject._retn();
687 //=============================================================================
689 * CORBA method: Finds a servant instance of a component
690 * \param registeredName Name of the component in Registry or Name Service,
691 * without instance suffix number
692 * \param studyId 0 if instance is not associated to a study,
693 * >0 otherwise (== study id)
694 * \return the first instance found with same studyId
696 //=============================================================================
698 Engines::Component_ptr
699 Engines_Container_i::find_component_instance( const char* registeredName,
702 Engines::Component_var anEngine = Engines::Component::_nil();
703 map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
704 while (itm != _listInstances_map.end())
706 string instance = (*itm).first;
708 if (instance.find(registeredName) == 0)
710 anEngine = (*itm).second;
711 if (studyId == anEngine->getStudyId())
713 return anEngine._retn();
718 return anEngine._retn();
721 //=============================================================================
723 * CORBA method: find or create an instance of the component (servant),
724 * load a new component class (dynamic library) if required,
725 * ---- FOR COMPATIBILITY WITH 2.2 ----
726 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
727 * The servant registers itself to naming service and Registry.
728 * \param genericRegisterName Name of the component to register
729 * in Registry & Name Service
730 * \param componentName Name of the constructed library of the component
731 * \return a loaded component
733 //=============================================================================
735 Engines::Component_ptr
736 Engines_Container_i::load_impl( const char* genericRegisterName,
737 const char* componentName )
739 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
740 Engines::Component_var iobject = Engines::Component::_nil() ;
741 if (load_component_Library(genericRegisterName))
742 iobject = find_or_create_instance(genericRegisterName, impl_name);
743 return iobject._retn();
747 //=============================================================================
749 * CORBA method: Stops the component servant, and deletes all related objects
750 * \param component_i Component to be removed
752 //=============================================================================
754 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
756 ASSERT(! CORBA::is_nil(component_i));
757 string instanceName = component_i->instanceName() ;
758 MESSAGE("unload component " << instanceName);
759 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
760 _listInstances_map.erase(instanceName);
761 _numInstanceMutex.unlock() ;
762 component_i->destroy() ;
763 _NS->Destroy_Name(instanceName.c_str());
766 //=============================================================================
768 * CORBA method: Discharges unused libraries from the container.
770 //=============================================================================
772 void Engines_Container_i::finalize_removal()
774 MESSAGE("finalize unload : dlclose");
775 _numInstanceMutex.lock(); // lock to be alone
776 // (see decInstanceCnt, load_component_Library)
777 map<string, void *>::iterator ith;
778 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
780 void *handle = (*ith).second;
781 string impl_name= (*ith).first;
786 // dlclose(handle); // SALOME unstable after ...
787 // _library_map.erase(impl_name);
790 _toRemove_map.clear();
791 _numInstanceMutex.unlock();
794 //=============================================================================
796 * CORBA method: Kill the container process with exit(0).
797 * To remove : never returns !
799 //=============================================================================
801 bool Engines_Container_i::Kill_impl()
803 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
804 << _containerName.c_str() << " machineName "
805 << GetHostname().c_str());
806 INFOS("===============================================================");
807 INFOS("= REMOVE calls to Kill_impl in C++ container =");
808 INFOS("===============================================================");
814 //=============================================================================
816 * CORBA method: get or create a fileRef object associated to a local file
817 * (a file on the computer on which runs the container server), which stores
818 * a list of (machine, localFileName) corresponding to copies already done.
820 * \param origFileName absolute path for a local file to copy on other
822 * \return a fileRef object associated to the file.
824 //=============================================================================
827 Engines_Container_i::createFileRef(const char* origFileName)
829 string origName(origFileName);
830 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
832 if (origName[0] != '/')
834 INFOS("path of file to copy must be an absolute path begining with '/'");
835 return Engines::fileRef::_nil();
838 if (CORBA::is_nil(_fileRef_map[origName]))
840 CORBA::Object_var obj=_poa->id_to_reference(*_id);
841 Engines::Container_var pCont = Engines::Container::_narrow(obj);
842 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
843 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
844 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
845 _fileRef_map[origName] = theFileRef;
846 _numInstanceMutex.unlock() ;
849 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
850 ASSERT(! CORBA::is_nil(theFileRef));
851 return theFileRef._retn();
854 //=============================================================================
857 * \return a reference to the fileTransfer object
859 //=============================================================================
861 Engines::fileTransfer_ptr
862 Engines_Container_i::getFileTransfer()
864 Engines::fileTransfer_var aFileTransfer
865 = Engines::fileTransfer::_duplicate(_fileTransfer);
866 return aFileTransfer._retn();
870 Engines::Salome_file_ptr
871 Engines_Container_i::createSalome_file(const char* origFileName)
873 string origName(origFileName);
874 if (CORBA::is_nil(_Salome_file_map[origName]))
876 Salome_file_i* aSalome_file = new Salome_file_i();
877 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
880 aSalome_file->setLocalFile(origFileName);
881 aSalome_file->recvFiles();
883 catch (const SALOME::SALOME_Exception& e)
885 return Engines::Salome_file::_nil();
888 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
889 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
890 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
891 _Salome_file_map[origName] = theSalome_file;
892 _numInstanceMutex.unlock() ;
895 Engines::Salome_file_ptr theSalome_file =
896 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
897 ASSERT(!CORBA::is_nil(theSalome_file));
898 return theSalome_file;
900 //=============================================================================
902 * C++ method: Finds an already existing servant instance of a component, or
903 * create an instance.
904 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
905 * \param genericRegisterName Name of the component instance to register
906 * in Registry & Name Service,
907 * (without _inst_n suffix, like "COMPONENT")
908 * \param componentLibraryName like "libCOMPONENTEngine.so"
909 * \return a loaded component
911 * example with names:
912 * aGenRegisterName = COMPONENT (= first argument)
913 * impl_name = libCOMPONENTEngine.so (= second argument)
914 * _containerName = /Containers/cli76ce/FactoryServer
915 * factoryName = COMPONENTEngine_factory
916 * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
918 * instanceName = COMPONENT_inst_1
919 * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
921 //=============================================================================
923 Engines::Component_ptr
924 Engines_Container_i::find_or_create_instance(string genericRegisterName,
925 string componentLibraryName)
927 string aGenRegisterName = genericRegisterName;
928 string impl_name = componentLibraryName;
929 if (_library_map.count(impl_name) == 0)
931 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
932 return Engines::Component::_nil() ;
936 // --- find a registered instance in naming service, or create
938 void* handle = _library_map[impl_name];
939 string component_registerBase =
940 _containerName + "/" + aGenRegisterName;
941 Engines::Component_var iobject = Engines::Component::_nil() ;
944 CORBA::Object_var obj =
945 _NS->ResolveFirst( component_registerBase.c_str());
946 if ( CORBA::is_nil( obj ) )
948 iobject = createInstance(genericRegisterName,
950 0); // force multiStudy instance here !
954 iobject = Engines::Component::_narrow( obj ) ;
955 Engines_Component_i *servant =
956 dynamic_cast<Engines_Component_i*>
957 (_poa->reference_to_servant(iobject));
959 int studyId = servant->getStudyId();
960 ASSERT (studyId >= 0);
961 if (studyId == 0) // multiStudy instance, OK
964 MESSAGE(component_registerBase.c_str()<<" already bound");
966 else // monoStudy instance: NOK
968 iobject = Engines::Component::_nil();
969 INFOS("load_impl & find_component_instance methods "
970 << "NOT SUITABLE for mono study components");
976 INFOS( "Container_i::load_impl catched" ) ;
978 return iobject._retn();
982 //=============================================================================
984 * C++ method: create a servant instance of a component.
985 * \param genericRegisterName Name of the component instance to register
986 * in Registry & Name Service,
987 * (without _inst_n suffix, like "COMPONENT")
988 * \param handle loaded library handle
989 * \param studyId 0 for multiStudy instance,
990 * study Id (>0) otherwise
991 * \return a loaded component
993 * example with names:
994 * aGenRegisterName = COMPONENT (= first argument)
995 * _containerName = /Containers/cli76ce/FactoryServer
996 * factoryName = COMPONENTEngine_factory
997 * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
998 * instanceName = COMPONENT_inst_1
999 * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1001 //=============================================================================
1003 Engines::Component_ptr
1004 Engines_Container_i::createInstance(string genericRegisterName,
1008 // --- find the factory
1010 string aGenRegisterName = genericRegisterName;
1011 string factory_name = aGenRegisterName + string("Engine_factory");
1012 SCRUTE(factory_name) ;
1014 typedef PortableServer::ObjectId * (*FACTORY_FUNCTION)
1016 PortableServer::POA_ptr,
1017 PortableServer::ObjectId *,
1022 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1024 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1027 if ( !Component_factory )
1029 INFOS( "Can't resolve symbol: " + factory_name );
1031 SCRUTE( dlerror() );
1033 return Engines::Component::_nil() ;
1036 // --- create instance
1038 Engines::Component_var iobject = Engines::Component::_nil() ;
1042 _numInstanceMutex.lock() ; // lock on the instance number
1044 int numInstance = _numInstance ;
1045 _numInstanceMutex.unlock() ;
1048 sprintf( aNumI , "%d" , numInstance ) ;
1049 string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1050 string component_registerName =
1051 _containerName + "/" + instanceName;
1053 // --- Instanciate required CORBA object
1055 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1056 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1057 aGenRegisterName.c_str() ) ;
1059 return iobject._retn();
1061 // --- get reference & servant from id
1063 CORBA::Object_var obj = _poa->id_to_reference(*id);
1064 iobject = Engines::Component::_narrow( obj ) ;
1066 Engines_Component_i *servant =
1067 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1069 //SCRUTE(servant->pd_refCount);
1070 servant->_remove_ref(); // compensate previous id_to_reference
1071 //SCRUTE(servant->pd_refCount);
1072 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1073 _listInstances_map[instanceName] = iobject;
1074 _cntInstances_map[aGenRegisterName] += 1;
1075 _numInstanceMutex.unlock() ;
1076 SCRUTE(aGenRegisterName);
1077 SCRUTE(_cntInstances_map[aGenRegisterName]);
1078 //SCRUTE(servant->pd_refCount);
1079 bool ret_studyId = servant->setStudyId(studyId);
1080 ASSERT(ret_studyId);
1082 // --- register the engine under the name
1083 // containerName(.dir)/instanceName(.object)
1085 _NS->Register( iobject , component_registerName.c_str() ) ;
1086 MESSAGE( component_registerName.c_str() << " bound" ) ;
1090 INFOS( "Container_i::createInstance exception catched" ) ;
1092 return iobject._retn();
1095 //=============================================================================
1099 //=============================================================================
1101 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
1103 if(_cntInstances_map.count(genericRegisterName)==0)
1105 string aGenRegisterName =genericRegisterName;
1106 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1107 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1108 _numInstanceMutex.lock(); // lock to be alone
1109 // (see finalize_removal, load_component_Library)
1110 _cntInstances_map[aGenRegisterName] -= 1;
1111 SCRUTE(_cntInstances_map[aGenRegisterName]);
1112 if (_cntInstances_map[aGenRegisterName] == 0)
1115 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1117 void* handle = _library_map[impl_name];
1119 _toRemove_map[impl_name] = handle;
1121 _numInstanceMutex.unlock();
1124 //=============================================================================
1126 * Retrieves only with container naming convention if it is a python container
1128 //=============================================================================
1130 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1133 int len=strlen(ContainerName);
1135 if(strcmp(ContainerName+len-2,"Py")==0)
1140 //=============================================================================
1144 //=============================================================================
1146 void ActSigIntHandler()
1149 struct sigaction SigIntAct ;
1150 SigIntAct.sa_sigaction = &SigIntHandler ;
1151 SigIntAct.sa_flags = SA_SIGINFO ;
1154 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1155 // (SIGINT | SIGUSR1) :
1156 // it must be only one signal ===> one call for SIGINT
1157 // and an other one for SIGUSR1
1160 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1162 perror("SALOME_Container main ") ;
1165 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1167 perror("SALOME_Container main ") ;
1170 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1172 perror("SALOME_Container main ") ;
1176 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1177 // use of streams (and so on) should never be used because :
1178 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1179 // A stream operation may be interrupted by a signal and if the Handler use stream we
1180 // may have a "Dead-Lock" ===HangUp
1181 //==INFOS is commented
1182 // INFOS(pthread_self() << "SigIntHandler activated") ;
1185 signal( SIGINT, SigIntHandler );
1186 signal( SIGUSR1, SigIntHandler );
1192 void CallCancelThread() ;
1195 void SigIntHandler(int what ,
1196 siginfo_t * siginfo ,
1199 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1200 // use of streams (and so on) should never be used because :
1201 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1202 // A stream operation may be interrupted by a signal and if the Handler use stream we
1203 // may have a "Dead-Lock" ===HangUp
1204 //==MESSAGE is commented
1205 // MESSAGE(pthread_self() << "SigIntHandler what " << what << endl
1206 // << " si_signo " << siginfo->si_signo << endl
1207 // << " si_code " << siginfo->si_code << endl
1208 // << " si_pid " << siginfo->si_pid) ;
1213 // MESSAGE("SigIntHandler END sleeping.") ;
1218 ActSigIntHandler() ;
1219 if ( siginfo->si_signo == SIGUSR1 )
1223 else if ( siginfo->si_signo == SIGUSR2 )
1225 CallCancelThread() ;
1230 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1237 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1243 void SigIntHandler( int what )
1246 MESSAGE( pthread_self() << "SigIntHandler what " << what << endl );
1248 MESSAGE( "SigIntHandler what " << what << endl );
1253 MESSAGE("SigIntHandler END sleeping.") ;
1258 ActSigIntHandler() ;
1259 if ( what == SIGUSR1 )
1266 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1273 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;