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 return iobject._retn();
686 //=============================================================================
688 * CORBA method: Finds a servant instance of a component
689 * \param registeredName Name of the component in Registry or Name Service,
690 * without instance suffix number
691 * \param studyId 0 if instance is not associated to a study,
692 * >0 otherwise (== study id)
693 * \return the first instance found with same studyId
695 //=============================================================================
697 Engines::Component_ptr
698 Engines_Container_i::find_component_instance( const char* registeredName,
701 Engines::Component_var anEngine = Engines::Component::_nil();
702 map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
703 while (itm != _listInstances_map.end())
705 string instance = (*itm).first;
707 if (instance.find(registeredName) == 0)
709 anEngine = (*itm).second;
710 if (studyId == anEngine->getStudyId())
712 return anEngine._retn();
717 return anEngine._retn();
720 //=============================================================================
722 * CORBA method: find or create an instance of the component (servant),
723 * load a new component class (dynamic library) if required,
724 * ---- FOR COMPATIBILITY WITH 2.2 ----
725 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
726 * The servant registers itself to naming service and Registry.
727 * \param genericRegisterName Name of the component to register
728 * in Registry & Name Service
729 * \param componentName Name of the constructed library of the component
730 * \return a loaded component
732 //=============================================================================
734 Engines::Component_ptr
735 Engines_Container_i::load_impl( const char* genericRegisterName,
736 const char* componentName )
738 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
739 Engines::Component_var iobject = Engines::Component::_nil() ;
740 if (load_component_Library(genericRegisterName))
741 iobject = find_or_create_instance(genericRegisterName, impl_name);
742 return iobject._retn();
746 //=============================================================================
748 * CORBA method: Stops the component servant, and deletes all related objects
749 * \param component_i Component to be removed
751 //=============================================================================
753 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
755 ASSERT(! CORBA::is_nil(component_i));
756 string instanceName = component_i->instanceName() ;
757 MESSAGE("unload component " << instanceName);
758 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
759 _listInstances_map.erase(instanceName);
760 _numInstanceMutex.unlock() ;
761 component_i->destroy() ;
762 _NS->Destroy_Name(instanceName.c_str());
765 //=============================================================================
767 * CORBA method: Discharges unused libraries from the container.
769 //=============================================================================
771 void Engines_Container_i::finalize_removal()
773 MESSAGE("finalize unload : dlclose");
774 _numInstanceMutex.lock(); // lock to be alone
775 // (see decInstanceCnt, load_component_Library)
776 map<string, void *>::iterator ith;
777 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
779 void *handle = (*ith).second;
780 string impl_name= (*ith).first;
785 // dlclose(handle); // SALOME unstable after ...
786 // _library_map.erase(impl_name);
789 _toRemove_map.clear();
790 _numInstanceMutex.unlock();
793 //=============================================================================
795 * CORBA method: Kill the container process with exit(0).
796 * To remove : never returns !
798 //=============================================================================
800 bool Engines_Container_i::Kill_impl()
802 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
803 << _containerName.c_str() << " machineName "
804 << GetHostname().c_str());
805 INFOS("===============================================================");
806 INFOS("= REMOVE calls to Kill_impl in C++ container =");
807 INFOS("===============================================================");
813 //=============================================================================
815 * CORBA method: get or create a fileRef object associated to a local file
816 * (a file on the computer on which runs the container server), which stores
817 * a list of (machine, localFileName) corresponding to copies already done.
819 * \param origFileName absolute path for a local file to copy on other
821 * \return a fileRef object associated to the file.
823 //=============================================================================
826 Engines_Container_i::createFileRef(const char* origFileName)
828 string origName(origFileName);
829 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
831 if (origName[0] != '/')
833 INFOS("path of file to copy must be an absolute path begining with '/'");
834 return Engines::fileRef::_nil();
837 if (CORBA::is_nil(_fileRef_map[origName]))
839 CORBA::Object_var obj=_poa->id_to_reference(*_id);
840 Engines::Container_var pCont = Engines::Container::_narrow(obj);
841 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
842 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
843 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
844 _fileRef_map[origName] = theFileRef;
845 _numInstanceMutex.unlock() ;
848 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
849 ASSERT(! CORBA::is_nil(theFileRef));
850 return theFileRef._retn();
853 //=============================================================================
856 * \return a reference to the fileTransfer object
858 //=============================================================================
860 Engines::fileTransfer_ptr
861 Engines_Container_i::getFileTransfer()
863 Engines::fileTransfer_var aFileTransfer
864 = Engines::fileTransfer::_duplicate(_fileTransfer);
865 return aFileTransfer._retn();
869 Engines::Salome_file_ptr
870 Engines_Container_i::createSalome_file(const char* origFileName)
872 string origName(origFileName);
873 if (CORBA::is_nil(_Salome_file_map[origName]))
875 Salome_file_i* aSalome_file = new Salome_file_i();
876 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
879 aSalome_file->setLocalFile(origFileName);
880 aSalome_file->recvFiles();
882 catch (const SALOME::SALOME_Exception& e)
884 return Engines::Salome_file::_nil();
887 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
888 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
889 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
890 _Salome_file_map[origName] = theSalome_file;
891 _numInstanceMutex.unlock() ;
894 Engines::Salome_file_ptr theSalome_file =
895 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
896 ASSERT(!CORBA::is_nil(theSalome_file));
897 return theSalome_file;
899 //=============================================================================
901 * C++ method: Finds an already existing servant instance of a component, or
902 * create an instance.
903 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
904 * \param genericRegisterName Name of the component instance to register
905 * in Registry & Name Service,
906 * (without _inst_n suffix, like "COMPONENT")
907 * \param componentLibraryName like "libCOMPONENTEngine.so"
908 * \return a loaded component
910 * example with names:
911 * aGenRegisterName = COMPONENT (= first argument)
912 * impl_name = libCOMPONENTEngine.so (= second argument)
913 * _containerName = /Containers/cli76ce/FactoryServer
914 * factoryName = COMPONENTEngine_factory
915 * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
917 * instanceName = COMPONENT_inst_1
918 * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
920 //=============================================================================
922 Engines::Component_ptr
923 Engines_Container_i::find_or_create_instance(string genericRegisterName,
924 string componentLibraryName)
926 string aGenRegisterName = genericRegisterName;
927 string impl_name = componentLibraryName;
928 if (_library_map.count(impl_name) == 0)
930 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
931 return Engines::Component::_nil() ;
935 // --- find a registered instance in naming service, or create
937 void* handle = _library_map[impl_name];
938 string component_registerBase =
939 _containerName + "/" + aGenRegisterName;
940 Engines::Component_var iobject = Engines::Component::_nil() ;
943 CORBA::Object_var obj =
944 _NS->ResolveFirst( component_registerBase.c_str());
945 if ( CORBA::is_nil( obj ) )
947 iobject = createInstance(genericRegisterName,
949 0); // force multiStudy instance here !
953 iobject = Engines::Component::_narrow( obj ) ;
954 Engines_Component_i *servant =
955 dynamic_cast<Engines_Component_i*>
956 (_poa->reference_to_servant(iobject));
958 int studyId = servant->getStudyId();
959 ASSERT (studyId >= 0);
960 if (studyId == 0) // multiStudy instance, OK
963 MESSAGE(component_registerBase.c_str()<<" already bound");
965 else // monoStudy instance: NOK
967 iobject = Engines::Component::_nil();
968 INFOS("load_impl & find_component_instance methods "
969 << "NOT SUITABLE for mono study components");
975 INFOS( "Container_i::load_impl catched" ) ;
977 return iobject._retn();
981 //=============================================================================
983 * C++ method: create a servant instance of a component.
984 * \param genericRegisterName Name of the component instance to register
985 * in Registry & Name Service,
986 * (without _inst_n suffix, like "COMPONENT")
987 * \param handle loaded library handle
988 * \param studyId 0 for multiStudy instance,
989 * study Id (>0) otherwise
990 * \return a loaded component
992 * example with names:
993 * aGenRegisterName = COMPONENT (= first argument)
994 * _containerName = /Containers/cli76ce/FactoryServer
995 * factoryName = COMPONENTEngine_factory
996 * component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
997 * instanceName = COMPONENT_inst_1
998 * component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1000 //=============================================================================
1002 Engines::Component_ptr
1003 Engines_Container_i::createInstance(string genericRegisterName,
1007 // --- find the factory
1009 string aGenRegisterName = genericRegisterName;
1010 string factory_name = aGenRegisterName + string("Engine_factory");
1011 SCRUTE(factory_name) ;
1013 typedef PortableServer::ObjectId * (*FACTORY_FUNCTION)
1015 PortableServer::POA_ptr,
1016 PortableServer::ObjectId *,
1021 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1023 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1026 if ( !Component_factory )
1028 INFOS( "Can't resolve symbol: " + factory_name );
1030 SCRUTE( dlerror() );
1032 return Engines::Component::_nil() ;
1035 // --- create instance
1037 Engines::Component_var iobject = Engines::Component::_nil() ;
1041 _numInstanceMutex.lock() ; // lock on the instance number
1043 int numInstance = _numInstance ;
1044 _numInstanceMutex.unlock() ;
1047 sprintf( aNumI , "%d" , numInstance ) ;
1048 string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1049 string component_registerName =
1050 _containerName + "/" + instanceName;
1052 // --- Instanciate required CORBA object
1054 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1055 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1056 aGenRegisterName.c_str() ) ;
1058 return iobject._retn();
1060 // --- get reference & servant from id
1062 CORBA::Object_var obj = _poa->id_to_reference(*id);
1063 iobject = Engines::Component::_narrow( obj ) ;
1065 Engines_Component_i *servant =
1066 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1068 //SCRUTE(servant->pd_refCount);
1069 servant->_remove_ref(); // compensate previous id_to_reference
1070 //SCRUTE(servant->pd_refCount);
1071 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1072 _listInstances_map[instanceName] = iobject;
1073 _cntInstances_map[aGenRegisterName] += 1;
1074 _numInstanceMutex.unlock() ;
1075 SCRUTE(aGenRegisterName);
1076 SCRUTE(_cntInstances_map[aGenRegisterName]);
1077 //SCRUTE(servant->pd_refCount);
1078 bool ret_studyId = servant->setStudyId(studyId);
1079 ASSERT(ret_studyId);
1081 // --- register the engine under the name
1082 // containerName(.dir)/instanceName(.object)
1084 _NS->Register( iobject , component_registerName.c_str() ) ;
1085 MESSAGE( component_registerName.c_str() << " bound" ) ;
1089 INFOS( "Container_i::createInstance exception catched" ) ;
1091 return iobject._retn();
1094 //=============================================================================
1098 //=============================================================================
1100 void Engines_Container_i::decInstanceCnt(string genericRegisterName)
1102 if(_cntInstances_map.count(genericRegisterName)==0)
1104 string aGenRegisterName =genericRegisterName;
1105 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1106 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1107 _numInstanceMutex.lock(); // lock to be alone
1108 // (see finalize_removal, load_component_Library)
1109 _cntInstances_map[aGenRegisterName] -= 1;
1110 SCRUTE(_cntInstances_map[aGenRegisterName]);
1111 if (_cntInstances_map[aGenRegisterName] == 0)
1114 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1116 void* handle = _library_map[impl_name];
1118 _toRemove_map[impl_name] = handle;
1120 _numInstanceMutex.unlock();
1123 //=============================================================================
1125 * Retrieves only with container naming convention if it is a python container
1127 //=============================================================================
1129 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1132 int len=strlen(ContainerName);
1134 if(strcmp(ContainerName+len-2,"Py")==0)
1139 //=============================================================================
1143 //=============================================================================
1145 void ActSigIntHandler()
1148 struct sigaction SigIntAct ;
1149 SigIntAct.sa_sigaction = &SigIntHandler ;
1150 SigIntAct.sa_flags = SA_SIGINFO ;
1153 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1154 // (SIGINT | SIGUSR1) :
1155 // it must be only one signal ===> one call for SIGINT
1156 // and an other one for SIGUSR1
1159 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1161 perror("SALOME_Container main ") ;
1164 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1166 perror("SALOME_Container main ") ;
1169 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1171 perror("SALOME_Container main ") ;
1175 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1176 // use of streams (and so on) should never be used because :
1177 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1178 // A stream operation may be interrupted by a signal and if the Handler use stream we
1179 // may have a "Dead-Lock" ===HangUp
1180 //==INFOS is commented
1181 // INFOS(pthread_self() << "SigIntHandler activated") ;
1184 signal( SIGINT, SigIntHandler );
1185 signal( SIGUSR1, SigIntHandler );
1191 void CallCancelThread() ;
1194 void SigIntHandler(int what ,
1195 siginfo_t * siginfo ,
1198 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1199 // use of streams (and so on) should never be used because :
1200 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1201 // A stream operation may be interrupted by a signal and if the Handler use stream we
1202 // may have a "Dead-Lock" ===HangUp
1203 //==MESSAGE is commented
1204 // MESSAGE(pthread_self() << "SigIntHandler what " << what << endl
1205 // << " si_signo " << siginfo->si_signo << endl
1206 // << " si_code " << siginfo->si_code << endl
1207 // << " si_pid " << siginfo->si_pid) ;
1212 // MESSAGE("SigIntHandler END sleeping.") ;
1217 ActSigIntHandler() ;
1218 if ( siginfo->si_signo == SIGUSR1 )
1222 else if ( siginfo->si_signo == SIGUSR2 )
1224 CallCancelThread() ;
1229 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1236 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1242 void SigIntHandler( int what )
1245 MESSAGE( pthread_self() << "SigIntHandler what " << what << endl );
1247 MESSAGE( "SigIntHandler what " << what << endl );
1252 MESSAGE("SigIntHandler END sleeping.") ;
1257 ActSigIntHandler() ;
1258 if ( what == SIGUSR1 )
1265 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1272 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;