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;
1252 bool envd = true; // source the environment
1259 command << "-l " << username << " ";
1261 command << hostname << " ";
1267 command << "-l " << username << " ";
1269 command << hostname << " ";
1272 // no need to redefine the user with srun, the job user is taken by default
1273 // (note: for srun, user id can be specified with " --uid=<user>")
1274 command << "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=" << hostname << " ";
1278 command << "pbsdsh -o -h " << hostname << " ";
1281 command << "blaunch -no-shell " << hostname << " ";
1284 throw SALOME_Exception("Unknown protocol");
1287 std::string remoteapplipath;
1289 remoteapplipath = GetenvThreadSafeAsString("APPLI");
1291 remoteapplipath = applipath;
1293 ASSERT(GetenvThreadSafe("NSHOST"));
1294 ASSERT(GetenvThreadSafe("NSPORT"));
1296 // $APPLI points either to an application directory, or to a salome launcher file
1297 // we prepare the remote command according to the case
1298 struct stat statbuf;
1299 if (stat(GetenvThreadSafe("APPLI"), &statbuf) ==0 && S_ISREG(statbuf.st_mode))
1301 // if $APPLI is a regular file, we asume it's a salome Launcher
1302 // generate a command with a salome launcher
1303 command << remoteapplipath
1306 << GetenvThreadSafeAsString("NSHOST") // hostname of CORBA name server
1308 << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1310 command << "-d " << workdir;
1313 else // we assume it's a salome application directory
1315 // generate a command with runRemote.sh
1316 command << remoteapplipath;
1317 command << "/" << this->GetRunRemoteExecutableScript() << " ";
1319 command << "--noenvd ";
1323 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1324 CORBA::String_var iorNS = _orb->object_to_string(ns);
1329 command << GetenvThreadSafeAsString("NSHOST"); // hostname of CORBA name server
1331 command << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1336 command << " WORKINGDIR ";
1338 if(workdir == "$TEMPDIR")
1339 command << "\\$TEMPDIR";
1341 command << workdir; // requested working directory
1346 return command.str();
1350 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1354 // Step 1 : check ContainerParameters
1355 // Check container_name, has to be defined
1356 if (std::string(params.container_name.in()) == "")
1358 INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1361 // Check parallelLib
1362 std::string parallelLib = params.parallelLib.in();
1363 if (parallelLib != "Mpi" && parallelLib != "Dummy")
1365 INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1366 INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1367 INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1371 if (params.nb_proc <= 0)
1373 INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1377 // Step 2 : check resource_selected
1378 const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1379 //std::string protocol = resource_definition->protocol.in();
1380 std::string username = resource_definition.UserName;
1381 std::string applipath = resource_definition.AppliPath;
1383 //if (protocol == "" || username == "" || applipath == "")
1384 if (username == "" || applipath == "")
1386 INFOS("[checkPaCOParameters] resource selected is not well defined");
1387 INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1388 INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1389 INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1390 INFOS("[checkPaCOParameters] resource username: " << username);
1391 INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1399 * :WARNING: Do not directly convert returned value to std::string
1400 * This function may return NULL if env variable is not defined.
1401 * And std::string(NULL) causes undefined behavior.
1402 * Use GetenvThreadSafeAsString to properly get a std::string.
1404 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1405 {// getenv is not thread safe. See man 7 pthread.
1406 Utils_Locker lock (&_getenvMutex);
1407 return getenv(name);
1411 * Return env variable as a std::string.
1412 * Return empty string if env variable is not set.
1414 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1416 char* var = GetenvThreadSafe(name);
1417 return var ? std::string(var) : std::string();
1420 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1422 Utils_Locker lock (&_systemMutex);
1423 return system(command);
1426 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1428 Utils_Locker lock(&_systemMutex);
1429 if(command.size()<1)
1430 throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1432 pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1434 pid_t pid = -1; //Throw SALOME_Exception on Windows
1436 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1438 std::size_t sz(command.size());
1439 char **args = new char *[sz+1];
1440 for(std::size_t i=0;i<sz;i++)
1441 args[i] = strdup(command[i].c_str());
1443 execvp( command[0].c_str() , args );
1444 std::ostringstream oss;
1445 oss << "Error when launching " << command[0];
1446 throw SALOME_Exception(oss.str().c_str()); // execvp failed
1450 throw SALOME_Exception("fork() failed");
1452 else // I'm a parent
1458 #ifdef WITH_PACO_PARALLEL
1460 //=============================================================================
1462 * Start a suitable PaCO++ Parallel Container in a list of machines.
1463 * \param params Container Parameters required for the container
1464 * \return CORBA container reference.
1466 //=============================================================================
1467 Engines::Container_ptr
1468 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1469 std::string resource_selected)
1471 CORBA::Object_var obj;
1472 PaCO::InterfaceManager_var container_proxy;
1473 Engines::Container_ptr ret = Engines::Container::_nil();
1474 Engines::ContainerParameters params(params_const);
1475 params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1477 // Step 0 : Check parameters
1478 if (!checkPaCOParameters(params, resource_selected))
1480 INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1484 // Step 1 : Starting a new parallel container !
1485 INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1486 INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1488 // Step 2 : Get a MachineFile for the parallel container
1489 std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1491 params.parallelLib.in());
1493 if (machine_file_name == "")
1495 INFOS("[StartPaCOPPContainer] Machine file generation failed");
1499 // Step 3 : starting parallel container proxy
1500 std::string command_proxy("");
1501 std::string proxy_machine;
1504 command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1506 catch(const SALOME_Exception & ex)
1508 INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1512 obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1513 if (CORBA::is_nil(obj))
1515 INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1518 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1519 MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1521 // Step 4 : starting parallel container nodes
1522 std::string command_nodes("");
1523 SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1526 command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1528 catch(const SALOME_Exception & ex)
1530 INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1535 std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1536 bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1539 INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1540 // Il faut tuer le proxy
1543 Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1548 INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1553 // Step 4 : connecting nodes and the proxy to actually create a parallel container
1554 for (int i = 0; i < params.nb_proc; i++)
1556 std::ostringstream tmp;
1558 std::string proc_number = tmp.str();
1559 std::string container_node_name = container_generic_node_name + proc_number;
1561 std::string theNodeMachine(nodes_machines[i]);
1562 std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1563 obj = _NS->Resolve(containerNameInNS.c_str());
1564 if (CORBA::is_nil(obj))
1566 INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1567 INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1572 MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1573 PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1575 MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1577 catch(CORBA::SystemException& e)
1579 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1580 INFOS("CORBA::SystemException : " << e);
1583 catch(CORBA::Exception& e)
1585 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1586 INFOS("CORBA::Exception" << e);
1591 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1592 INFOS("Unknown exception !");
1597 // Step 5 : starting parallel container
1600 MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1601 container_proxy->start();
1602 MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1603 ret = Engines::Container::_narrow(container_proxy);
1605 catch(CORBA::SystemException& e)
1607 INFOS("Caught CORBA::SystemException. : " << e);
1609 catch(PortableServer::POA::ServantAlreadyActive&)
1611 INFOS("Caught CORBA::ServantAlreadyActiveException");
1613 catch(CORBA::Exception&)
1615 INFOS("Caught CORBA::Exception.");
1617 catch(std::exception& exc)
1619 INFOS("Caught std::exception - "<<exc.what());
1623 INFOS("Caught unknown exception.");
1629 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1630 std::string machine_file_name,
1631 std::string & proxy_hostname)
1633 // In the proxy case, we always launch a Dummy Proxy
1634 std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1635 std::string container_name = params.container_name.in();
1637 // Convert nb_proc in string
1638 std::ostringstream tmp_string;
1639 tmp_string << params.nb_proc;
1640 std::string nb_proc_str = tmp_string.str();
1642 // Get resource definition
1643 ParserResourcesType resource_definition =
1644 _resManager->GetResourceDefinition(params.resource_params.name.in());
1647 std::string hostname;
1648 std::ifstream machine_file(machine_file_name.c_str());
1649 std::getline(machine_file, hostname, ' ');
1650 size_t found = hostname.find('\n');
1651 if (found!=std::string::npos)
1652 hostname.erase(found, 1); // Remove \n
1653 proxy_hostname = hostname;
1654 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1657 bool remote_execution = false;
1658 if (hostname != std::string(Kernel_Utils::GetHostname()))
1660 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1661 remote_execution = true;
1665 std::string log_type("");
1666 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1670 // Generating the command
1671 std::string command_begin("");
1672 std::string command_end("");
1673 std::ostringstream command;
1675 LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1676 command << command_begin;
1678 // Adding connection command
1679 // We can only have a remote execution with
1680 // a SALOME application
1681 if (remote_execution)
1683 ASSERT(GetenvThreadSafe("NSHOST"));
1684 ASSERT(GetenvThreadSafe("NSPORT"));
1686 command << resource_definition.getAccessProtocolTypeStr();
1688 command << resource_definition.UserName;
1689 command << " " << hostname;
1690 command << " " << resource_definition.AppliPath;
1691 command << "/runRemote.sh ";
1692 command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1693 command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1696 command << exe_name;
1697 command << " " << container_name;
1698 command << " Dummy";
1699 command << " " << hostname;
1700 command << " " << nb_proc_str;
1702 AddOmninamesParams(command);
1705 command << command_end;
1706 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1708 return command.str();
1712 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1713 const std::string & machine_file_name,
1714 SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1715 const std::string & proxy_hostname)
1718 std::string exe_name = "SALOME_ParallelContainerNode";
1719 exe_name += params.parallelLib.in();
1720 std::string container_name = params.container_name.in();
1722 // Convert nb_proc in string
1723 std::ostringstream nb_proc_stream;
1724 nb_proc_stream << params.nb_proc;
1726 // Get resource definition
1727 ParserResourcesType resource_definition =
1728 _resManager->GetResourceDefinition(params.resource_params.name.in());
1731 std::string log_type("");
1732 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1736 // Now the command is different according to paralleLib
1737 std::ostringstream command_nodes;
1738 std::ifstream machine_file(machine_file_name.c_str());
1739 if (std::string(params.parallelLib.in()) == "Dummy")
1741 for (int i= 0; i < params.nb_proc; i++)
1744 std::string hostname;
1745 std::getline(machine_file, hostname);
1746 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1749 bool remote_execution = false;
1750 if (hostname != std::string(Kernel_Utils::GetHostname()))
1752 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1753 remote_execution = true;
1756 // For each node we have a new command
1757 // Generating the command
1758 std::ostringstream command_node_stream;
1759 std::string command_node_begin("");
1760 std::string command_node_end("");
1761 std::ostringstream node_number;
1763 std::string container_node_name = container_name + node_number.str();
1764 LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1766 // Adding connection command
1767 // We can only have a remote execution with
1768 // a SALOME application
1769 if (remote_execution)
1771 ASSERT(GetenvThreadSafe("NSHOST"));
1772 ASSERT(GetenvThreadSafe("NSPORT"));
1774 command_node_stream << resource_definition.getAccessProtocolTypeStr();
1775 command_node_stream << " -l ";
1776 command_node_stream << resource_definition.UserName;
1777 command_node_stream << " " << hostname;
1778 command_node_stream << " " << resource_definition.AppliPath;
1779 command_node_stream << "/runRemote.sh ";
1780 command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1781 command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1784 command_node_stream << exe_name;
1785 command_node_stream << " " << container_name;
1786 command_node_stream << " " << params.parallelLib.in();
1787 command_node_stream << " " << proxy_hostname;
1788 command_node_stream << " " << node_number.str();
1789 command_node_stream << " -";
1790 AddOmninamesParams(command_node_stream);
1792 command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1793 vect_machine.push_back(hostname);
1797 else if (std::string(params.parallelLib.in()) == "Mpi")
1800 std::string hostname;
1801 std::getline(machine_file, hostname, ' ');
1802 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1805 bool remote_execution = false;
1806 if (hostname != std::string(Kernel_Utils::GetHostname()))
1808 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1809 remote_execution = true;
1812 // In case of Mpi and Remote, we copy machine_file in the applipath
1813 // scp mpi_machine_file user@machine:Path
1814 std::ostringstream command_remote_stream;
1815 std::string::size_type last = machine_file_name.find_last_of("/");
1816 if (last == std::string::npos)
1819 if (resource_definition.Protocol == rsh)
1820 command_remote_stream << "rcp ";
1822 command_remote_stream << "scp ";
1823 command_remote_stream << machine_file_name << " ";
1824 command_remote_stream << resource_definition.UserName << "@";
1825 command_remote_stream << hostname << ":" << resource_definition.AppliPath;
1826 command_remote_stream << "/" << machine_file_name.substr(last+1);
1828 int status = SystemThreadSafe(command_remote_stream.str().c_str());
1831 INFOS("copy of the MPI machine file failed ! - sorry !");
1835 // Generating the command
1836 std::string command_begin("");
1837 std::string command_end("");
1839 LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1840 command_nodes << command_begin;
1842 // Adding connection command
1843 // We can only have a remote execution with
1844 // a SALOME application
1845 if (remote_execution)
1847 ASSERT(GetenvThreadSafe("NSHOST"));
1848 ASSERT(GetenvThreadSafe("NSPORT"));
1850 command_nodes << resource_definition.getAccessProtocolTypeStr();
1851 command_nodes << " -l ";
1852 command_nodes << resource_definition.UserName;
1853 command_nodes << " " << hostname;
1854 command_nodes << " " << resource_definition.AppliPath;
1855 command_nodes << "/runRemote.sh ";
1856 command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1857 command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1860 if (resource_definition.mpi == lam)
1862 command_nodes << "mpiexec -ssi boot ";
1863 command_nodes << "-machinefile " << machine_file_name << " ";
1864 command_nodes << "-n " << params.nb_proc;
1868 command_nodes << "mpirun -np " << params.nb_proc;
1870 command_nodes << " " << exe_name;
1871 command_nodes << " " << container_name;
1872 command_nodes << " " << params.parallelLib.in();
1873 command_nodes << " " << proxy_hostname;
1874 command_nodes << " -";
1875 AddOmninamesParams(command_nodes);
1877 // We don't put hostname, because nodes are registered in the resource of the proxy
1878 for (int i= 0; i < params.nb_proc; i++)
1879 vect_machine.push_back(proxy_hostname);
1881 command_nodes << command_end;
1883 return command_nodes.str();
1887 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
1888 const std::string & exe_type,
1889 const std::string & container_name,
1890 const std::string & hostname,
1891 std::string & begin,
1894 if(log_type == "xterm")
1896 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1899 else if(log_type == "xterm_debug")
1901 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1906 // default into a file...
1907 std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
1908 std::string user = GetenvThreadSafeAsString("USER");
1910 user = GetenvThreadSafeAsString("LOGNAME");
1911 logFilename += user + ".log";
1912 end = " > " + logFilename + " 2>&1 & ";
1917 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
1918 const Engines::ContainerParameters& params,
1919 const std::string & hostname)
1921 PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
1923 MESSAGE("[LaunchPaCOProxyContainer] Launch command");
1924 int status = SystemThreadSafe(command.c_str());
1926 INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
1927 return container_proxy;
1929 else if (status == 217) {
1930 INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
1931 return container_proxy;
1934 int count(GetTimeOutToLoaunchServer());
1935 CORBA::Object_var obj = CORBA::Object::_nil();
1936 std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
1938 MESSAGE("[LaunchParallelContainer] Waiting for Parallel Container proxy : " << containerNameInNS);
1940 while (CORBA::is_nil(obj) && count)
1944 obj = _NS->Resolve(containerNameInNS.c_str());
1949 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1951 catch(CORBA::SystemException& e)
1953 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1954 INFOS("CORBA::SystemException : " << e);
1955 return container_proxy;
1957 catch(CORBA::Exception& e)
1959 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1960 INFOS("CORBA::Exception" << e);
1961 return container_proxy;
1965 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1966 INFOS("Unknown exception !");
1967 return container_proxy;
1969 if (CORBA::is_nil(container_proxy))
1971 INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
1972 return container_proxy;
1977 //=============================================================================
1978 /*! This method launches the parallel container.
1979 * It will may be placed on the resources manager.
1981 * \param command to launch
1982 * \param container's parameters
1983 * \param name of the container
1985 * \return CORBA container reference
1987 //=============================================================================
1989 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
1990 const Engines::ContainerParameters& params,
1991 const std::string& name,
1992 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
1994 INFOS("[LaunchPaCONodeContainer] Launch command");
1995 int status = SystemThreadSafe(command.c_str());
1997 INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
2000 else if (status == 217) {
2001 INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
2005 INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
2006 // We are waiting all the nodes
2007 for (int i = 0; i < params.nb_proc; i++)
2009 CORBA::Object_var obj = CORBA::Object::_nil();
2010 std::string theMachine(vect_machine[i]);
2012 std::ostringstream tmp;
2014 std::string proc_number = tmp.str();
2015 std::string container_node_name = name + proc_number;
2016 std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
2017 INFOS("[LaunchPaCONodeContainer] Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
2018 int count(GetTimeOutToLoaunchServer());
2019 while (CORBA::is_nil(obj) && count) {
2022 obj = _NS->Resolve(containerNameInNS.c_str());
2024 if (CORBA::is_nil(obj))
2026 INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2035 Engines::Container_ptr
2036 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2037 std::string /*resource_selected*/)
2039 Engines::Container_ptr ret = Engines::Container::_nil();
2040 INFOS("[StarPaCOPPContainer] is disabled !");
2041 INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2046 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2047 std::string /*machine_file_name*/,
2048 std::string & /*proxy_hostname*/)
2054 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2055 const std::string & /*machine_file_name*/,
2056 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2057 const std::string & /*proxy_hostname*/)
2062 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2063 const std::string & /*exe_type*/,
2064 const std::string & /*container_name*/,
2065 const std::string & /*hostname*/,
2066 std::string & /*begin*/,
2067 std::string & /*end*/)
2072 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2073 const Engines::ContainerParameters& /*params*/,
2074 const std::string& /*hostname*/)
2076 CORBA::Object_ptr ret = CORBA::Object::_nil();
2081 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2082 const Engines::ContainerParameters& /*params*/,
2083 const std::string& /*name*/,
2084 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)