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 static PyObject* _pyCont;
88 int checkifexecutable(const std::string&);
89 int findpathof(std::string&, const std::string&);
91 /*! \class Engines_Container_i
92 * \brief C++ implementation of Engines::Container interface
97 //=============================================================================
99 * Default constructor, not for use
101 //=============================================================================
103 Engines_Container_i::Engines_Container_i () :
104 _numInstance(0),_id(0),_NS(0)
108 //=============================================================================
112 //=============================================================================
114 Engines_Container_i::Engines_Container_i (CORBA::ORB_ptr orb,
115 PortableServer::POA_ptr poa,
116 char *containerName ,
117 int argc , char* argv[],
119 bool isServantAloneInProcess
121 _numInstance(0),_isServantAloneInProcess(isServantAloneInProcess),_id(0),_NS(0)
123 _pid = (long)getpid();
131 string hostname = Kernel_Utils::GetHostname();
133 MESSAGE(hostname << " " << getpid() <<
134 " Engines_Container_i starting argc " <<
135 _argc << " Thread " << pthread_self() ) ;
137 MESSAGE(hostname << " " << _getpid() <<
138 " Engines_Container_i starting argc " << _argc<< " Thread " << pthread_self().p ) ;
144 MESSAGE(" argv" << i << " " << _argv[ i ]) ;
150 INFOS("SALOME_Container usage : SALOME_Container ServerName");
154 _isSupervContainer = false;
155 if (strcmp(argv[1],"SuperVisionContainer") == 0) _isSupervContainer = true;
157 if (_isSupervContainer)
163 _orb = CORBA::ORB::_duplicate(orb) ;
164 _poa = PortableServer::POA::_duplicate(poa) ;
166 // Pour les containers paralleles: il ne faut pas enregistrer et activer
167 // le container generique, mais le container specialise
171 _id = _poa->activate_object(this);
172 _NS = new SALOME_NamingService();
173 _NS->init_orb( _orb ) ;
174 CORBA::Object_var obj=_poa->id_to_reference(*_id);
175 Engines::Container_var pCont
176 = Engines::Container::_narrow(obj);
179 _containerName = _NS->BuildContainerNameForNS(containerName,
181 SCRUTE(_containerName);
182 _NS->Register(pCont, _containerName.c_str());
183 MESSAGE("Engines_Container_i::Engines_Container_i : Container name "
187 // import SALOME_Container
188 // pycont = SALOME_Container.SALOME_Container_i(containerIORStr)
190 CORBA::String_var sior = _orb->object_to_string(pCont);
191 string myCommand="pyCont = SALOME_Container.SALOME_Container_i('";
192 myCommand += _containerName + "','";
197 if (!_isSupervContainer)
199 PyGILState_STATE gstate = PyGILState_Ensure();
202 // mpv: this is temporary solution: there is a unregular crash if not
205 // first element is the path to Registry.dll, but it's wrong
206 PyRun_SimpleString("import sys\n");
207 PyRun_SimpleString("sys.path = sys.path[1:]\n");
209 PyRun_SimpleString("import SALOME_Container\n");
210 PyRun_SimpleString((char*)myCommand.c_str());
211 PyObject *mainmod = PyImport_AddModule("__main__");
212 PyObject *globals = PyModule_GetDict(mainmod);
213 _pyCont = PyDict_GetItemString(globals, "pyCont");
215 PyGILState_Release(gstate);
218 fileTransfer_i* aFileTransfer = new fileTransfer_i();
219 CORBA::Object_var obref=aFileTransfer->_this();
220 _fileTransfer = Engines::fileTransfer::_narrow(obref);
221 aFileTransfer->_remove_ref();
225 //=============================================================================
229 //=============================================================================
231 Engines_Container_i::~Engines_Container_i()
233 MESSAGE("Container_i::~Container_i()");
240 //=============================================================================
241 //! Get container name
243 * CORBA attribute: Container name (see constructor)
245 //=============================================================================
247 char* Engines_Container_i::name()
249 return CORBA::string_dup(_containerName.c_str()) ;
252 //=============================================================================
253 //! Get container working directory
255 * CORBA attribute: Container working directory
257 //=============================================================================
259 char* Engines_Container_i::workingdir()
263 return CORBA::string_dup(wd) ;
266 //=============================================================================
267 //! Get container log file name
269 * CORBA attribute: Container log file name
271 //=============================================================================
273 char* Engines_Container_i::logfilename()
275 return CORBA::string_dup(_logfilename.c_str()) ;
278 //! Set container log file name
279 void Engines_Container_i::logfilename(const char* name)
284 //=============================================================================
285 //! Get container host name
287 * CORBA method: Get the hostName of the Container (without domain extensions)
289 //=============================================================================
291 char* Engines_Container_i::getHostName()
293 string s = Kernel_Utils::GetHostname();
294 // MESSAGE("Engines_Container_i::getHostName " << s);
295 return CORBA::string_dup(s.c_str()) ;
298 //=============================================================================
299 //! Get container PID
301 * CORBA method: Get the PID (process identification) of the Container
303 //=============================================================================
305 CORBA::Long Engines_Container_i::getPID()
307 return (CORBA::Long)getpid();
310 //=============================================================================
311 //! Ping the servant to check it is still alive
313 * CORBA method: check if servant is still alive
315 //=============================================================================
317 void Engines_Container_i::ping()
319 MESSAGE("Engines_Container_i::ping() pid "<< getpid());
322 //=============================================================================
323 //! Shutdown the container
325 * CORBA method, oneway: Server shutdown.
326 * - Container name removed from naming service,
327 * - servant deactivation,
328 * - orb shutdown if no other servants in the process
330 //=============================================================================
332 void Engines_Container_i::Shutdown()
334 MESSAGE("Engines_Container_i::Shutdown()");
336 /* For each component contained in this container
337 * tell it to self-destroy
339 std::map<std::string, Engines::Component_var>::iterator itm;
340 for (itm = _listInstances_map.begin(); itm != _listInstances_map.end(); itm++)
344 itm->second->destroy();
346 catch(const CORBA::Exception& e)
348 // ignore this entry and continue
352 // ignore this entry and continue
356 _NS->Destroy_FullDirectory(_containerName.c_str());
357 _NS->Destroy_Name(_containerName.c_str());
359 //_poa->deactivate_object(*_id);
360 if(_isServantAloneInProcess)
362 MESSAGE("Effective Shutdown of container Begins...");
363 if(!CORBA::is_nil(_orb))
368 /* int checkifexecutable(const char *filename)
370 * Return non-zero if the name is an executable file, and
371 * zero if it is not executable, or if it does not exist.
374 int checkifexecutable(const string& filename)
377 struct stat statinfo;
379 result = stat(filename.c_str(), &statinfo);
380 if (result < 0) return 0;
381 if (!S_ISREG(statinfo.st_mode)) return 0;
386 if (statinfo.st_uid == geteuid()) return statinfo.st_mode & S_IXUSR;
387 if (statinfo.st_gid == getegid()) return statinfo.st_mode & S_IXGRP;
388 return statinfo.st_mode & S_IXOTH;
393 /* int findpathof(char *pth, const char *exe)
395 * Find executable by searching the PATH environment variable.
397 * const char *exe - executable name to search for.
398 * char *pth - the path found is stored here, space
399 * needs to be available.
401 * If a path is found, returns non-zero, and the path is stored
402 * in pth. If exe is not found returns 0, with pth undefined.
405 int findpathof(string& pth, const string& exe)
407 string path( getenv("PATH") );
408 if ( path.size() == 0 )
428 while(!stop && !found)
430 int pos = path.find( path_spr, offset );
431 if (pos == string::npos)
434 pth = path.substr( offset, pos - offset );
435 if ( pth.size() > 0 )
437 if( pth[pth.size()-1] != dir_spr )
440 found = checkifexecutable(pth.c_str());
451 if (strchr(exe, separator) != NULL) {
453 if (realpath(exe, pth) == NULL) return 0;
455 return checkifexecutable(pth);
458 searchpath = getenv("PATH");
459 if (searchpath == NULL) return 0;
460 if (strlen(searchpath) <= 0) return 0;
462 string env_path(searchpath);
467 end = strchr(beg, ':');
470 strncpy(pth, beg, PATH_MAX);
473 strncpy(pth, beg, end - beg);
474 pth[end - beg] = '\0';
477 if (pth[len - 1] != '/') strncat(pth, "/", 1);
478 strncat(pth, exe, PATH_MAX - len);
479 found = checkifexecutable(pth);
480 if (!stop) beg = end + 1;
481 } while (!stop && !found);
488 //=============================================================================
489 //! load a new component class
491 * CORBA method: load a new component class (Python or C++ implementation)
492 * \param componentName like COMPONENT
493 * try to make a Python import of COMPONENT,
494 * then a lib open of libCOMPONENTEngine.so
495 * \return true if dlopen successfull or already done, false otherwise
497 //=============================================================================
500 Engines_Container_i::load_component_Library(const char* componentName)
503 string aCompName = componentName;
505 // --- try dlopen C++ component
508 string impl_name = string ("lib") + aCompName + string("Engine.so");
510 string impl_name = aCompName + string("Engine.dll");
514 _numInstanceMutex.lock(); // lock to be alone
515 // (see decInstanceCnt, finalize_removal))
516 if (_toRemove_map.count(impl_name) != 0) _toRemove_map.erase(impl_name);
517 if (_library_map.count(impl_name) != 0)
519 MESSAGE("Library " << impl_name << " already loaded");
520 _numInstanceMutex.unlock();
524 std::string retso="";
527 handle = dlopen( impl_name.c_str() , RTLD_LAZY ) ;
528 if ( !handle )retso=dlerror();
531 handle = LoadLibrary( impl_name.c_str() );
536 _library_map[impl_name] = handle;
537 _numInstanceMutex.unlock();
540 _numInstanceMutex.unlock();
542 // --- try import Python component
544 INFOS("try import Python component "<<componentName);
546 if (_isSupervContainer)
548 INFOS("Supervision Container does not support Python Component Engines");
551 if (_library_map.count(aCompName) != 0)
553 return true; // Python Component, already imported
557 PyGILState_STATE gstate = PyGILState_Ensure();
558 PyObject *result = PyObject_CallMethod(_pyCont,
559 (char*)"import_component",
560 (char*)"s",componentName);
562 retpy=PyString_AsString(result);
565 PyGILState_Release(gstate);
567 if (retpy=="") // import possible: Python component
569 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
570 _library_map[aCompName] = (void *)_pyCont; // any non O value OK
571 _numInstanceMutex.unlock() ;
572 MESSAGE("import Python: "<<aCompName<<" OK");
576 // Try to find an executable
577 std::string executable=aCompName+".exe";
579 if (findpathof(path, executable))
582 INFOS( "Impossible to load component: " << componentName );
583 INFOS( "Can't load shared library: " << impl_name );
584 std::cerr << retso << std::endl;
585 INFOS( "Can't import Python module: " << componentName );
586 std::cerr << retpy << std::endl;
587 INFOS( "Can't execute program: " << executable );
591 //=============================================================================
592 //! Create a new component instance
594 * CORBA method: Creates a new servant instance of a component.
595 * The servant registers itself to naming service and Registry.
596 * \param genericRegisterName Name of the component instance to register
597 * in Registry & Name Service (without _inst_n suffix)
598 * \param studyId 0 for multiStudy instance,
599 * study Id (>0) otherwise
600 * \return a loaded component
602 //=============================================================================
604 Engines::Component_ptr
605 Engines_Container_i::create_component_instance(const char*genericRegisterName,
610 INFOS("studyId must be > 0 for mono study instance, =0 for multiStudy");
611 return Engines::Component::_nil() ;
614 Engines::Component_var iobject = Engines::Component::_nil() ;
616 string aCompName = genericRegisterName;
617 if (_library_map.count(aCompName) != 0) // Python component
619 if (_isSupervContainer)
621 INFOS("Supervision Container does not support Python Component Engines");
622 return Engines::Component::_nil();
624 _numInstanceMutex.lock() ; // lock on the instance number
626 int numInstance = _numInstance ;
627 _numInstanceMutex.unlock() ;
630 sprintf( aNumI , "%d" , numInstance ) ;
631 string instanceName = aCompName + "_inst_" + aNumI ;
632 string component_registerName =
633 _containerName + "/" + instanceName;
635 PyGILState_STATE gstate = PyGILState_Ensure();
636 PyObject *result = PyObject_CallMethod(_pyCont,
637 (char*)"create_component_instance",
640 instanceName.c_str(),
642 string iors = PyString_AsString(result);
645 PyGILState_Release(gstate);
649 CORBA::Object_var obj = _orb->string_to_object(iors.c_str());
650 iobject = Engines::Component::_narrow( obj ) ;
651 _listInstances_map[instanceName] = iobject;
653 return iobject._retn();
659 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
661 string impl_name = genericRegisterName +string("Engine.dll");
663 if (_library_map.count(impl_name) != 0) // C++ component
665 void* handle = _library_map[impl_name];
666 iobject = createInstance(genericRegisterName,
669 return iobject._retn();
672 // If it's not a Python or a C++ component try to launch a standalone component
673 // in a sub directory
674 // This component is implemented in an executable with name genericRegisterName.exe
675 // It must register itself in Naming Service. The container waits some time (10 s max)
676 // it's registration.
678 _numInstanceMutex.lock() ; // lock on the instance number
680 int numInstance = _numInstance ;
681 _numInstanceMutex.unlock() ;
684 sprintf( aNumI , "%d" , numInstance ) ;
685 string instanceName = aCompName + "_inst_" + aNumI ;
686 string component_registerName = _containerName + "/" + instanceName;
688 //check if an entry exist in naming service
689 CORBA::Object_var nsobj = _NS->Resolve(component_registerName.c_str());
690 if ( !CORBA::is_nil(nsobj) )
692 // unregister the registered component
693 _NS->Destroy_Name(component_registerName.c_str());
694 //kill or shutdown it ???
697 // first arg container ior string
698 // second arg container name
699 // third arg instance name
701 Engines::Container_var pCont= _this();
702 CORBA::String_var sior = _orb->object_to_string(pCont);
706 command+=instanceName;
708 command+=instanceName;
710 command+=genericRegisterName ;
713 command+= sior; // container ior string
715 command+=_containerName; //container name
717 command+=instanceName; //instance name
719 MESSAGE("SALOME_Container::create_component_instance command=" << command);
720 // launch component with a system call
721 int status=system(command.c_str());
725 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status -1)");
726 return Engines::Component::_nil();
729 else if (WEXITSTATUS(status) == 217)
731 MESSAGE("SALOME_Container::create_component_instance system failed " << "(system command status 217)");
732 return Engines::Component::_nil();
738 CORBA::Object_var obj = CORBA::Object::_nil() ;
739 while ( CORBA::is_nil(obj) && count )
747 MESSAGE( count << ". Waiting for component " << genericRegisterName);
748 obj = _NS->Resolve(component_registerName.c_str());
751 if(CORBA::is_nil(obj))
753 MESSAGE("SALOME_Container::create_component_instance failed");
754 return Engines::Component::_nil();
758 MESSAGE("SALOME_Container::create_component_instance successful");
759 iobject=Engines::Component::_narrow(obj);
760 _listInstances_map[instanceName] = iobject;
761 return iobject._retn();
766 //=============================================================================
767 //! Find an existing (in the container) component instance
769 * CORBA method: Finds a servant instance of a component
770 * \param registeredName Name of the component in Registry or Name Service,
771 * without instance suffix number
772 * \param studyId 0 if instance is not associated to a study,
773 * >0 otherwise (== study id)
774 * \return the first instance found with same studyId
776 //=============================================================================
778 Engines::Component_ptr
779 Engines_Container_i::find_component_instance( const char* registeredName,
782 Engines::Component_var anEngine = Engines::Component::_nil();
783 map<string,Engines::Component_var>::iterator itm =_listInstances_map.begin();
784 while (itm != _listInstances_map.end())
786 string instance = (*itm).first;
788 if (instance.find(registeredName) == 0)
790 anEngine = (*itm).second;
791 if (studyId == anEngine->getStudyId())
793 return anEngine._retn();
798 return anEngine._retn();
801 //=============================================================================
802 //! Find or create a new component instance
804 * CORBA method: find or create an instance of the component (servant),
805 * load a new component class (dynamic library) if required,
807 * ---- FOR COMPATIBILITY WITH 2.2 ----
809 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
811 * The servant registers itself to naming service and Registry.
812 * \param genericRegisterName Name of the component to register
813 * in Registry & Name Service
814 * \param componentName Name of the constructed library of the component
815 * \return a loaded component
817 //=============================================================================
819 Engines::Component_ptr
820 Engines_Container_i::load_impl( const char* genericRegisterName,
821 const char* componentName )
823 string impl_name = string ("lib") + genericRegisterName +string("Engine.so");
824 Engines::Component_var iobject = Engines::Component::_nil() ;
825 if (load_component_Library(genericRegisterName))
826 iobject = find_or_create_instance(genericRegisterName, impl_name);
827 return iobject._retn();
831 //=============================================================================
832 //! Remove the component instance from container
834 * CORBA method: Stops the component servant, and deletes all related objects
835 * \param component_i Component to be removed
837 //=============================================================================
839 void Engines_Container_i::remove_impl(Engines::Component_ptr component_i)
841 ASSERT(! CORBA::is_nil(component_i));
842 string instanceName = component_i->instanceName() ;
843 MESSAGE("unload component " << instanceName);
844 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
845 _listInstances_map.erase(instanceName);
846 _numInstanceMutex.unlock() ;
847 component_i->destroy() ;
848 _NS->Destroy_Name(instanceName.c_str());
851 //=============================================================================
852 //! Unload component libraries from the container
854 * CORBA method: Discharges unused libraries from the container.
856 //=============================================================================
858 void Engines_Container_i::finalize_removal()
860 MESSAGE("finalize unload : dlclose");
861 _numInstanceMutex.lock(); // lock to be alone
862 // (see decInstanceCnt, load_component_Library)
863 map<string, void *>::iterator ith;
864 for (ith = _toRemove_map.begin(); ith != _toRemove_map.end(); ith++)
866 void *handle = (*ith).second;
867 string impl_name= (*ith).first;
872 // dlclose(handle); // SALOME unstable after ...
873 // _library_map.erase(impl_name);
876 _toRemove_map.clear();
877 _numInstanceMutex.unlock();
880 //=============================================================================
881 //! Kill the container
883 * CORBA method: Kill the container process with exit(0).
884 * To remove : never returns !
886 //=============================================================================
888 bool Engines_Container_i::Kill_impl()
890 MESSAGE("Engines_Container_i::Kill() pid "<< getpid() << " containerName "
891 << _containerName.c_str() << " machineName "
892 << Kernel_Utils::GetHostname().c_str());
893 INFOS("===============================================================");
894 INFOS("= REMOVE calls to Kill_impl in C++ container =");
895 INFOS("===============================================================");
901 //=============================================================================
902 //! Get or create a file reference object associated to a local file (to transfer it)
904 * CORBA method: get or create a fileRef object associated to a local file
905 * (a file on the computer on which runs the container server), which stores
906 * a list of (machine, localFileName) corresponding to copies already done.
908 * \param origFileName absolute path for a local file to copy on other
910 * \return a fileRef object associated to the file.
912 //=============================================================================
915 Engines_Container_i::createFileRef(const char* origFileName)
917 string origName(origFileName);
918 Engines::fileRef_var theFileRef = Engines::fileRef::_nil();
920 if (origName[0] != '/')
922 INFOS("path of file to copy must be an absolute path begining with '/'");
923 return Engines::fileRef::_nil();
926 if (CORBA::is_nil(_fileRef_map[origName]))
928 CORBA::Object_var obj=_poa->id_to_reference(*_id);
929 Engines::Container_var pCont = Engines::Container::_narrow(obj);
930 fileRef_i* aFileRef = new fileRef_i(pCont, origFileName);
931 theFileRef = Engines::fileRef::_narrow(aFileRef->_this());
932 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
933 _fileRef_map[origName] = theFileRef;
934 _numInstanceMutex.unlock() ;
937 theFileRef = Engines::fileRef::_duplicate(_fileRef_map[origName]);
938 ASSERT(! CORBA::is_nil(theFileRef));
939 return theFileRef._retn();
942 //=============================================================================
943 //! Get a fileTransfer reference
946 * \return a reference to the fileTransfer object
948 //=============================================================================
950 Engines::fileTransfer_ptr
951 Engines_Container_i::getFileTransfer()
953 Engines::fileTransfer_var aFileTransfer
954 = Engines::fileTransfer::_duplicate(_fileTransfer);
955 return aFileTransfer._retn();
959 //! Create a Salome file
960 Engines::Salome_file_ptr
961 Engines_Container_i::createSalome_file(const char* origFileName)
963 string origName(origFileName);
964 if (CORBA::is_nil(_Salome_file_map[origName]))
966 Salome_file_i* aSalome_file = new Salome_file_i();
967 aSalome_file->setContainer(Engines::Container::_duplicate(this->_this()));
970 aSalome_file->setLocalFile(origFileName);
971 aSalome_file->recvFiles();
973 catch (const SALOME::SALOME_Exception& e)
975 return Engines::Salome_file::_nil();
978 Engines::Salome_file_var theSalome_file = Engines::Salome_file::_nil();
979 theSalome_file = Engines::Salome_file::_narrow(aSalome_file->_this());
980 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
981 _Salome_file_map[origName] = theSalome_file;
982 _numInstanceMutex.unlock() ;
985 Engines::Salome_file_ptr theSalome_file =
986 Engines::Salome_file::_duplicate(_Salome_file_map[origName]);
987 ASSERT(!CORBA::is_nil(theSalome_file));
988 return theSalome_file;
990 //=============================================================================
991 //! Finds an already existing component instance or create a new instance
993 * C++ method: Finds an already existing servant instance of a component, or
994 * create an instance.
995 * ---- USE ONLY FOR MULTISTUDY INSTANCES ! --------
996 * \param genericRegisterName Name of the component instance to register
997 * in Registry & Name Service,
998 * (without _inst_n suffix, like "COMPONENT")
999 * \param componentLibraryName like "libCOMPONENTEngine.so"
1000 * \return a loaded component
1002 * example with names:
1003 * - aGenRegisterName = COMPONENT (= first argument)
1004 * - impl_name = libCOMPONENTEngine.so (= second argument)
1005 * - _containerName = /Containers/cli76ce/FactoryServer
1006 * - factoryName = COMPONENTEngine_factory
1007 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1008 * - instanceName = COMPONENT_inst_1
1009 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1011 //=============================================================================
1013 Engines::Component_ptr
1014 Engines_Container_i::find_or_create_instance(std::string genericRegisterName,
1015 std::string componentLibraryName)
1017 string aGenRegisterName = genericRegisterName;
1018 string impl_name = componentLibraryName;
1019 if (_library_map.count(impl_name) == 0)
1021 INFOS("shared library " << impl_name <<" must be loaded before creating instance");
1022 return Engines::Component::_nil() ;
1026 // --- find a registered instance in naming service, or create
1028 void* handle = _library_map[impl_name];
1029 string component_registerBase =
1030 _containerName + "/" + aGenRegisterName;
1031 Engines::Component_var iobject = Engines::Component::_nil() ;
1034 CORBA::Object_var obj =
1035 _NS->ResolveFirst( component_registerBase.c_str());
1036 if ( CORBA::is_nil( obj ) )
1038 iobject = createInstance(genericRegisterName,
1040 0); // force multiStudy instance here !
1044 iobject = Engines::Component::_narrow( obj ) ;
1045 Engines_Component_i *servant =
1046 dynamic_cast<Engines_Component_i*>
1047 (_poa->reference_to_servant(iobject));
1049 int studyId = servant->getStudyId();
1050 ASSERT (studyId >= 0);
1051 if (studyId == 0) // multiStudy instance, OK
1054 MESSAGE(component_registerBase.c_str()<<" already bound");
1056 else // monoStudy instance: NOK
1058 iobject = Engines::Component::_nil();
1059 INFOS("load_impl & find_component_instance methods "
1060 << "NOT SUITABLE for mono study components");
1066 INFOS( "Container_i::load_impl catched" ) ;
1068 return iobject._retn();
1072 //=============================================================================
1073 //! Create a new component instance
1075 * C++ method: create a servant instance of a component.
1076 * \param genericRegisterName Name of the component instance to register
1077 * in Registry & Name Service,
1078 * (without _inst_n suffix, like "COMPONENT")
1079 * \param handle loaded library handle
1080 * \param studyId 0 for multiStudy instance,
1081 * study Id (>0) otherwise
1082 * \return a loaded component
1084 * example with names:
1085 * - aGenRegisterName = COMPONENT (= first argument)
1086 * - _containerName = /Containers/cli76ce/FactoryServer
1087 * - factoryName = COMPONENTEngine_factory
1088 * - component_registerBase = /Containers/cli76ce/FactoryServer/COMPONENT
1089 * - instanceName = COMPONENT_inst_1
1090 * - component_registerName = /Containers/cli76ce/FactoryServer/COMPONENT_inst_1
1092 //=============================================================================
1094 Engines::Component_ptr
1095 Engines_Container_i::createInstance(std::string genericRegisterName,
1099 // --- find the factory
1101 string aGenRegisterName = genericRegisterName;
1102 string factory_name = aGenRegisterName + string("Engine_factory");
1103 SCRUTE(factory_name) ;
1105 typedef PortableServer::ObjectId * (*FACTORY_FUNCTION)
1107 PortableServer::POA_ptr,
1108 PortableServer::ObjectId *,
1113 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)dlsym( handle, factory_name.c_str() );
1115 FACTORY_FUNCTION Component_factory = (FACTORY_FUNCTION)GetProcAddress( (HINSTANCE)handle, factory_name.c_str() );
1118 if ( !Component_factory )
1120 INFOS( "Can't resolve symbol: " + factory_name );
1122 SCRUTE( dlerror() );
1124 return Engines::Component::_nil() ;
1127 // --- create instance
1129 Engines::Component_var iobject = Engines::Component::_nil() ;
1133 _numInstanceMutex.lock() ; // lock on the instance number
1135 int numInstance = _numInstance ;
1136 _numInstanceMutex.unlock() ;
1139 sprintf( aNumI , "%d" , numInstance ) ;
1140 string instanceName = aGenRegisterName + "_inst_" + aNumI ;
1141 string component_registerName =
1142 _containerName + "/" + instanceName;
1144 // --- Instanciate required CORBA object
1146 PortableServer::ObjectId *id ; //not owner, do not delete (nore use var)
1147 id = (Component_factory) ( _orb, _poa, _id, instanceName.c_str(),
1148 aGenRegisterName.c_str() ) ;
1150 return iobject._retn();
1152 // --- get reference & servant from id
1154 CORBA::Object_var obj = _poa->id_to_reference(*id);
1155 iobject = Engines::Component::_narrow( obj ) ;
1157 Engines_Component_i *servant =
1158 dynamic_cast<Engines_Component_i*>(_poa->reference_to_servant(iobject));
1160 //SCRUTE(servant->pd_refCount);
1161 servant->_remove_ref(); // compensate previous id_to_reference
1162 //SCRUTE(servant->pd_refCount);
1163 _numInstanceMutex.lock() ; // lock to be alone (stl container write)
1164 _listInstances_map[instanceName] = iobject;
1165 _cntInstances_map[aGenRegisterName] += 1;
1166 _numInstanceMutex.unlock() ;
1167 SCRUTE(aGenRegisterName);
1168 SCRUTE(_cntInstances_map[aGenRegisterName]);
1169 //SCRUTE(servant->pd_refCount);
1170 #if defined(_DEBUG_) || defined(_DEBUG)
1171 bool ret_studyId = servant->setStudyId(studyId);
1172 ASSERT(ret_studyId);
1174 servant->setStudyId(studyId);
1177 // --- register the engine under the name
1178 // containerName(.dir)/instanceName(.object)
1180 _NS->Register( iobject , component_registerName.c_str() ) ;
1181 MESSAGE( component_registerName.c_str() << " bound" ) ;
1185 INFOS( "Container_i::createInstance exception catched" ) ;
1187 return iobject._retn();
1190 //=============================================================================
1191 //! Decrement component instance reference count
1195 //=============================================================================
1197 void Engines_Container_i::decInstanceCnt(std::string genericRegisterName)
1199 if(_cntInstances_map.count(genericRegisterName)==0)
1201 string aGenRegisterName =genericRegisterName;
1202 MESSAGE("Engines_Container_i::decInstanceCnt " << aGenRegisterName);
1203 ASSERT(_cntInstances_map[aGenRegisterName] > 0);
1204 _numInstanceMutex.lock(); // lock to be alone
1205 // (see finalize_removal, load_component_Library)
1206 _cntInstances_map[aGenRegisterName] -= 1;
1207 SCRUTE(_cntInstances_map[aGenRegisterName]);
1208 if (_cntInstances_map[aGenRegisterName] == 0)
1211 Engines_Component_i::GetDynLibraryName(aGenRegisterName.c_str());
1213 void* handle = _library_map[impl_name];
1215 _toRemove_map[impl_name] = handle;
1217 _numInstanceMutex.unlock();
1220 //=============================================================================
1221 //! Indicate if container is a python one
1223 * Retrieves only with container naming convention if it is a python container
1225 //=============================================================================
1227 bool Engines_Container_i::isPythonContainer(const char* ContainerName)
1230 int len=strlen(ContainerName);
1232 if(strcmp(ContainerName+len-2,"Py")==0)
1237 //=============================================================================
1241 //=============================================================================
1243 void ActSigIntHandler()
1246 struct sigaction SigIntAct ;
1247 SigIntAct.sa_sigaction = &SigIntHandler ;
1248 SigIntAct.sa_flags = SA_SIGINFO ;
1251 // DEBUG 03.02.2005 : the first parameter of sigaction is not a mask of signals
1252 // (SIGINT | SIGUSR1) :
1253 // it must be only one signal ===> one call for SIGINT
1254 // and an other one for SIGUSR1
1257 if ( sigaction( SIGINT , &SigIntAct, NULL ) )
1259 perror("SALOME_Container main ") ;
1262 if ( sigaction( SIGUSR1 , &SigIntAct, NULL ) )
1264 perror("SALOME_Container main ") ;
1267 if ( sigaction( SIGUSR2 , &SigIntAct, NULL ) )
1269 perror("SALOME_Container main ") ;
1273 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1274 // use of streams (and so on) should never be used because :
1275 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1276 // A stream operation may be interrupted by a signal and if the Handler use stream we
1277 // may have a "Dead-Lock" ===HangUp
1278 //==INFOS is commented
1279 // INFOS(pthread_self() << "SigIntHandler activated") ;
1282 signal( SIGINT, SigIntHandler );
1283 signal( SIGUSR1, SigIntHandler );
1289 void CallCancelThread() ;
1292 void SigIntHandler(int what ,
1293 siginfo_t * siginfo ,
1296 //PAL9042 JR : during the execution of a Signal Handler (and of methods called through Signal Handlers)
1297 // use of streams (and so on) should never be used because :
1298 // streams of C++ are naturally thread-safe and use pthread_mutex_lock ===>
1299 // A stream operation may be interrupted by a signal and if the Handler use stream we
1300 // may have a "Dead-Lock" ===HangUp
1301 //==MESSAGE is commented
1302 // MESSAGE(pthread_self() << "SigIntHandler what " << what << endl
1303 // << " si_signo " << siginfo->si_signo << endl
1304 // << " si_code " << siginfo->si_code << endl
1305 // << " si_pid " << siginfo->si_pid) ;
1310 // MESSAGE("SigIntHandler END sleeping.") ;
1315 ActSigIntHandler() ;
1316 if ( siginfo->si_signo == SIGUSR1 )
1320 else if ( siginfo->si_signo == SIGUSR2 )
1322 CallCancelThread() ;
1327 // MESSAGE("SigIntHandler BEGIN sleeping.") ;
1334 // MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1340 void SigIntHandler( int what )
1343 MESSAGE( pthread_self() << "SigIntHandler what " << what << endl );
1345 MESSAGE( "SigIntHandler what " << what << endl );
1350 MESSAGE("SigIntHandler END sleeping.") ;
1355 ActSigIntHandler() ;
1356 if ( what == SIGUSR1 )
1363 MESSAGE("SigIntHandler BEGIN sleeping.") ;
1370 MESSAGE("SigIntHandler LEAVE sleeping after " << count << " s.") ;
1377 /*! \brief copy a file from a remote host (container) to the local host
1378 * \param container the remote container
1379 * \param remoteFile the file to copy locally from the remote host into localFile
1380 * \param localFile the local file
1382 void Engines_Container_i::copyFile(Engines::Container_ptr container, const char* remoteFile, const char* localFile)
1384 Engines::fileTransfer_var fileTransfer = container->getFileTransfer();
1387 if ((fp = fopen(localFile,"wb")) == NULL)
1389 INFOS("file " << localFile << " cannot be open for writing");
1393 CORBA::Long fileId = fileTransfer->open(remoteFile);
1396 Engines::fileBlock* aBlock;
1403 aBlock = fileTransfer->getBlock(fileId);
1404 toFollow = aBlock->length();
1406 CORBA::Octet *buf = aBlock->get_buffer();
1407 fwrite(buf, sizeof(CORBA::Octet), toFollow, fp);
1411 MESSAGE("end of transfer");
1412 fileTransfer->close(fileId);
1416 INFOS("open reference file for copy impossible");