1 // Copyright (C) 2007-2021 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, or (at your option) any later version.
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
23 #include "SALOME_ContainerManager.hxx"
24 #include "SALOME_ResourcesManager.hxx"
25 #include "SALOME_LoadRateManager.hxx"
26 #include "SALOME_NamingService.hxx"
27 #include "SALOME_ResourcesManager_Client.hxx"
28 #include "SALOME_Embedded_NamingService.hxx"
29 #include "SALOME_ModuleCatalog.hh"
30 #include "Basics_Utils.hxx"
31 #include "Basics_DirUtils.hxx"
32 #include <sys/types.h>
39 #include "Utils_CorbaException.hxx"
43 #include <SALOMEconfig.h>
44 #include CORBA_CLIENT_HEADER(SALOME_Session)
53 #define getpid _getpid
56 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
61 #ifdef WITH_PACO_PARALLEL
65 const int SALOME_ContainerManager::TIME_OUT_TO_LAUNCH_CONT=60;
67 const char *SALOME_ContainerManager::_ContainerManagerNameInNS =
70 omni_mutex SALOME_ContainerManager::_numInstanceMutex;
72 Utils_Mutex SALOME_ContainerManager::_getenvMutex;
74 Utils_Mutex SALOME_ContainerManager::_systemMutex;
76 //=============================================================================
80 * Define a CORBA single thread policy for the server, which avoid to deal
81 * with non thread-safe usage like Change_Directory in SALOME naming service
83 //=============================================================================
85 SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_NamingService_Abstract *ns)
88 MESSAGE("constructor");
90 _resManager = new SALOME_ResourcesManager_Client(ns);
92 PortableServer::POAManager_var pman = poa->the_POAManager();
93 _orb = CORBA::ORB::_duplicate(orb) ;
94 CORBA::PolicyList policies;
96 PortableServer::ThreadPolicy_var threadPol(poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL));
97 policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
99 _poa = poa->create_POA("MThreadPOA",pman,policies);
100 threadPol->destroy();
101 PortableServer::ObjectId_var id = _poa->activate_object(this);
102 CORBA::Object_var obj = _poa->id_to_reference(id);
103 Engines::ContainerManager_var refContMan = Engines::ContainerManager::_narrow(obj);
105 _NS->Register(refContMan,_ContainerManagerNameInNS);
106 _isAppliSalomeDefined = (GetenvThreadSafe("APPLI") != 0);
111 // the urifile name depends on pid of the process
112 std::stringstream urifile;
113 urifile << GetenvThreadSafeAsString("HOME") << "/.urifile_" << getpid();
114 setenv("OMPI_URI_FILE",urifile.str().c_str(),1);
115 if( GetenvThreadSafe("OMPI_URI_FILE") != NULL ){
116 // Linux specific code
117 pid_t pid = fork(); // spawn a child process, following code is executed in both processes
118 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
120 std::string uriarg = GetenvThreadSafeAsString("OMPI_URI_FILE");
121 execlp( "ompi-server", "ompi-server", "-r", uriarg.c_str(), NULL );
122 throw SALOME_Exception("Error when launching ompi-server"); // execlp failed
126 throw SALOME_Exception("fork() failed");
130 //wait(NULL); // wait(?) for a child end
131 _pid_mpiServer = pid;
136 // Linux specific code
137 pid_t pid = fork(); // spawn a child process, following code is executed in both processes
138 if ( pid == 0 ) // I'm a child, replace myself with a new hydra_nameserver
140 execlp( "hydra_nameserver", "hydra_nameserver", NULL );
141 throw SALOME_Exception("Error when launching hydra_nameserver"); // execlp failed
145 throw SALOME_Exception("fork() failed");
150 _pid_mpiServer = pid;
155 MESSAGE("constructor end");
158 //=============================================================================
162 //=============================================================================
164 SALOME_ContainerManager::~SALOME_ContainerManager()
166 MESSAGE("destructor");
170 if( GetenvThreadSafe("OMPI_URI_FILE") != NULL ){
171 // kill my ompi-server
172 if( kill(_pid_mpiServer,SIGTERM) != 0 )
173 throw SALOME_Exception("Error when killing ompi-server");
175 int status=SystemThreadSafe("rm -f ${OMPI_URI_FILE}");
177 throw SALOME_Exception("Error when removing urifile");
180 // kill my hydra_nameserver
181 if(_pid_mpiServer > -1)
182 if( kill(_pid_mpiServer,SIGTERM) != 0 )
183 throw SALOME_Exception("Error when killing hydra_nameserver");
188 //=============================================================================
189 //! shutdown all the containers, then the ContainerManager servant
192 //=============================================================================
194 void SALOME_ContainerManager::Shutdown()
197 ShutdownContainers();
199 _NS->Destroy_Name(_ContainerManagerNameInNS);
200 PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
201 _poa->deactivate_object(oid);
204 //=============================================================================
205 //! Loop on all the containers listed in naming service, ask shutdown on each
208 //=============================================================================
210 void SALOME_ContainerManager::ShutdownContainers()
212 MESSAGE("ShutdownContainers");
215 SALOME::Session_var session = SALOME::Session::_nil();
217 CORBA::Object_var objS = _NS->Resolve("/Kernel/Session");
218 if (!CORBA::is_nil(objS))
220 session = SALOME::Session::_narrow(objS);
221 if (!CORBA::is_nil(session))
222 pid = session->getPID();
226 isOK = _NS->Change_Directory("/Containers");
228 std::vector<std::string> vec = _NS->list_directory_recurs();
229 std::list<std::string> lstCont;
230 for(std::vector<std::string>::iterator iter = vec.begin();iter!=vec.end();iter++)
233 CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
236 Engines::Container_var cont=Engines::Container::_narrow(obj);
237 if(!CORBA::is_nil(cont) && pid != cont->getPID())
238 lstCont.push_back((*iter));
240 catch(const CORBA::Exception&)
242 // ignore this entry and continue
245 MESSAGE("Container list: ");
246 for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
249 for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++)
254 CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
255 Engines::Container_var cont=Engines::Container::_narrow(obj);
256 if(!CORBA::is_nil(cont))
258 MESSAGE("ShutdownContainers: " << (*iter));
262 MESSAGE("ShutdownContainers: no container ref for " << (*iter));
264 catch(CORBA::SystemException& e)
266 INFOS("CORBA::SystemException ignored : " << e);
268 catch(CORBA::Exception&)
270 INFOS("CORBA::Exception ignored.");
274 INFOS("Unknown exception ignored.");
280 //=============================================================================
281 //! Give a suitable Container given constraints
283 * \param params Container Parameters required for the container
284 * \return the container or nil
286 //=============================================================================
287 Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::ContainerParameters& params)
289 std::string machFile;
290 Engines::Container_ptr ret(Engines::Container::_nil());
292 // Step 0: Default mode is start
293 Engines::ContainerParameters local_params(params);
294 if (std::string(local_params.mode.in()) == "")
295 local_params.mode = CORBA::string_dup("start");
296 std::string mode = local_params.mode.in();
297 MESSAGE("[GiveContainer] starting with mode: " << mode);
299 // Step 1: Find Container for find and findorstart mode
300 if (mode == "find" || mode == "findorstart")
302 ret = FindContainer(params, params.resource_params.resList);
303 if(!CORBA::is_nil(ret))
309 MESSAGE("[GiveContainer] no container found");
319 // Step 2: Get all possibleResources from the parameters
320 // Consider only resources that can run containers
321 resourceParams resource_params = resourceParameters_CORBAtoCPP(local_params.resource_params);
322 resource_params.can_run_containers = true;
323 std::vector<std::string> possibleResources = _resManager->GetFittingResources(resource_params);
324 MESSAGE("[GiveContainer] - length of possible resources " << possibleResources.size());
325 std::vector<std::string> local_resources;
327 // Step 3: if mode is "get" keep only machines with existing containers
330 for(unsigned int i=0; i < possibleResources.size(); i++)
332 Engines::Container_ptr cont = FindContainer(params, possibleResources[i]);
335 if(!cont->_non_existent())
336 local_resources.push_back(possibleResources[i]);
338 catch(CORBA::Exception&) {}
341 // if local_resources is empty, we cannot give a container
342 if (local_resources.size() == 0)
344 MESSAGE("[GiveContainer] cannot find a container for mode get");
349 local_resources = possibleResources;
351 // Step 4: select the resource where to get/start the container
352 bool resource_available = true;
353 std::string resource_selected;
354 std::vector<std::string> resources = local_resources;
355 while (resource_available)
357 if (resources.size() == 0)
358 resource_available = false;
363 resource_selected = _resManager->Find(params.resource_params.policy.in(), resources);
364 // Remove resource_selected from vector
365 std::vector<std::string>::iterator it;
366 for (it=resources.begin() ; it < resources.end(); it++ )
367 if (*it == resource_selected)
373 catch(const SALOME_Exception &ex) //!< TODO: unused variable
375 MESSAGE("[GiveContainer] Exception in ResourceManager find !: " << ex.what());
378 MESSAGE("[GiveContainer] Resource selected is: " << resource_selected);
380 // Step 5: Create container name
381 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
382 std::string hostname(resource_definition.HostName);
383 std::string containerNameInNS;
385 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
388 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
389 machFile = machinesFile(nbproc);
391 catch(const SALOME_Exception & ex)
393 std::string err_msg = ex.what();
394 err_msg += params.container_name;
395 INFOS(err_msg.c_str());
398 // A mpi parallel container register on zero node in NS
399 std::string mpiZeroNode = GetMPIZeroNode(resource_selected,machFile).c_str();
400 containerNameInNS = _NS->BuildContainerNameForNS(params, mpiZeroNode.c_str());
403 containerNameInNS = _NS->BuildContainerNameForNS(params, hostname.c_str());
404 MESSAGE("[GiveContainer] Container name in the naming service: " << containerNameInNS);
406 // Step 6: check if the name exists in naming service
407 //if params.mode == "getorstart" or "get" use the existing container
408 //if params.mode == "start" shutdown the existing container before launching a new one with that name
410 { // critical section
411 Utils_Locker lock (&_giveContainerMutex1);
412 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
413 if (!CORBA::is_nil(obj))
417 Engines::Container_var cont=Engines::Container::_narrow(obj);
418 if(!cont->_non_existent())
420 if(std::string(params.mode.in())=="getorstart" || std::string(params.mode.in())=="get"){
421 return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
425 INFOS("[GiveContainer] A container is already registered with the name: " << containerNameInNS << ", shutdown the existing container");
426 cont->Shutdown(); // shutdown the registered container if it exists
430 catch(CORBA::Exception&)
432 INFOS("[GiveContainer] CORBA::Exception ignored when trying to get the container - we start a new one");
435 } // end critical section
436 Engines::Container_var cont = LaunchContainer(params, resource_selected, hostname, machFile, containerNameInNS);
437 if (!CORBA::is_nil(cont))
439 INFOS("[GiveContainer] container " << containerNameInNS << " launched");
444 INFOS("[GiveContainer] Failed to launch container on resource " << resource_selected);
449 // We were not able to launch the container
450 INFOS("[GiveContainer] Cannot launch the container on the following selected resources:")
451 std::vector<std::string>::iterator it;
452 for (it=local_resources.begin() ; it < local_resources.end(); it++ )
453 INFOS("[GiveContainer] " << *it)
457 std::string SALOME_ContainerManager::GetCppBinaryOfKernelContainer() const
459 std::string ret = this->_isSSL ? "SALOME_Container_No_NS_Serv" : "SALOME_Container";
463 std::string SALOME_ContainerManager::GetRunRemoteExecutableScript() const
465 std::string ret = this->_isSSL ? "runRemoteSSL.sh" : "runRemote.sh";
469 Engines::Container_ptr
470 SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& params,
471 const std::string & resource_selected,
472 const std::string & hostname,
473 const std::string & machFile,
474 const std::string & containerNameInNS)
476 std::string user,command,logFilename,tmpFileName;
478 Engines::Container_ptr ret(Engines::Container::_nil());
479 {//start of critical section
480 Utils_Locker lock (&_giveContainerMutex1);
481 // Step 1: type of container: PaCO, Exe, Mpi or Classic
482 // Mpi already tested in step 5, specific code on BuildCommandToLaunch Local/Remote Container methods
483 // TODO -> separates Mpi from Classic/Exe
485 std::string container_exe = this->GetCppBinaryOfKernelContainer();
486 Engines::ContainerParameters local_params(params);
490 CORBA::String_var container_exe_tmp;
491 CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
492 SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
493 if (CORBA::is_nil (Catalog))
495 INFOS("[GiveContainer] Module Catalog is not found -> cannot launch a container");
498 // Loop through component list
499 for(unsigned int i=0; i < local_params.resource_params.componentList.length(); i++)
501 const char* compoi = local_params.resource_params.componentList[i];
502 SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
503 if (CORBA::is_nil (compoInfo))
507 SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
508 container_exe_tmp=compoInfo->implementation_name();
509 if(impl==SALOME_ModuleCatalog::CEXE)
513 INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
514 return Engines::Container::_nil();
516 MESSAGE("[GiveContainer] Exe container found !: " << container_exe_tmp);
517 container_exe = container_exe_tmp.in();
522 catch (ServiceUnreachable&)
524 INFOS("Caught exception: Naming Service Unreachable");
529 INFOS("Caught unknown exception.");
533 // Step 2: test resource
534 // Only if an application directory is set
535 if(hostname != Kernel_Utils::GetHostname() && _isAppliSalomeDefined)
538 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_selected));
539 std::string command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
540 resInfo.UserName, resInfo.AppliPath);
542 // Launch remote command
543 command += " \"ls /tmp >/dev/null 2>&1\"";
544 // Anthony : command is NO MORE launched to improve dramatically time to launch containers
548 // Error on resource - cannot launch commands
549 INFOS("[LaunchContainer] Cannot launch commands on machine " << hostname);
550 INFOS("[LaunchContainer] Command was " << command);
552 INFOS("[LaunchContainer] Command status is " << WEXITSTATUS(status));
554 return Engines::Container::_nil();
558 // Step 3: start a new container
559 // Check if a PaCO container
561 if (std::string(local_params.parallelLib.in()) != "")
563 ret = StartPaCOPPContainer(params, resource_selected);
566 // Other type of containers...
567 MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
568 // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
569 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL && params.isMPI )
570 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
571 // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
572 else if(hostname == Kernel_Utils::GetHostname())
573 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
574 // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
576 command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
578 //redirect stdout and stderr in a file
580 logFilename=GetenvThreadSafeAsString("TEMP");
582 user = GetenvThreadSafeAsString( "USERNAME" );
584 user = GetenvThreadSafeAsString( "USER" );
586 user = GetenvThreadSafeAsString( "LOGNAME" );
588 char* val = GetenvThreadSafe("SALOME_TMP_DIR");
591 struct stat file_info;
592 stat(val, &file_info);
593 bool is_dir = S_ISDIR(file_info.st_mode);
594 if (is_dir)logFilename=val;
595 else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
599 logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
600 std::ostringstream tmp;
601 tmp << "_" << getpid();
602 logFilename += tmp.str();
603 logFilename += ".log" ;
604 command += " > " + logFilename + " 2>&1";
605 MakeTheCommandToBeLaunchedASync(command);
607 // launch container with a system call
608 status=SystemThreadSafe(command.c_str());
609 }//end of critical of section
613 INFOS("[LaunchContainer] command failed (system command status -1): " << command);
614 RmTmpFile(tmpFileName); // command file can be removed here
615 return Engines::Container::_nil();
617 else if (status == 217)
619 INFOS("[LaunchContainer] command failed (system command status 217): " << command);
620 RmTmpFile(tmpFileName); // command file can be removed here
621 return Engines::Container::_nil();
625 // Step 4: Wait for the container
626 int count(GetTimeOutToLoaunchServer());
627 INFOS("[GiveContainer] waiting " << count << " second steps container " << containerNameInNS);
628 while (CORBA::is_nil(ret) && count)
632 MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
633 CORBA::Object_var obj(_NS->Resolve(containerNameInNS.c_str()));
634 ret=Engines::Container::_narrow(obj);
636 if (CORBA::is_nil(ret))
638 INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
642 // Setting log file name
643 logFilename=":"+logFilename;
644 logFilename="@"+Kernel_Utils::GetHostname()+logFilename;//threadsafe
645 logFilename=user+logFilename;
646 ret->logfilename(logFilename.c_str());
647 RmTmpFile(tmpFileName); // command file can be removed here
653 //=============================================================================
654 //! Find a container given constraints (params) on a list of machines (possibleComputers)
655 //! agy : this method is ThreadSafe
659 //=============================================================================
661 Engines::Container_ptr SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const Engines::ResourceList& possibleResources)
663 MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
664 for(unsigned int i=0; i < possibleResources.length();i++)
666 Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
667 if(!CORBA::is_nil(cont))
670 MESSAGE("[FindContainer] no container found");
671 return Engines::Container::_nil();
674 //=============================================================================
675 //! Find a container given constraints (params) on a machine (theMachine)
676 //! agy : this method is ThreadSafe
680 //=============================================================================
682 Engines::Container_ptr
683 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const std::string& resource)
685 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource);
686 std::string hostname(resource_definition.HostName);
687 std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
688 MESSAGE("[FindContainer] Try to find a container " << containerNameInNS << " on resource " << resource);
689 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
692 if(obj->_non_existent())
693 return Engines::Container::_nil();
695 return Engines::Container::_narrow(obj);
697 catch(const CORBA::Exception&)
699 return Engines::Container::_nil();
704 bool isPythonContainer(const char* ContainerName);
706 //=============================================================================
708 * This is no longer valid (C++ container are also python containers)
710 //=============================================================================
711 bool isPythonContainer(const char* ContainerName)
713 return false; // VSR 02/08/2013: Python containers are no more supported
715 size_t len = strlen(ContainerName);
718 if (strcmp(ContainerName + len - 2, "Py") == 0)
724 //=============================================================================
726 * Builds the script to be launched
728 * If SALOME Application not defined ($APPLI),
729 * see BuildTempFileToLaunchRemoteContainer()
731 * Else rely on distant configuration. Command is under the form (example):
732 * ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
733 * SALOME_Container containerName &"
735 * - where user is omitted if not specified in CatalogResources,
736 * - where distant path is always relative to user@machine $HOME, and
737 * equal to $APPLI if not specified in CatalogResources,
738 * - where hostNS is the hostname of CORBA naming server (set by scripts to
739 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
740 * - where portNS is the port used by CORBA naming server (set by scripts to
741 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
742 * - where workingdir is the requested working directory for the container.
743 * If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
745 //=============================================================================
748 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
750 std::string command,tmpFileName;
751 if (!_isAppliSalomeDefined)
752 command = BuildTempFileToLaunchRemoteContainer(resource_name, params, tmpFileName);
755 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
757 std::string wdir = params.workingdir.in();
759 // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
760 // SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
762 // "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
763 // -- SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
764 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
765 resInfo.UserName, resInfo.AppliPath,
770 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
771 command += " mpirun -np ";
772 std::ostringstream o;
776 command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
777 #elif defined(OPEN_MPI)
778 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
779 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
781 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
782 command += GetenvThreadSafeAsString("OMPI_URI_FILE");
785 command += "-nameserver " + Kernel_Utils::GetHostname();
787 command += " SALOME_MPIContainer ";
790 command += " " +container_exe+ " ";
792 command += _NS->ContainerName(params);
796 AddOmninamesParams(command);
798 MESSAGE("command =" << command);
804 //=============================================================================
806 * builds the command to be launched.
808 //=============================================================================
809 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
811 tmpFileName = BuildTemporaryFileName();
814 std::ostringstream o;
818 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
824 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
825 o << "-machinefile " << machinesFile << " ";
828 o << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
829 #elif defined(OPEN_MPI)
830 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
831 o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
834 o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
835 o << GetenvThreadSafeAsString("OMPI_URI_FILE");
838 o << "-nameserver " + Kernel_Utils::GetHostname();
841 if (isPythonContainer(params.container_name))
842 o << " pyMPI SALOME_ContainerPy.py ";
844 o << " SALOME_MPIContainer ";
849 std::string wdir=params.workingdir.in();
852 // a working directory is requested
853 if(wdir == "$TEMPDIR")
855 // a new temporary directory is requested
856 std::string dir = Kernel_Utils::GetTmpDir();
858 o << "cd /d " << dir << std::endl;
860 o << "cd " << dir << ";";
866 // a permanent directory is requested use it or create it
868 o << "mkdir " + wdir << std::endl;
869 o << "cd /D " + wdir << std::endl;
871 o << "mkdir -p " << wdir << " && cd " << wdir + ";";
876 if (isPythonContainer(params.container_name))
877 o << "SALOME_ContainerPy.py ";
879 o << container_exe + " ";
883 o << _NS->ContainerName(params) << " ";
887 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
888 CORBA::String_var iorNS = _orb->object_to_string(ns);
894 AddOmninamesParams(o);
897 std::ofstream command_file( tmpFileName.c_str() );
898 command_file << o.str();
899 command_file.close();
902 chmod(tmpFileName.c_str(), 0x1ED);
904 command = tmpFileName;
906 MESSAGE("Command is file ... " << command);
907 MESSAGE("Command is ... " << o.str());
912 //=============================================================================
914 * removes the generated temporary file in case of a remote launch.
915 * This method is thread safe
917 //=============================================================================
919 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
921 size_t length = tmpFileName.size();
925 std::string command = "del /F ";
927 std::string command = "rm ";
930 command += tmpFileName.substr(0, length - 3 );
932 command += tmpFileName;
934 SystemThreadSafe(command.c_str());
935 //if dir is empty - remove it
936 std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
937 if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
940 command = "del /F " + tmp_dir;
942 command = "rmdir " + tmp_dir;
944 SystemThreadSafe(command.c_str());
949 //=============================================================================
951 * add to command all options relative to naming service.
953 //=============================================================================
955 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
957 std::ostringstream oss;
958 AddOmninamesParams(oss);
962 //=============================================================================
964 * add to command all options relative to naming service.
966 //=============================================================================
968 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
970 AddOmninamesParams(fileStream,_NS);
973 //=============================================================================
975 * add to command all options relative to naming service.
977 //=============================================================================
979 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
981 SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
984 CORBA::String_var iorstr(nsTrad->getIORaddr());
985 fileStream << "ORBInitRef NameService=";
986 fileStream << iorstr;
990 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
993 command = "%PYTHONBIN% -c \"import subprocess ; subprocess.Popen(r'" + command + "').pid\"";
999 int SALOME_ContainerManager::GetTimeOutToLoaunchServer()
1001 int count(TIME_OUT_TO_LAUNCH_CONT);
1002 if (GetenvThreadSafe("TIMEOUT_TO_LAUNCH_CONTAINER") != 0)
1004 std::string new_count_str(GetenvThreadSafeAsString("TIMEOUT_TO_LAUNCH_CONTAINER"));
1006 std::istringstream ss(new_count_str);
1007 if (!(ss >> new_count))
1009 INFOS("[LaunchContainer] TIMEOUT_TO_LAUNCH_CONTAINER should be an int");
1017 void SALOME_ContainerManager::SleepInSecond(int ellapseTimeInSecond)
1020 sleep( ellapseTimeInSecond ) ;
1022 int timeInMS(1000*ellapseTimeInSecond);
1027 //=============================================================================
1029 * generate a file name in /tmp directory
1031 //=============================================================================
1033 std::string SALOME_ContainerManager::BuildTemporaryFileName()
1035 //build more complex file name to support multiple salome session
1036 std::string aFileName = Kernel_Utils::GetTmpFileName();
1037 std::ostringstream str_pid;
1038 str_pid << ::getpid();
1039 aFileName = aFileName + "-" + str_pid.str();
1043 aFileName += ".bat";
1048 //=============================================================================
1050 * Builds in a temporary file the script to be launched.
1052 * Used if SALOME Application ($APPLI) is not defined.
1053 * The command is build with data from CatalogResources, in which every path
1054 * used on remote computer must be defined.
1056 //=============================================================================
1058 std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const std::string& resource_name, const Engines::ContainerParameters& params, std::string& tmpFileName) const
1062 tmpFileName = BuildTemporaryFileName();
1063 std::ofstream tempOutputFile;
1064 tempOutputFile.open(tmpFileName.c_str(), std::ofstream::out );
1065 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
1066 tempOutputFile << "#! /bin/sh" << std::endl;
1070 tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1071 //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1077 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
1079 tempOutputFile << "mpirun -np ";
1081 tempOutputFile << nbproc << " ";
1083 tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1084 #elif defined(OPEN_MPI)
1085 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
1086 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1088 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1089 tempOutputFile << GetenvThreadSafeAsString("OMPI_URI_FILE");
1091 #elif defined(MPICH)
1092 tempOutputFile << "-nameserver " + Kernel_Utils::GetHostname();
1096 tempOutputFile << GetenvThreadSafeAsString("KERNEL_ROOT_DIR") << "/bin/salome/";
1100 if (isPythonContainer(params.container_name))
1101 tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1103 tempOutputFile << " SALOME_MPIContainer ";
1108 if (isPythonContainer(params.container_name))
1109 tempOutputFile << "SALOME_ContainerPy.py ";
1111 tempOutputFile << "SALOME_Container ";
1114 tempOutputFile << _NS->ContainerName(params) << " -";
1115 AddOmninamesParams(tempOutputFile);
1116 tempOutputFile << " &" << std::endl;
1117 tempOutputFile.flush();
1118 tempOutputFile.close();
1120 chmod(tmpFileName.c_str(), 0x1ED);
1123 // --- Build command
1125 std::string command;
1127 if (resInfo.Protocol == rsh)
1130 std::string commandRcp = "rcp ";
1131 commandRcp += tmpFileName;
1133 commandRcp += resInfo.HostName;
1135 commandRcp += tmpFileName;
1136 status = SystemThreadSafe(commandRcp.c_str());
1139 else if (resInfo.Protocol == ssh)
1142 std::string commandRcp = "scp ";
1143 commandRcp += tmpFileName;
1145 commandRcp += resInfo.HostName;
1147 commandRcp += tmpFileName;
1148 status = SystemThreadSafe(commandRcp.c_str());
1151 else if (resInfo.Protocol == srun)
1153 command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
1154 std::string commandRcp = "rcp ";
1155 commandRcp += tmpFileName;
1157 commandRcp += resInfo.HostName;
1159 commandRcp += tmpFileName;
1160 status = SystemThreadSafe(commandRcp.c_str());
1163 throw SALOME_Exception("Unknown protocol");
1166 throw SALOME_Exception("Error of connection on remote host");
1168 command += resInfo.HostName;
1170 command += tmpFileName;
1178 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile) const
1181 std::string zeronode;
1182 std::string command;
1183 std::string tmpFile = BuildTemporaryFileName();
1184 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(machine));
1186 if(resInfo.Protocol == sh)
1188 return resInfo.HostName;
1191 if( GetenvThreadSafe("LIBBATCH_NODEFILE") == NULL )
1193 if (_isAppliSalomeDefined)
1195 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
1196 resInfo.UserName, resInfo.AppliPath);
1197 command += " mpirun -np 1 hostname -s > " + tmpFile;
1200 command = "mpirun -np 1 hostname -s > " + tmpFile;
1203 command = "mpirun -np 1 -machinefile " + machinesFile + " hostname -s > " + tmpFile;
1205 status = SystemThreadSafe(command.c_str());
1207 std::ifstream fp(tmpFile.c_str(),std::ios::in);
1208 while(fp >> zeronode);
1216 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1219 std::string nodesFile = GetenvThreadSafeAsString("LIBBATCH_NODEFILE");
1220 std::string machinesFile = Kernel_Utils::GetTmpFileName();
1221 std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1222 std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1224 _numInstanceMutex.lock();
1226 for(int i=0;i<_nbprocUsed;i++)
1229 for(int i=0;i<nbproc;i++)
1231 fpo << tmp << std::endl;
1233 throw SALOME_Exception("You need more processors than batch session have allocated for you! Unable to launch the mpi container: ");
1235 _nbprocUsed += nbproc;
1239 _numInstanceMutex.unlock();
1241 return machinesFile;
1245 std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol,
1246 const std::string & hostname,
1247 const std::string & username,
1248 const std::string & applipath,
1249 const std::string & workdir) const
1251 std::ostringstream command;
1258 command << "-l " << username << " ";
1260 command << hostname << " ";
1266 command << "-l " << username << " ";
1268 command << hostname << " ";
1271 // no need to redefine the user with srun, the job user is taken by default
1272 // (note: for srun, user id can be specified with " --uid=<user>")
1273 command << "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=" << hostname << " ";
1276 command << "pbsdsh -o -h " << hostname << " ";
1279 command << "blaunch -no-shell " << hostname << " ";
1282 throw SALOME_Exception("Unknown protocol");
1285 std::string remoteapplipath;
1287 remoteapplipath = GetenvThreadSafeAsString("APPLI");
1289 remoteapplipath = applipath;
1291 ASSERT(GetenvThreadSafe("NSHOST"));
1292 ASSERT(GetenvThreadSafe("NSPORT"));
1294 // $APPLI points either to an application directory, or to a salome launcher file
1295 // we prepare the remote command according to the case
1296 struct stat statbuf;
1297 if (stat(GetenvThreadSafe("APPLI"), &statbuf) ==0 && S_ISREG(statbuf.st_mode))
1299 // if $APPLI is a regular file, we asume it's a salome Launcher
1300 // generate a command with a salome launcher
1301 command << remoteapplipath
1304 << GetenvThreadSafeAsString("NSHOST") // hostname of CORBA name server
1306 << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1308 command << "-d " << workdir;
1311 else // we assume it's a salome application directory
1313 // generate a command with runRemote.sh
1314 command << remoteapplipath;
1315 command << "/" << this->GetRunRemoteExecutableScript() << " ";
1319 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1320 CORBA::String_var iorNS = _orb->object_to_string(ns);
1325 command << GetenvThreadSafeAsString("NSHOST"); // hostname of CORBA name server
1327 command << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1332 command << " WORKINGDIR ";
1334 if(workdir == "$TEMPDIR")
1335 command << "\\$TEMPDIR";
1337 command << workdir; // requested working directory
1342 return command.str();
1346 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1350 // Step 1 : check ContainerParameters
1351 // Check container_name, has to be defined
1352 if (std::string(params.container_name.in()) == "")
1354 INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1357 // Check parallelLib
1358 std::string parallelLib = params.parallelLib.in();
1359 if (parallelLib != "Mpi" && parallelLib != "Dummy")
1361 INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1362 INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1363 INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1367 if (params.nb_proc <= 0)
1369 INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1373 // Step 2 : check resource_selected
1374 const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1375 //std::string protocol = resource_definition->protocol.in();
1376 std::string username = resource_definition.UserName;
1377 std::string applipath = resource_definition.AppliPath;
1379 //if (protocol == "" || username == "" || applipath == "")
1380 if (username == "" || applipath == "")
1382 INFOS("[checkPaCOParameters] resource selected is not well defined");
1383 INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1384 INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1385 INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1386 INFOS("[checkPaCOParameters] resource username: " << username);
1387 INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1395 * :WARNING: Do not directly convert returned value to std::string
1396 * This function may return NULL if env variable is not defined.
1397 * And std::string(NULL) causes undefined behavior.
1398 * Use GetenvThreadSafeAsString to properly get a std::string.
1400 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1401 {// getenv is not thread safe. See man 7 pthread.
1402 Utils_Locker lock (&_getenvMutex);
1403 return getenv(name);
1407 * Return env variable as a std::string.
1408 * Return empty string if env variable is not set.
1410 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1412 char* var = GetenvThreadSafe(name);
1413 return var ? std::string(var) : std::string();
1416 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1418 Utils_Locker lock (&_systemMutex);
1419 return system(command);
1422 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1424 Utils_Locker lock(&_systemMutex);
1425 if(command.size()<1)
1426 throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1428 pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1430 pid_t pid = -1; //Throw SALOME_Exception on Windows
1432 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1434 std::size_t sz(command.size());
1435 char **args = new char *[sz+1];
1436 for(std::size_t i=0;i<sz;i++)
1437 args[i] = strdup(command[i].c_str());
1439 execvp( command[0].c_str() , args );
1440 std::ostringstream oss;
1441 oss << "Error when launching " << command[0];
1442 throw SALOME_Exception(oss.str().c_str()); // execvp failed
1446 throw SALOME_Exception("fork() failed");
1448 else // I'm a parent
1454 #ifdef WITH_PACO_PARALLEL
1456 //=============================================================================
1458 * Start a suitable PaCO++ Parallel Container in a list of machines.
1459 * \param params Container Parameters required for the container
1460 * \return CORBA container reference.
1462 //=============================================================================
1463 Engines::Container_ptr
1464 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1465 std::string resource_selected)
1467 CORBA::Object_var obj;
1468 PaCO::InterfaceManager_var container_proxy;
1469 Engines::Container_ptr ret = Engines::Container::_nil();
1470 Engines::ContainerParameters params(params_const);
1471 params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1473 // Step 0 : Check parameters
1474 if (!checkPaCOParameters(params, resource_selected))
1476 INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1480 // Step 1 : Starting a new parallel container !
1481 INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1482 INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1484 // Step 2 : Get a MachineFile for the parallel container
1485 std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1487 params.parallelLib.in());
1489 if (machine_file_name == "")
1491 INFOS("[StartPaCOPPContainer] Machine file generation failed");
1495 // Step 3 : starting parallel container proxy
1496 std::string command_proxy("");
1497 std::string proxy_machine;
1500 command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1502 catch(const SALOME_Exception & ex)
1504 INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1508 obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1509 if (CORBA::is_nil(obj))
1511 INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1514 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1515 MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1517 // Step 4 : starting parallel container nodes
1518 std::string command_nodes("");
1519 SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1522 command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1524 catch(const SALOME_Exception & ex)
1526 INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1531 std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1532 bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1535 INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1536 // Il faut tuer le proxy
1539 Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1544 INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1549 // Step 4 : connecting nodes and the proxy to actually create a parallel container
1550 for (int i = 0; i < params.nb_proc; i++)
1552 std::ostringstream tmp;
1554 std::string proc_number = tmp.str();
1555 std::string container_node_name = container_generic_node_name + proc_number;
1557 std::string theNodeMachine(nodes_machines[i]);
1558 std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1559 obj = _NS->Resolve(containerNameInNS.c_str());
1560 if (CORBA::is_nil(obj))
1562 INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1563 INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1568 MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1569 PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1571 MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1573 catch(CORBA::SystemException& e)
1575 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1576 INFOS("CORBA::SystemException : " << e);
1579 catch(CORBA::Exception& e)
1581 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1582 INFOS("CORBA::Exception" << e);
1587 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1588 INFOS("Unknown exception !");
1593 // Step 5 : starting parallel container
1596 MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1597 container_proxy->start();
1598 MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1599 ret = Engines::Container::_narrow(container_proxy);
1601 catch(CORBA::SystemException& e)
1603 INFOS("Caught CORBA::SystemException. : " << e);
1605 catch(PortableServer::POA::ServantAlreadyActive&)
1607 INFOS("Caught CORBA::ServantAlreadyActiveException");
1609 catch(CORBA::Exception&)
1611 INFOS("Caught CORBA::Exception.");
1613 catch(std::exception& exc)
1615 INFOS("Caught std::exception - "<<exc.what());
1619 INFOS("Caught unknown exception.");
1625 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1626 std::string machine_file_name,
1627 std::string & proxy_hostname)
1629 // In the proxy case, we always launch a Dummy Proxy
1630 std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1631 std::string container_name = params.container_name.in();
1633 // Convert nb_proc in string
1634 std::ostringstream tmp_string;
1635 tmp_string << params.nb_proc;
1636 std::string nb_proc_str = tmp_string.str();
1638 // Get resource definition
1639 ParserResourcesType resource_definition =
1640 _resManager->GetResourceDefinition(params.resource_params.name.in());
1643 std::string hostname;
1644 std::ifstream machine_file(machine_file_name.c_str());
1645 std::getline(machine_file, hostname, ' ');
1646 size_t found = hostname.find('\n');
1647 if (found!=std::string::npos)
1648 hostname.erase(found, 1); // Remove \n
1649 proxy_hostname = hostname;
1650 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1653 bool remote_execution = false;
1654 if (hostname != std::string(Kernel_Utils::GetHostname()))
1656 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1657 remote_execution = true;
1661 std::string log_type("");
1662 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1666 // Generating the command
1667 std::string command_begin("");
1668 std::string command_end("");
1669 std::ostringstream command;
1671 LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1672 command << command_begin;
1674 // Adding connection command
1675 // We can only have a remote execution with
1676 // a SALOME application
1677 if (remote_execution)
1679 ASSERT(GetenvThreadSafe("NSHOST"));
1680 ASSERT(GetenvThreadSafe("NSPORT"));
1682 command << resource_definition.getAccessProtocolTypeStr();
1684 command << resource_definition.UserName;
1685 command << " " << hostname;
1686 command << " " << resource_definition.AppliPath;
1687 command << "/runRemote.sh ";
1688 command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1689 command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1692 command << exe_name;
1693 command << " " << container_name;
1694 command << " Dummy";
1695 command << " " << hostname;
1696 command << " " << nb_proc_str;
1698 AddOmninamesParams(command);
1701 command << command_end;
1702 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1704 return command.str();
1708 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1709 const std::string & machine_file_name,
1710 SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1711 const std::string & proxy_hostname)
1714 std::string exe_name = "SALOME_ParallelContainerNode";
1715 exe_name += params.parallelLib.in();
1716 std::string container_name = params.container_name.in();
1718 // Convert nb_proc in string
1719 std::ostringstream nb_proc_stream;
1720 nb_proc_stream << params.nb_proc;
1722 // Get resource definition
1723 ParserResourcesType resource_definition =
1724 _resManager->GetResourceDefinition(params.resource_params.name.in());
1727 std::string log_type("");
1728 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1732 // Now the command is different according to paralleLib
1733 std::ostringstream command_nodes;
1734 std::ifstream machine_file(machine_file_name.c_str());
1735 if (std::string(params.parallelLib.in()) == "Dummy")
1737 for (int i= 0; i < params.nb_proc; i++)
1740 std::string hostname;
1741 std::getline(machine_file, hostname);
1742 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1745 bool remote_execution = false;
1746 if (hostname != std::string(Kernel_Utils::GetHostname()))
1748 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1749 remote_execution = true;
1752 // For each node we have a new command
1753 // Generating the command
1754 std::ostringstream command_node_stream;
1755 std::string command_node_begin("");
1756 std::string command_node_end("");
1757 std::ostringstream node_number;
1759 std::string container_node_name = container_name + node_number.str();
1760 LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1762 // Adding connection command
1763 // We can only have a remote execution with
1764 // a SALOME application
1765 if (remote_execution)
1767 ASSERT(GetenvThreadSafe("NSHOST"));
1768 ASSERT(GetenvThreadSafe("NSPORT"));
1770 command_node_stream << resource_definition.getAccessProtocolTypeStr();
1771 command_node_stream << " -l ";
1772 command_node_stream << resource_definition.UserName;
1773 command_node_stream << " " << hostname;
1774 command_node_stream << " " << resource_definition.AppliPath;
1775 command_node_stream << "/runRemote.sh ";
1776 command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1777 command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1780 command_node_stream << exe_name;
1781 command_node_stream << " " << container_name;
1782 command_node_stream << " " << params.parallelLib.in();
1783 command_node_stream << " " << proxy_hostname;
1784 command_node_stream << " " << node_number.str();
1785 command_node_stream << " -";
1786 AddOmninamesParams(command_node_stream);
1788 command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1789 vect_machine.push_back(hostname);
1793 else if (std::string(params.parallelLib.in()) == "Mpi")
1796 std::string hostname;
1797 std::getline(machine_file, hostname, ' ');
1798 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1801 bool remote_execution = false;
1802 if (hostname != std::string(Kernel_Utils::GetHostname()))
1804 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1805 remote_execution = true;
1808 // In case of Mpi and Remote, we copy machine_file in the applipath
1809 // scp mpi_machine_file user@machine:Path
1810 std::ostringstream command_remote_stream;
1811 std::string::size_type last = machine_file_name.find_last_of("/");
1812 if (last == std::string::npos)
1815 if (resource_definition.Protocol == rsh)
1816 command_remote_stream << "rcp ";
1818 command_remote_stream << "scp ";
1819 command_remote_stream << machine_file_name << " ";
1820 command_remote_stream << resource_definition.UserName << "@";
1821 command_remote_stream << hostname << ":" << resource_definition.AppliPath;
1822 command_remote_stream << "/" << machine_file_name.substr(last+1);
1824 int status = SystemThreadSafe(command_remote_stream.str().c_str());
1827 INFOS("copy of the MPI machine file failed ! - sorry !");
1831 // Generating the command
1832 std::string command_begin("");
1833 std::string command_end("");
1835 LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1836 command_nodes << command_begin;
1838 // Adding connection command
1839 // We can only have a remote execution with
1840 // a SALOME application
1841 if (remote_execution)
1843 ASSERT(GetenvThreadSafe("NSHOST"));
1844 ASSERT(GetenvThreadSafe("NSPORT"));
1846 command_nodes << resource_definition.getAccessProtocolTypeStr();
1847 command_nodes << " -l ";
1848 command_nodes << resource_definition.UserName;
1849 command_nodes << " " << hostname;
1850 command_nodes << " " << resource_definition.AppliPath;
1851 command_nodes << "/runRemote.sh ";
1852 command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1853 command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1856 if (resource_definition.mpi == lam)
1858 command_nodes << "mpiexec -ssi boot ";
1859 command_nodes << "-machinefile " << machine_file_name << " ";
1860 command_nodes << "-n " << params.nb_proc;
1864 command_nodes << "mpirun -np " << params.nb_proc;
1866 command_nodes << " " << exe_name;
1867 command_nodes << " " << container_name;
1868 command_nodes << " " << params.parallelLib.in();
1869 command_nodes << " " << proxy_hostname;
1870 command_nodes << " -";
1871 AddOmninamesParams(command_nodes);
1873 // We don't put hostname, because nodes are registered in the resource of the proxy
1874 for (int i= 0; i < params.nb_proc; i++)
1875 vect_machine.push_back(proxy_hostname);
1877 command_nodes << command_end;
1879 return command_nodes.str();
1883 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
1884 const std::string & exe_type,
1885 const std::string & container_name,
1886 const std::string & hostname,
1887 std::string & begin,
1890 if(log_type == "xterm")
1892 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1895 else if(log_type == "xterm_debug")
1897 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1902 // default into a file...
1903 std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
1904 std::string user = GetenvThreadSafeAsString("USER");
1906 user = GetenvThreadSafeAsString("LOGNAME");
1907 logFilename += user + ".log";
1908 end = " > " + logFilename + " 2>&1 & ";
1913 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
1914 const Engines::ContainerParameters& params,
1915 const std::string & hostname)
1917 PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
1919 MESSAGE("[LaunchPaCOProxyContainer] Launch command");
1920 int status = SystemThreadSafe(command.c_str());
1922 INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
1923 return container_proxy;
1925 else if (status == 217) {
1926 INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
1927 return container_proxy;
1930 int count(GetTimeOutToLoaunchServer());
1931 CORBA::Object_var obj = CORBA::Object::_nil();
1932 std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
1934 MESSAGE("[LaunchParallelContainer] Waiting for Parallel Container proxy : " << containerNameInNS);
1936 while (CORBA::is_nil(obj) && count)
1940 obj = _NS->Resolve(containerNameInNS.c_str());
1945 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1947 catch(CORBA::SystemException& e)
1949 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1950 INFOS("CORBA::SystemException : " << e);
1951 return container_proxy;
1953 catch(CORBA::Exception& e)
1955 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1956 INFOS("CORBA::Exception" << e);
1957 return container_proxy;
1961 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1962 INFOS("Unknown exception !");
1963 return container_proxy;
1965 if (CORBA::is_nil(container_proxy))
1967 INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
1968 return container_proxy;
1973 //=============================================================================
1974 /*! This method launches the parallel container.
1975 * It will may be placed on the resources manager.
1977 * \param command to launch
1978 * \param container's parameters
1979 * \param name of the container
1981 * \return CORBA container reference
1983 //=============================================================================
1985 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
1986 const Engines::ContainerParameters& params,
1987 const std::string& name,
1988 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
1990 INFOS("[LaunchPaCONodeContainer] Launch command");
1991 int status = SystemThreadSafe(command.c_str());
1993 INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
1996 else if (status == 217) {
1997 INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
2001 INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
2002 // We are waiting all the nodes
2003 for (int i = 0; i < params.nb_proc; i++)
2005 CORBA::Object_var obj = CORBA::Object::_nil();
2006 std::string theMachine(vect_machine[i]);
2008 std::ostringstream tmp;
2010 std::string proc_number = tmp.str();
2011 std::string container_node_name = name + proc_number;
2012 std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
2013 INFOS("[LaunchPaCONodeContainer] Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
2014 int count(GetTimeOutToLoaunchServer());
2015 while (CORBA::is_nil(obj) && count) {
2018 obj = _NS->Resolve(containerNameInNS.c_str());
2020 if (CORBA::is_nil(obj))
2022 INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2031 Engines::Container_ptr
2032 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2033 std::string /*resource_selected*/)
2035 Engines::Container_ptr ret = Engines::Container::_nil();
2036 INFOS("[StarPaCOPPContainer] is disabled !");
2037 INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2042 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2043 std::string /*machine_file_name*/,
2044 std::string & /*proxy_hostname*/)
2050 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2051 const std::string & /*machine_file_name*/,
2052 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2053 const std::string & /*proxy_hostname*/)
2058 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2059 const std::string & /*exe_type*/,
2060 const std::string & /*container_name*/,
2061 const std::string & /*hostname*/,
2062 std::string & /*begin*/,
2063 std::string & /*end*/)
2068 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2069 const Engines::ContainerParameters& /*params*/,
2070 const std::string& /*hostname*/)
2072 CORBA::Object_ptr ret = CORBA::Object::_nil();
2077 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2078 const Engines::ContainerParameters& /*params*/,
2079 const std::string& /*name*/,
2080 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)