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 Engines::Container_ptr
458 SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& params,
459 const std::string & resource_selected,
460 const std::string & hostname,
461 const std::string & machFile,
462 const std::string & containerNameInNS)
464 std::string user,command,logFilename,tmpFileName;
466 Engines::Container_ptr ret(Engines::Container::_nil());
467 {//start of critical section
468 Utils_Locker lock (&_giveContainerMutex1);
469 // Step 1: type of container: PaCO, Exe, Mpi or Classic
470 // Mpi already tested in step 5, specific code on BuildCommandToLaunch Local/Remote Container methods
471 // TODO -> separates Mpi from Classic/Exe
473 std::string container_exe = this->_isSSL ? "SALOME_Container_No_NS_Serv" : "SALOME_Container"; // Classic container
474 Engines::ContainerParameters local_params(params);
478 CORBA::String_var container_exe_tmp;
479 CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
480 SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
481 if (CORBA::is_nil (Catalog))
483 INFOS("[GiveContainer] Module Catalog is not found -> cannot launch a container");
486 // Loop through component list
487 for(unsigned int i=0; i < local_params.resource_params.componentList.length(); i++)
489 const char* compoi = local_params.resource_params.componentList[i];
490 SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
491 if (CORBA::is_nil (compoInfo))
495 SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
496 container_exe_tmp=compoInfo->implementation_name();
497 if(impl==SALOME_ModuleCatalog::CEXE)
501 INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
502 return Engines::Container::_nil();
504 MESSAGE("[GiveContainer] Exe container found !: " << container_exe_tmp);
505 container_exe = container_exe_tmp.in();
510 catch (ServiceUnreachable&)
512 INFOS("Caught exception: Naming Service Unreachable");
517 INFOS("Caught unknown exception.");
521 // Step 2: test resource
522 // Only if an application directory is set
523 if(hostname != Kernel_Utils::GetHostname() && _isAppliSalomeDefined)
526 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_selected));
527 std::string command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
528 resInfo.UserName, resInfo.AppliPath);
530 // Launch remote command
531 command += " \"ls /tmp >/dev/null 2>&1\"";
532 // Anthony : command is NO MORE launched to improve dramatically time to launch containers
536 // Error on resource - cannot launch commands
537 INFOS("[LaunchContainer] Cannot launch commands on machine " << hostname);
538 INFOS("[LaunchContainer] Command was " << command);
540 INFOS("[LaunchContainer] Command status is " << WEXITSTATUS(status));
542 return Engines::Container::_nil();
546 // Step 3: start a new container
547 // Check if a PaCO container
549 if (std::string(local_params.parallelLib.in()) != "")
551 ret = StartPaCOPPContainer(params, resource_selected);
554 // Other type of containers...
555 MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
556 // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
557 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL && params.isMPI )
558 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
559 // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
560 else if(hostname == Kernel_Utils::GetHostname())
561 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
562 // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
564 command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
566 //redirect stdout and stderr in a file
568 logFilename=GetenvThreadSafeAsString("TEMP");
570 user = GetenvThreadSafeAsString( "USERNAME" );
572 user = GetenvThreadSafeAsString( "USER" );
574 user = GetenvThreadSafeAsString( "LOGNAME" );
576 char* val = GetenvThreadSafe("SALOME_TMP_DIR");
579 struct stat file_info;
580 stat(val, &file_info);
581 bool is_dir = S_ISDIR(file_info.st_mode);
582 if (is_dir)logFilename=val;
583 else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
587 logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
588 std::ostringstream tmp;
589 tmp << "_" << getpid();
590 logFilename += tmp.str();
591 logFilename += ".log" ;
592 command += " > " + logFilename + " 2>&1";
593 MakeTheCommandToBeLaunchedASync(command);
595 // launch container with a system call
596 status=SystemThreadSafe(command.c_str());
597 }//end of critical of section
601 INFOS("[LaunchContainer] command failed (system command status -1): " << command);
602 RmTmpFile(tmpFileName); // command file can be removed here
603 return Engines::Container::_nil();
605 else if (status == 217)
607 INFOS("[LaunchContainer] command failed (system command status 217): " << command);
608 RmTmpFile(tmpFileName); // command file can be removed here
609 return Engines::Container::_nil();
613 // Step 4: Wait for the container
614 int count(GetTimeOutToLoaunchServer());
615 INFOS("[GiveContainer] waiting " << count << " second steps container " << containerNameInNS);
616 while (CORBA::is_nil(ret) && count)
620 MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
621 CORBA::Object_var obj(_NS->Resolve(containerNameInNS.c_str()));
622 ret=Engines::Container::_narrow(obj);
624 if (CORBA::is_nil(ret))
626 INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
630 // Setting log file name
631 logFilename=":"+logFilename;
632 logFilename="@"+Kernel_Utils::GetHostname()+logFilename;//threadsafe
633 logFilename=user+logFilename;
634 ret->logfilename(logFilename.c_str());
635 RmTmpFile(tmpFileName); // command file can be removed here
641 //=============================================================================
642 //! Find a container given constraints (params) on a list of machines (possibleComputers)
643 //! agy : this method is ThreadSafe
647 //=============================================================================
649 Engines::Container_ptr SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const Engines::ResourceList& possibleResources)
651 MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
652 for(unsigned int i=0; i < possibleResources.length();i++)
654 Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
655 if(!CORBA::is_nil(cont))
658 MESSAGE("[FindContainer] no container found");
659 return Engines::Container::_nil();
662 //=============================================================================
663 //! Find a container given constraints (params) on a machine (theMachine)
664 //! agy : this method is ThreadSafe
668 //=============================================================================
670 Engines::Container_ptr
671 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const std::string& resource)
673 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource);
674 std::string hostname(resource_definition.HostName);
675 std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
676 MESSAGE("[FindContainer] Try to find a container " << containerNameInNS << " on resource " << resource);
677 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
680 if(obj->_non_existent())
681 return Engines::Container::_nil();
683 return Engines::Container::_narrow(obj);
685 catch(const CORBA::Exception&)
687 return Engines::Container::_nil();
692 bool isPythonContainer(const char* ContainerName);
694 //=============================================================================
696 * This is no longer valid (C++ container are also python containers)
698 //=============================================================================
699 bool isPythonContainer(const char* ContainerName)
701 return false; // VSR 02/08/2013: Python containers are no more supported
703 size_t len = strlen(ContainerName);
706 if (strcmp(ContainerName + len - 2, "Py") == 0)
712 //=============================================================================
714 * Builds the script to be launched
716 * If SALOME Application not defined ($APPLI),
717 * see BuildTempFileToLaunchRemoteContainer()
719 * Else rely on distant configuration. Command is under the form (example):
720 * ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
721 * SALOME_Container containerName &"
723 * - where user is omitted if not specified in CatalogResources,
724 * - where distant path is always relative to user@machine $HOME, and
725 * equal to $APPLI if not specified in CatalogResources,
726 * - where hostNS is the hostname of CORBA naming server (set by scripts to
727 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
728 * - where portNS is the port used by CORBA naming server (set by scripts to
729 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
730 * - where workingdir is the requested working directory for the container.
731 * If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
733 //=============================================================================
736 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
738 std::string command,tmpFileName;
739 if (!_isAppliSalomeDefined)
740 command = BuildTempFileToLaunchRemoteContainer(resource_name, params, tmpFileName);
743 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
745 std::string wdir = params.workingdir.in();
747 // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
748 // SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
750 // "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
751 // -- SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
752 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
753 resInfo.UserName, resInfo.AppliPath,
758 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
759 command += " mpirun -np ";
760 std::ostringstream o;
764 command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
765 #elif defined(OPEN_MPI)
766 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
767 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
769 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
770 command += GetenvThreadSafeAsString("OMPI_URI_FILE");
773 command += "-nameserver " + Kernel_Utils::GetHostname();
775 command += " SALOME_MPIContainer ";
778 command += " " +container_exe+ " ";
780 command += _NS->ContainerName(params);
782 AddOmninamesParams(command);
784 MESSAGE("command =" << command);
790 //=============================================================================
792 * builds the command to be launched.
794 //=============================================================================
795 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
797 tmpFileName = BuildTemporaryFileName();
800 std::ostringstream o;
804 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
810 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
811 o << "-machinefile " << machinesFile << " ";
814 o << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
815 #elif defined(OPEN_MPI)
816 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
817 o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
820 o << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
821 o << GetenvThreadSafeAsString("OMPI_URI_FILE");
824 o << "-nameserver " + Kernel_Utils::GetHostname();
827 if (isPythonContainer(params.container_name))
828 o << " pyMPI SALOME_ContainerPy.py ";
830 o << " SALOME_MPIContainer ";
835 std::string wdir=params.workingdir.in();
838 // a working directory is requested
839 if(wdir == "$TEMPDIR")
841 // a new temporary directory is requested
842 std::string dir = Kernel_Utils::GetTmpDir();
844 o << "cd /d " << dir << std::endl;
846 o << "cd " << dir << ";";
852 // a permanent directory is requested use it or create it
854 o << "mkdir " + wdir << std::endl;
855 o << "cd /D " + wdir << std::endl;
857 o << "mkdir -p " << wdir << " && cd " << wdir + ";";
862 if (isPythonContainer(params.container_name))
863 o << "SALOME_ContainerPy.py ";
865 o << container_exe + " ";
869 o << _NS->ContainerName(params) << " ";
873 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
874 CORBA::String_var iorNS = _orb->object_to_string(ns);
880 AddOmninamesParams(o);
883 std::ofstream command_file( tmpFileName.c_str() );
884 command_file << o.str();
885 command_file.close();
888 chmod(tmpFileName.c_str(), 0x1ED);
890 command = tmpFileName;
892 MESSAGE("Command is file ... " << command);
893 MESSAGE("Command is ... " << o.str());
898 //=============================================================================
900 * removes the generated temporary file in case of a remote launch.
901 * This method is thread safe
903 //=============================================================================
905 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
907 size_t length = tmpFileName.size();
911 std::string command = "del /F ";
913 std::string command = "rm ";
916 command += tmpFileName.substr(0, length - 3 );
918 command += tmpFileName;
920 SystemThreadSafe(command.c_str());
921 //if dir is empty - remove it
922 std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
923 if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
926 command = "del /F " + tmp_dir;
928 command = "rmdir " + tmp_dir;
930 SystemThreadSafe(command.c_str());
935 //=============================================================================
937 * add to command all options relative to naming service.
939 //=============================================================================
941 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
943 std::ostringstream oss;
944 AddOmninamesParams(oss);
948 //=============================================================================
950 * add to command all options relative to naming service.
952 //=============================================================================
954 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
956 AddOmninamesParams(fileStream,_NS);
959 //=============================================================================
961 * add to command all options relative to naming service.
963 //=============================================================================
965 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
967 SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
970 CORBA::String_var iorstr(nsTrad->getIORaddr());
971 fileStream << "ORBInitRef NameService=";
972 fileStream << iorstr;
976 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
979 command = "%PYTHONBIN% -c \"import subprocess ; subprocess.Popen(r'" + command + "').pid\"";
985 int SALOME_ContainerManager::GetTimeOutToLoaunchServer()
987 int count(TIME_OUT_TO_LAUNCH_CONT);
988 if (GetenvThreadSafe("TIMEOUT_TO_LAUNCH_CONTAINER") != 0)
990 std::string new_count_str(GetenvThreadSafeAsString("TIMEOUT_TO_LAUNCH_CONTAINER"));
992 std::istringstream ss(new_count_str);
993 if (!(ss >> new_count))
995 INFOS("[LaunchContainer] TIMEOUT_TO_LAUNCH_CONTAINER should be an int");
1003 void SALOME_ContainerManager::SleepInSecond(int ellapseTimeInSecond)
1006 sleep( ellapseTimeInSecond ) ;
1008 int timeInMS(1000*ellapseTimeInSecond);
1013 //=============================================================================
1015 * generate a file name in /tmp directory
1017 //=============================================================================
1019 std::string SALOME_ContainerManager::BuildTemporaryFileName()
1021 //build more complex file name to support multiple salome session
1022 std::string aFileName = Kernel_Utils::GetTmpFileName();
1023 std::ostringstream str_pid;
1024 str_pid << ::getpid();
1025 aFileName = aFileName + "-" + str_pid.str();
1029 aFileName += ".bat";
1034 //=============================================================================
1036 * Builds in a temporary file the script to be launched.
1038 * Used if SALOME Application ($APPLI) is not defined.
1039 * The command is build with data from CatalogResources, in which every path
1040 * used on remote computer must be defined.
1042 //=============================================================================
1044 std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const std::string& resource_name, const Engines::ContainerParameters& params, std::string& tmpFileName) const
1048 tmpFileName = BuildTemporaryFileName();
1049 std::ofstream tempOutputFile;
1050 tempOutputFile.open(tmpFileName.c_str(), std::ofstream::out );
1051 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
1052 tempOutputFile << "#! /bin/sh" << std::endl;
1056 tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1057 //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1063 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
1065 tempOutputFile << "mpirun -np ";
1067 tempOutputFile << nbproc << " ";
1069 tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1070 #elif defined(OPEN_MPI)
1071 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
1072 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1074 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1075 tempOutputFile << GetenvThreadSafeAsString("OMPI_URI_FILE");
1077 #elif defined(MPICH)
1078 tempOutputFile << "-nameserver " + Kernel_Utils::GetHostname();
1082 tempOutputFile << GetenvThreadSafeAsString("KERNEL_ROOT_DIR") << "/bin/salome/";
1086 if (isPythonContainer(params.container_name))
1087 tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1089 tempOutputFile << " SALOME_MPIContainer ";
1094 if (isPythonContainer(params.container_name))
1095 tempOutputFile << "SALOME_ContainerPy.py ";
1097 tempOutputFile << "SALOME_Container ";
1100 tempOutputFile << _NS->ContainerName(params) << " -";
1101 AddOmninamesParams(tempOutputFile);
1102 tempOutputFile << " &" << std::endl;
1103 tempOutputFile.flush();
1104 tempOutputFile.close();
1106 chmod(tmpFileName.c_str(), 0x1ED);
1109 // --- Build command
1111 std::string command;
1113 if (resInfo.Protocol == rsh)
1116 std::string commandRcp = "rcp ";
1117 commandRcp += tmpFileName;
1119 commandRcp += resInfo.HostName;
1121 commandRcp += tmpFileName;
1122 status = SystemThreadSafe(commandRcp.c_str());
1125 else if (resInfo.Protocol == ssh)
1128 std::string commandRcp = "scp ";
1129 commandRcp += tmpFileName;
1131 commandRcp += resInfo.HostName;
1133 commandRcp += tmpFileName;
1134 status = SystemThreadSafe(commandRcp.c_str());
1137 else if (resInfo.Protocol == srun)
1139 command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
1140 std::string commandRcp = "rcp ";
1141 commandRcp += tmpFileName;
1143 commandRcp += resInfo.HostName;
1145 commandRcp += tmpFileName;
1146 status = SystemThreadSafe(commandRcp.c_str());
1149 throw SALOME_Exception("Unknown protocol");
1152 throw SALOME_Exception("Error of connection on remote host");
1154 command += resInfo.HostName;
1156 command += tmpFileName;
1164 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile) const
1167 std::string zeronode;
1168 std::string command;
1169 std::string tmpFile = BuildTemporaryFileName();
1170 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(machine));
1172 if(resInfo.Protocol == sh)
1174 return resInfo.HostName;
1177 if( GetenvThreadSafe("LIBBATCH_NODEFILE") == NULL )
1179 if (_isAppliSalomeDefined)
1181 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
1182 resInfo.UserName, resInfo.AppliPath);
1183 command += " mpirun -np 1 hostname -s > " + tmpFile;
1186 command = "mpirun -np 1 hostname -s > " + tmpFile;
1189 command = "mpirun -np 1 -machinefile " + machinesFile + " hostname -s > " + tmpFile;
1191 status = SystemThreadSafe(command.c_str());
1193 std::ifstream fp(tmpFile.c_str(),std::ios::in);
1194 while(fp >> zeronode);
1202 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1205 std::string nodesFile = GetenvThreadSafeAsString("LIBBATCH_NODEFILE");
1206 std::string machinesFile = Kernel_Utils::GetTmpFileName();
1207 std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1208 std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1210 _numInstanceMutex.lock();
1212 for(int i=0;i<_nbprocUsed;i++)
1215 for(int i=0;i<nbproc;i++)
1217 fpo << tmp << std::endl;
1219 throw SALOME_Exception("You need more processors than batch session have allocated for you! Unable to launch the mpi container: ");
1221 _nbprocUsed += nbproc;
1225 _numInstanceMutex.unlock();
1227 return machinesFile;
1231 std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol,
1232 const std::string & hostname,
1233 const std::string & username,
1234 const std::string & applipath,
1235 const std::string & workdir)
1237 std::ostringstream command;
1244 command << "-l " << username << " ";
1246 command << hostname << " ";
1252 command << "-l " << username << " ";
1254 command << hostname << " ";
1257 // no need to redefine the user with srun, the job user is taken by default
1258 // (note: for srun, user id can be specified with " --uid=<user>")
1259 command << "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=" << hostname << " ";
1262 command << "pbsdsh -o -h " << hostname << " ";
1265 command << "blaunch -no-shell " << hostname << " ";
1268 throw SALOME_Exception("Unknown protocol");
1271 std::string remoteapplipath;
1273 remoteapplipath = GetenvThreadSafeAsString("APPLI");
1275 remoteapplipath = applipath;
1277 ASSERT(GetenvThreadSafe("NSHOST"));
1278 ASSERT(GetenvThreadSafe("NSPORT"));
1280 // $APPLI points either to an application directory, or to a salome launcher file
1281 // we prepare the remote command according to the case
1282 struct stat statbuf;
1283 if (stat(GetenvThreadSafe("APPLI"), &statbuf) ==0 && S_ISREG(statbuf.st_mode))
1285 // if $APPLI is a regular file, we asume it's a salome Launcher
1286 // generate a command with a salome launcher
1287 command << remoteapplipath
1290 << GetenvThreadSafeAsString("NSHOST") // hostname of CORBA name server
1292 << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1294 command << "-d " << workdir;
1297 else // we assume it's a salome application directory
1299 // generate a command with runRemote.sh
1300 command << remoteapplipath;
1301 command << "/runRemote.sh ";
1302 command << GetenvThreadSafeAsString("NSHOST"); // hostname of CORBA name server
1304 command << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1307 command << " WORKINGDIR ";
1309 if(workdir == "$TEMPDIR")
1310 command << "\\$TEMPDIR";
1312 command << workdir; // requested working directory
1317 return command.str();
1321 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1325 // Step 1 : check ContainerParameters
1326 // Check container_name, has to be defined
1327 if (std::string(params.container_name.in()) == "")
1329 INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1332 // Check parallelLib
1333 std::string parallelLib = params.parallelLib.in();
1334 if (parallelLib != "Mpi" && parallelLib != "Dummy")
1336 INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1337 INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1338 INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1342 if (params.nb_proc <= 0)
1344 INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1348 // Step 2 : check resource_selected
1349 const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1350 //std::string protocol = resource_definition->protocol.in();
1351 std::string username = resource_definition.UserName;
1352 std::string applipath = resource_definition.AppliPath;
1354 //if (protocol == "" || username == "" || applipath == "")
1355 if (username == "" || applipath == "")
1357 INFOS("[checkPaCOParameters] resource selected is not well defined");
1358 INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1359 INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1360 INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1361 INFOS("[checkPaCOParameters] resource username: " << username);
1362 INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1370 * :WARNING: Do not directly convert returned value to std::string
1371 * This function may return NULL if env variable is not defined.
1372 * And std::string(NULL) causes undefined behavior.
1373 * Use GetenvThreadSafeAsString to properly get a std::string.
1375 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1376 {// getenv is not thread safe. See man 7 pthread.
1377 Utils_Locker lock (&_getenvMutex);
1378 return getenv(name);
1382 * Return env variable as a std::string.
1383 * Return empty string if env variable is not set.
1385 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1387 char* var = GetenvThreadSafe(name);
1388 return var ? std::string(var) : std::string();
1391 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1393 Utils_Locker lock (&_systemMutex);
1394 return system(command);
1397 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1399 Utils_Locker lock(&_systemMutex);
1400 if(command.size()<1)
1401 throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1403 pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1405 pid_t pid = -1; //Throw SALOME_Exception on Windows
1407 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1409 std::size_t sz(command.size());
1410 char **args = new char *[sz+1];
1411 for(std::size_t i=0;i<sz;i++)
1412 args[i] = strdup(command[i].c_str());
1414 execvp( command[0].c_str() , args );
1415 std::ostringstream oss;
1416 oss << "Error when launching " << command[0];
1417 throw SALOME_Exception(oss.str().c_str()); // execvp failed
1421 throw SALOME_Exception("fork() failed");
1423 else // I'm a parent
1429 #ifdef WITH_PACO_PARALLEL
1431 //=============================================================================
1433 * Start a suitable PaCO++ Parallel Container in a list of machines.
1434 * \param params Container Parameters required for the container
1435 * \return CORBA container reference.
1437 //=============================================================================
1438 Engines::Container_ptr
1439 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1440 std::string resource_selected)
1442 CORBA::Object_var obj;
1443 PaCO::InterfaceManager_var container_proxy;
1444 Engines::Container_ptr ret = Engines::Container::_nil();
1445 Engines::ContainerParameters params(params_const);
1446 params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1448 // Step 0 : Check parameters
1449 if (!checkPaCOParameters(params, resource_selected))
1451 INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1455 // Step 1 : Starting a new parallel container !
1456 INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1457 INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1459 // Step 2 : Get a MachineFile for the parallel container
1460 std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1462 params.parallelLib.in());
1464 if (machine_file_name == "")
1466 INFOS("[StartPaCOPPContainer] Machine file generation failed");
1470 // Step 3 : starting parallel container proxy
1471 std::string command_proxy("");
1472 std::string proxy_machine;
1475 command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1477 catch(const SALOME_Exception & ex)
1479 INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1483 obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1484 if (CORBA::is_nil(obj))
1486 INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1489 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1490 MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1492 // Step 4 : starting parallel container nodes
1493 std::string command_nodes("");
1494 SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1497 command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1499 catch(const SALOME_Exception & ex)
1501 INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1506 std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1507 bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1510 INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1511 // Il faut tuer le proxy
1514 Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1519 INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1524 // Step 4 : connecting nodes and the proxy to actually create a parallel container
1525 for (int i = 0; i < params.nb_proc; i++)
1527 std::ostringstream tmp;
1529 std::string proc_number = tmp.str();
1530 std::string container_node_name = container_generic_node_name + proc_number;
1532 std::string theNodeMachine(nodes_machines[i]);
1533 std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1534 obj = _NS->Resolve(containerNameInNS.c_str());
1535 if (CORBA::is_nil(obj))
1537 INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1538 INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1543 MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1544 PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1546 MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1548 catch(CORBA::SystemException& e)
1550 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1551 INFOS("CORBA::SystemException : " << e);
1554 catch(CORBA::Exception& e)
1556 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1557 INFOS("CORBA::Exception" << e);
1562 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1563 INFOS("Unknown exception !");
1568 // Step 5 : starting parallel container
1571 MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1572 container_proxy->start();
1573 MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1574 ret = Engines::Container::_narrow(container_proxy);
1576 catch(CORBA::SystemException& e)
1578 INFOS("Caught CORBA::SystemException. : " << e);
1580 catch(PortableServer::POA::ServantAlreadyActive&)
1582 INFOS("Caught CORBA::ServantAlreadyActiveException");
1584 catch(CORBA::Exception&)
1586 INFOS("Caught CORBA::Exception.");
1588 catch(std::exception& exc)
1590 INFOS("Caught std::exception - "<<exc.what());
1594 INFOS("Caught unknown exception.");
1600 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1601 std::string machine_file_name,
1602 std::string & proxy_hostname)
1604 // In the proxy case, we always launch a Dummy Proxy
1605 std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1606 std::string container_name = params.container_name.in();
1608 // Convert nb_proc in string
1609 std::ostringstream tmp_string;
1610 tmp_string << params.nb_proc;
1611 std::string nb_proc_str = tmp_string.str();
1613 // Get resource definition
1614 ParserResourcesType resource_definition =
1615 _resManager->GetResourceDefinition(params.resource_params.name.in());
1618 std::string hostname;
1619 std::ifstream machine_file(machine_file_name.c_str());
1620 std::getline(machine_file, hostname, ' ');
1621 size_t found = hostname.find('\n');
1622 if (found!=std::string::npos)
1623 hostname.erase(found, 1); // Remove \n
1624 proxy_hostname = hostname;
1625 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1628 bool remote_execution = false;
1629 if (hostname != std::string(Kernel_Utils::GetHostname()))
1631 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1632 remote_execution = true;
1636 std::string log_type("");
1637 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1641 // Generating the command
1642 std::string command_begin("");
1643 std::string command_end("");
1644 std::ostringstream command;
1646 LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1647 command << command_begin;
1649 // Adding connection command
1650 // We can only have a remote execution with
1651 // a SALOME application
1652 if (remote_execution)
1654 ASSERT(GetenvThreadSafe("NSHOST"));
1655 ASSERT(GetenvThreadSafe("NSPORT"));
1657 command << resource_definition.getAccessProtocolTypeStr();
1659 command << resource_definition.UserName;
1660 command << " " << hostname;
1661 command << " " << resource_definition.AppliPath;
1662 command << "/runRemote.sh ";
1663 command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1664 command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1667 command << exe_name;
1668 command << " " << container_name;
1669 command << " Dummy";
1670 command << " " << hostname;
1671 command << " " << nb_proc_str;
1673 AddOmninamesParams(command);
1676 command << command_end;
1677 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1679 return command.str();
1683 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1684 const std::string & machine_file_name,
1685 SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1686 const std::string & proxy_hostname)
1689 std::string exe_name = "SALOME_ParallelContainerNode";
1690 exe_name += params.parallelLib.in();
1691 std::string container_name = params.container_name.in();
1693 // Convert nb_proc in string
1694 std::ostringstream nb_proc_stream;
1695 nb_proc_stream << params.nb_proc;
1697 // Get resource definition
1698 ParserResourcesType resource_definition =
1699 _resManager->GetResourceDefinition(params.resource_params.name.in());
1702 std::string log_type("");
1703 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1707 // Now the command is different according to paralleLib
1708 std::ostringstream command_nodes;
1709 std::ifstream machine_file(machine_file_name.c_str());
1710 if (std::string(params.parallelLib.in()) == "Dummy")
1712 for (int i= 0; i < params.nb_proc; i++)
1715 std::string hostname;
1716 std::getline(machine_file, hostname);
1717 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1720 bool remote_execution = false;
1721 if (hostname != std::string(Kernel_Utils::GetHostname()))
1723 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1724 remote_execution = true;
1727 // For each node we have a new command
1728 // Generating the command
1729 std::ostringstream command_node_stream;
1730 std::string command_node_begin("");
1731 std::string command_node_end("");
1732 std::ostringstream node_number;
1734 std::string container_node_name = container_name + node_number.str();
1735 LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1737 // Adding connection command
1738 // We can only have a remote execution with
1739 // a SALOME application
1740 if (remote_execution)
1742 ASSERT(GetenvThreadSafe("NSHOST"));
1743 ASSERT(GetenvThreadSafe("NSPORT"));
1745 command_node_stream << resource_definition.getAccessProtocolTypeStr();
1746 command_node_stream << " -l ";
1747 command_node_stream << resource_definition.UserName;
1748 command_node_stream << " " << hostname;
1749 command_node_stream << " " << resource_definition.AppliPath;
1750 command_node_stream << "/runRemote.sh ";
1751 command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1752 command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1755 command_node_stream << exe_name;
1756 command_node_stream << " " << container_name;
1757 command_node_stream << " " << params.parallelLib.in();
1758 command_node_stream << " " << proxy_hostname;
1759 command_node_stream << " " << node_number.str();
1760 command_node_stream << " -";
1761 AddOmninamesParams(command_node_stream);
1763 command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1764 vect_machine.push_back(hostname);
1768 else if (std::string(params.parallelLib.in()) == "Mpi")
1771 std::string hostname;
1772 std::getline(machine_file, hostname, ' ');
1773 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1776 bool remote_execution = false;
1777 if (hostname != std::string(Kernel_Utils::GetHostname()))
1779 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1780 remote_execution = true;
1783 // In case of Mpi and Remote, we copy machine_file in the applipath
1784 // scp mpi_machine_file user@machine:Path
1785 std::ostringstream command_remote_stream;
1786 std::string::size_type last = machine_file_name.find_last_of("/");
1787 if (last == std::string::npos)
1790 if (resource_definition.Protocol == rsh)
1791 command_remote_stream << "rcp ";
1793 command_remote_stream << "scp ";
1794 command_remote_stream << machine_file_name << " ";
1795 command_remote_stream << resource_definition.UserName << "@";
1796 command_remote_stream << hostname << ":" << resource_definition.AppliPath;
1797 command_remote_stream << "/" << machine_file_name.substr(last+1);
1799 int status = SystemThreadSafe(command_remote_stream.str().c_str());
1802 INFOS("copy of the MPI machine file failed ! - sorry !");
1806 // Generating the command
1807 std::string command_begin("");
1808 std::string command_end("");
1810 LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1811 command_nodes << command_begin;
1813 // Adding connection command
1814 // We can only have a remote execution with
1815 // a SALOME application
1816 if (remote_execution)
1818 ASSERT(GetenvThreadSafe("NSHOST"));
1819 ASSERT(GetenvThreadSafe("NSPORT"));
1821 command_nodes << resource_definition.getAccessProtocolTypeStr();
1822 command_nodes << " -l ";
1823 command_nodes << resource_definition.UserName;
1824 command_nodes << " " << hostname;
1825 command_nodes << " " << resource_definition.AppliPath;
1826 command_nodes << "/runRemote.sh ";
1827 command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1828 command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1831 if (resource_definition.mpi == lam)
1833 command_nodes << "mpiexec -ssi boot ";
1834 command_nodes << "-machinefile " << machine_file_name << " ";
1835 command_nodes << "-n " << params.nb_proc;
1839 command_nodes << "mpirun -np " << params.nb_proc;
1841 command_nodes << " " << exe_name;
1842 command_nodes << " " << container_name;
1843 command_nodes << " " << params.parallelLib.in();
1844 command_nodes << " " << proxy_hostname;
1845 command_nodes << " -";
1846 AddOmninamesParams(command_nodes);
1848 // We don't put hostname, because nodes are registered in the resource of the proxy
1849 for (int i= 0; i < params.nb_proc; i++)
1850 vect_machine.push_back(proxy_hostname);
1852 command_nodes << command_end;
1854 return command_nodes.str();
1858 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
1859 const std::string & exe_type,
1860 const std::string & container_name,
1861 const std::string & hostname,
1862 std::string & begin,
1865 if(log_type == "xterm")
1867 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1870 else if(log_type == "xterm_debug")
1872 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
1877 // default into a file...
1878 std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
1879 std::string user = GetenvThreadSafeAsString("USER");
1881 user = GetenvThreadSafeAsString("LOGNAME");
1882 logFilename += user + ".log";
1883 end = " > " + logFilename + " 2>&1 & ";
1888 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
1889 const Engines::ContainerParameters& params,
1890 const std::string & hostname)
1892 PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
1894 MESSAGE("[LaunchPaCOProxyContainer] Launch command");
1895 int status = SystemThreadSafe(command.c_str());
1897 INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
1898 return container_proxy;
1900 else if (status == 217) {
1901 INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
1902 return container_proxy;
1905 int count(GetTimeOutToLoaunchServer());
1906 CORBA::Object_var obj = CORBA::Object::_nil();
1907 std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
1909 MESSAGE("[LaunchParallelContainer] Waiting for Parallel Container proxy : " << containerNameInNS);
1911 while (CORBA::is_nil(obj) && count)
1915 obj = _NS->Resolve(containerNameInNS.c_str());
1920 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1922 catch(CORBA::SystemException& e)
1924 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1925 INFOS("CORBA::SystemException : " << e);
1926 return container_proxy;
1928 catch(CORBA::Exception& e)
1930 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1931 INFOS("CORBA::Exception" << e);
1932 return container_proxy;
1936 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
1937 INFOS("Unknown exception !");
1938 return container_proxy;
1940 if (CORBA::is_nil(container_proxy))
1942 INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
1943 return container_proxy;
1948 //=============================================================================
1949 /*! This method launches the parallel container.
1950 * It will may be placed on the resources manager.
1952 * \param command to launch
1953 * \param container's parameters
1954 * \param name of the container
1956 * \return CORBA container reference
1958 //=============================================================================
1960 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
1961 const Engines::ContainerParameters& params,
1962 const std::string& name,
1963 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
1965 INFOS("[LaunchPaCONodeContainer] Launch command");
1966 int status = SystemThreadSafe(command.c_str());
1968 INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
1971 else if (status == 217) {
1972 INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
1976 INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
1977 // We are waiting all the nodes
1978 for (int i = 0; i < params.nb_proc; i++)
1980 CORBA::Object_var obj = CORBA::Object::_nil();
1981 std::string theMachine(vect_machine[i]);
1983 std::ostringstream tmp;
1985 std::string proc_number = tmp.str();
1986 std::string container_node_name = name + proc_number;
1987 std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
1988 INFOS("[LaunchPaCONodeContainer] Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
1989 int count(GetTimeOutToLoaunchServer());
1990 while (CORBA::is_nil(obj) && count) {
1993 obj = _NS->Resolve(containerNameInNS.c_str());
1995 if (CORBA::is_nil(obj))
1997 INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2006 Engines::Container_ptr
2007 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2008 std::string /*resource_selected*/)
2010 Engines::Container_ptr ret = Engines::Container::_nil();
2011 INFOS("[StarPaCOPPContainer] is disabled !");
2012 INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2017 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2018 std::string /*machine_file_name*/,
2019 std::string & /*proxy_hostname*/)
2025 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2026 const std::string & /*machine_file_name*/,
2027 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2028 const std::string & /*proxy_hostname*/)
2033 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2034 const std::string & /*exe_type*/,
2035 const std::string & /*container_name*/,
2036 const std::string & /*hostname*/,
2037 std::string & /*begin*/,
2038 std::string & /*end*/)
2043 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2044 const Engines::ContainerParameters& /*params*/,
2045 const std::string& /*hostname*/)
2047 CORBA::Object_ptr ret = CORBA::Object::_nil();
2052 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2053 const Engines::ContainerParameters& /*params*/,
2054 const std::string& /*name*/,
2055 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)