1 // Copyright (C) 2007-2023 CEA, EDF, 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 "PythonCppUtils.hxx"
33 #include <sys/types.h>
40 #include "Utils_CorbaException.hxx"
45 #include <SALOMEconfig.h>
46 #include CORBA_CLIENT_HEADER(SALOME_Session)
55 #define getpid _getpid
58 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
63 #ifdef WITH_PACO_PARALLEL
67 const int SALOME_ContainerManager::TIME_OUT_TO_LAUNCH_CONT=60;
69 const char *SALOME_ContainerManager::_ContainerManagerNameInNS =
72 omni_mutex SALOME_ContainerManager::_numInstanceMutex;
74 Utils_Mutex SALOME_ContainerManager::_getenvMutex;
76 Utils_Mutex SALOME_ContainerManager::_systemMutex;
78 //=============================================================================
82 * Define a CORBA single thread policy for the server, which avoid to deal
83 * with non thread-safe usage like Change_Directory in SALOME naming service
85 //=============================================================================
87 SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_NamingService_Abstract *ns)
90 MESSAGE("constructor");
92 _resManager = new SALOME_ResourcesManager_Client(ns);
94 PortableServer::POAManager_var pman = poa->the_POAManager();
95 _orb = CORBA::ORB::_duplicate(orb) ;
96 CORBA::PolicyList policies;
98 PortableServer::ThreadPolicy_var threadPol(poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL));
99 policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
101 _poa = poa->create_POA("MThreadPOA",pman,policies);
102 threadPol->destroy();
103 PortableServer::ObjectId_var id = _poa->activate_object(this);
104 CORBA::Object_var obj = _poa->id_to_reference(id);
105 Engines::ContainerManager_var refContMan = Engines::ContainerManager::_narrow(obj);
107 _NS->Register(refContMan,_ContainerManagerNameInNS);
108 _isAppliSalomeDefined = (GetenvThreadSafe("APPLI") != 0);
113 // the urifile name depends on pid of the process
114 std::stringstream urifile;
115 urifile << GetenvThreadSafeAsString("HOME") << "/.urifile_" << getpid();
116 setenv("OMPI_URI_FILE",urifile.str().c_str(),1);
117 if( GetenvThreadSafe("OMPI_URI_FILE") != NULL ){
118 // Linux specific code
119 pid_t pid = fork(); // spawn a child process, following code is executed in both processes
120 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
122 std::string uriarg = GetenvThreadSafeAsString("OMPI_URI_FILE");
123 execlp( "ompi-server", "ompi-server", "-r", uriarg.c_str(), NULL );
124 throw SALOME_Exception("Error when launching ompi-server"); // execlp failed
128 throw SALOME_Exception("fork() failed");
132 //wait(NULL); // wait(?) for a child end
133 _pid_mpiServer = pid;
138 // Linux specific code
139 pid_t pid = fork(); // spawn a child process, following code is executed in both processes
140 if ( pid == 0 ) // I'm a child, replace myself with a new hydra_nameserver
142 execlp( "hydra_nameserver", "hydra_nameserver", NULL );
143 throw SALOME_Exception("Error when launching hydra_nameserver"); // execlp failed
147 throw SALOME_Exception("fork() failed");
152 _pid_mpiServer = pid;
157 MESSAGE("constructor end");
160 //=============================================================================
164 //=============================================================================
166 SALOME_ContainerManager::~SALOME_ContainerManager()
168 MESSAGE("destructor");
172 if( GetenvThreadSafe("OMPI_URI_FILE") != NULL ){
173 // kill my ompi-server
174 if( kill(_pid_mpiServer,SIGTERM) != 0 )
175 throw SALOME_Exception("Error when killing ompi-server");
177 int status=SystemThreadSafe("rm -f ${OMPI_URI_FILE}");
179 throw SALOME_Exception("Error when removing urifile");
182 // kill my hydra_nameserver
183 if(_pid_mpiServer > -1)
184 if( kill(_pid_mpiServer,SIGTERM) != 0 )
185 throw SALOME_Exception("Error when killing hydra_nameserver");
190 //=============================================================================
191 //! shutdown all the containers, then the ContainerManager servant
194 //=============================================================================
196 void SALOME_ContainerManager::Shutdown()
199 ShutdownContainers();
201 _NS->Destroy_Name(_ContainerManagerNameInNS);
202 PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
203 _poa->deactivate_object(oid);
206 //=============================================================================
207 //! Loop on all the containers listed in naming service, ask shutdown on each
210 //=============================================================================
212 void SALOME_ContainerManager::ShutdownContainers()
214 MESSAGE("ShutdownContainers");
217 SALOME::Session_var session = SALOME::Session::_nil();
219 CORBA::Object_var objS = _NS->Resolve("/Kernel/Session");
220 if (!CORBA::is_nil(objS))
222 session = SALOME::Session::_narrow(objS);
223 if (!CORBA::is_nil(session))
224 pid = session->getPID();
228 isOK = _NS->Change_Directory("/Containers");
230 std::vector<std::string> vec = _NS->list_directory_recurs();
231 std::list<std::string> lstCont;
232 for(std::vector<std::string>::iterator iter = vec.begin();iter!=vec.end();iter++)
235 CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
238 Engines::Container_var cont=Engines::Container::_narrow(obj);
239 if(!CORBA::is_nil(cont) && pid != cont->getPID())
240 lstCont.push_back((*iter));
242 catch(const CORBA::Exception&)
244 // ignore this entry and continue
247 MESSAGE("Container list: ");
248 for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
251 for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++)
256 CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
257 Engines::Container_var cont=Engines::Container::_narrow(obj);
258 if(!CORBA::is_nil(cont))
260 MESSAGE("ShutdownContainers: " << (*iter));
264 MESSAGE("ShutdownContainers: no container ref for " << (*iter));
266 catch(CORBA::SystemException& e)
268 INFOS("CORBA::SystemException ignored : " << e);
270 catch(CORBA::Exception&)
272 INFOS("CORBA::Exception ignored.");
276 INFOS("Unknown exception ignored.");
282 void SALOME_ContainerManager::SetOverrideEnvForContainers(const Engines::KeyValDict& env)
284 this->_override_env.clear();
285 auto sz = env.length();
286 for(auto i = 0 ; i < sz ; ++i)
287 _override_env.emplace_back(env[i].key.in(), env[i].val.in());
290 Engines::KeyValDict *SALOME_ContainerManager::GetOverrideEnvForContainers()
292 std::unique_ptr<Engines::KeyValDict> ret( new Engines::KeyValDict );
293 auto sz = _override_env.size();
295 for(auto i = 0 ; i < sz ; ++i)
297 (*ret)[i].key = CORBA::string_dup( _override_env[i].first.c_str() );
298 (*ret)[i].val = CORBA::string_dup( _override_env[i].second.c_str() );
300 return ret.release();
303 //=============================================================================
304 //! Give a suitable Container given constraints
306 * \param params Container Parameters required for the container
307 * \return the container or nil
309 //=============================================================================
310 Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::ContainerParameters& params)
312 std::string machFile;
313 Engines::Container_ptr ret(Engines::Container::_nil());
315 // Step 0: Default mode is start
316 Engines::ContainerParameters local_params(params);
317 if (std::string(local_params.mode.in()) == "")
318 local_params.mode = CORBA::string_dup("start");
319 std::string mode = local_params.mode.in();
320 MESSAGE("[GiveContainer] starting with mode: " << mode);
322 // Step 1: Find Container for find and findorstart mode
323 if (mode == "find" || mode == "findorstart")
325 ret = FindContainer(params, params.resource_params.resList);
326 if(!CORBA::is_nil(ret))
332 MESSAGE("[GiveContainer] no container found");
342 // Step 2: Get all possibleResources from the parameters
343 // Consider only resources that can run containers
344 resourceParams resource_params = resourceParameters_CORBAtoCPP(local_params.resource_params);
345 resource_params.can_run_containers = true;
346 std::vector<std::string> possibleResources = _resManager->GetFittingResources(resource_params);
347 MESSAGE("[GiveContainer] - length of possible resources " << possibleResources.size());
348 std::vector<std::string> local_resources;
350 // Step 3: if mode is "get" keep only machines with existing containers
353 for(unsigned int i=0; i < possibleResources.size(); i++)
355 Engines::Container_ptr cont = FindContainer(params, possibleResources[i]);
358 if(!cont->_non_existent())
359 local_resources.push_back(possibleResources[i]);
361 catch(CORBA::Exception&) {}
364 // if local_resources is empty, we cannot give a container
365 if (local_resources.size() == 0)
367 MESSAGE("[GiveContainer] cannot find a container for mode get");
372 local_resources = possibleResources;
374 // Step 4: select the resource where to get/start the container
375 bool resource_available = true;
376 std::string resource_selected;
377 std::vector<std::string> resources = local_resources;
378 while (resource_available)
380 if (resources.size() == 0)
381 resource_available = false;
386 resource_selected = _resManager->Find(params.resource_params.policy.in(), resources);
387 // Remove resource_selected from vector
388 std::vector<std::string>::iterator it;
389 for (it=resources.begin() ; it < resources.end(); it++ )
390 if (*it == resource_selected)
396 catch(const SALOME_Exception &ex) //!< TODO: unused variable
398 MESSAGE("[GiveContainer] Exception in ResourceManager find !: " << ex.what());
401 MESSAGE("[GiveContainer] Resource selected is: " << resource_selected);
403 // Step 5: Create container name
404 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
405 std::string hostname(resource_definition.HostName);
406 std::string containerNameInNS;
408 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
411 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
412 machFile = machinesFile(nbproc);
414 catch(const SALOME_Exception & ex)
416 std::string err_msg = ex.what();
417 err_msg += params.container_name;
418 INFOS(err_msg.c_str());
421 // A mpi parallel container register on zero node in NS
422 std::string mpiZeroNode = GetMPIZeroNode(resource_selected,machFile).c_str();
423 containerNameInNS = _NS->BuildContainerNameForNS(params, mpiZeroNode.c_str());
426 containerNameInNS = _NS->BuildContainerNameForNS(params, hostname.c_str());
427 MESSAGE("[GiveContainer] Container name in the naming service: " << containerNameInNS);
429 // Step 6: check if the name exists in naming service
430 //if params.mode == "getorstart" or "get" use the existing container
431 //if params.mode == "start" shutdown the existing container before launching a new one with that name
433 { // critical section
434 Utils_Locker lock (&_giveContainerMutex1);
435 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
436 if (!CORBA::is_nil(obj))
440 Engines::Container_var cont=Engines::Container::_narrow(obj);
441 if(!cont->_non_existent())
443 if(std::string(params.mode.in())=="getorstart" || std::string(params.mode.in())=="get"){
444 return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
448 INFOS("[GiveContainer] A container is already registered with the name: " << containerNameInNS << ", shutdown the existing container");
449 cont->Shutdown(); // shutdown the registered container if it exists
453 catch(CORBA::Exception&)
455 INFOS("[GiveContainer] CORBA::Exception ignored when trying to get the container - we start a new one");
458 } // end critical section
459 Engines::Container_var cont = LaunchContainer(params, resource_selected, hostname, machFile, containerNameInNS);
460 if (!CORBA::is_nil(cont))
462 INFOS("[GiveContainer] container " << containerNameInNS << " launched");
463 std::ostringstream envInfo;
464 std::for_each( _override_env.begin(), _override_env.end(), [&envInfo](const std::pair<std::string,std::string>& p) { envInfo << p.first << " = " << p.second << std::endl; } );
465 INFOS("[GiveContainer] container " << containerNameInNS << " override " << envInfo.str());
466 Engines::FieldsDict envCorba;
468 auto sz = _override_env.size();
470 for(auto i = 0 ; i < sz ; ++i)
472 envCorba[i].key = CORBA::string_dup( _override_env[i].first.c_str() );
473 envCorba[i].value <<= CORBA::string_dup( _override_env[i].second.c_str() );
476 cont->override_environment_python( envCorba );
481 INFOS("[GiveContainer] Failed to launch container on resource " << resource_selected);
486 // We were not able to launch the container
487 INFOS("[GiveContainer] Cannot launch the container on the following selected resources:")
488 std::vector<std::string>::iterator it;
489 for (it=local_resources.begin() ; it < local_resources.end(); it++ )
490 INFOS("[GiveContainer] " << *it)
494 std::string SALOME_ContainerManager::GetCppBinaryOfKernelContainer() const
496 std::string ret = this->_isSSL ? "SALOME_Container_No_NS_Serv" : "SALOME_Container";
500 std::string SALOME_ContainerManager::GetRunRemoteExecutableScript() const
502 std::string ret = this->_isSSL ? "runRemoteSSL.sh" : "runRemote.sh";
506 Engines::Container_ptr
507 SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& params,
508 const std::string & resource_selected,
509 const std::string & hostname,
510 const std::string & machFile,
511 const std::string & containerNameInNS)
513 std::string user,command,logFilename,tmpFileName;
515 Engines::Container_ptr ret(Engines::Container::_nil());
516 {//start of critical section
517 Utils_Locker lock (&_giveContainerMutex1);
518 // Step 1: type of container: PaCO, Exe, Mpi or Classic
519 // Mpi already tested in step 5, specific code on BuildCommandToLaunch Local/Remote Container methods
520 // TODO -> separates Mpi from Classic/Exe
522 std::string container_exe = this->GetCppBinaryOfKernelContainer();
523 Engines::ContainerParameters local_params(params);
527 CORBA::String_var container_exe_tmp;
528 CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
529 SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
530 if (CORBA::is_nil (Catalog))
532 INFOS("[GiveContainer] Module Catalog is not found -> cannot launch a container");
535 // Loop through component list
536 for(unsigned int i=0; i < local_params.resource_params.componentList.length(); i++)
538 const char* compoi = local_params.resource_params.componentList[i];
539 SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
540 if (CORBA::is_nil (compoInfo))
544 SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
545 container_exe_tmp=compoInfo->implementation_name();
546 if(impl==SALOME_ModuleCatalog::CEXE)
550 INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
551 return Engines::Container::_nil();
553 MESSAGE("[GiveContainer] Exe container found !: " << container_exe_tmp);
554 container_exe = container_exe_tmp.in();
559 catch (ServiceUnreachable&)
561 INFOS("Caught exception: Naming Service Unreachable");
566 INFOS("Caught unknown exception.");
570 // Step 2: test resource
571 // Only if an application directory is set
572 if(hostname != Kernel_Utils::GetHostname() && _isAppliSalomeDefined)
575 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_selected));
576 std::string command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
577 resInfo.UserName, resInfo.AppliPath);
579 // Launch remote command
580 command += " \"ls /tmp >/dev/null 2>&1\"";
581 // Anthony : command is NO MORE launched to improve dramatically time to launch containers
585 // Error on resource - cannot launch commands
586 INFOS("[LaunchContainer] Cannot launch commands on machine " << hostname);
587 INFOS("[LaunchContainer] Command was " << command);
589 INFOS("[LaunchContainer] Command status is " << WEXITSTATUS(status));
591 return Engines::Container::_nil();
595 // Step 3: start a new container
596 // Check if a PaCO container
598 if (std::string(local_params.parallelLib.in()) != "")
600 ret = StartPaCOPPContainer(params, resource_selected);
603 // Other type of containers...
604 MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
605 // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
606 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL && params.isMPI )
607 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
608 // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
609 else if(hostname == Kernel_Utils::GetHostname())
610 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
611 // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
613 command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
615 //redirect stdout and stderr in a file
617 logFilename=GetenvThreadSafeAsString("TEMP");
619 user = GetenvThreadSafeAsString( "USERNAME" );
621 user = GetenvThreadSafeAsString( "USER" );
623 user = GetenvThreadSafeAsString( "LOGNAME" );
625 char* val = GetenvThreadSafe("SALOME_TMP_DIR");
628 struct stat file_info;
629 stat(val, &file_info);
630 bool is_dir = S_ISDIR(file_info.st_mode);
631 if (is_dir)logFilename=val;
632 else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
636 logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
637 std::ostringstream tmp;
638 tmp << "_" << getpid();
639 logFilename += tmp.str();
640 logFilename += ".log" ;
641 command += " > " + logFilename + " 2>&1";
642 MakeTheCommandToBeLaunchedASync(command);
644 // launch container with a system call
645 status=SystemThreadSafe(command.c_str());
646 }//end of critical of section
650 INFOS("[LaunchContainer] command failed (system command status -1): " << command);
651 RmTmpFile(tmpFileName); // command file can be removed here
652 return Engines::Container::_nil();
654 else if (status == 217)
656 INFOS("[LaunchContainer] command failed (system command status 217): " << command);
657 RmTmpFile(tmpFileName); // command file can be removed here
658 return Engines::Container::_nil();
662 // Step 4: Wait for the container
663 int count(GetTimeOutToLoaunchServer());
664 INFOS("[GiveContainer] waiting " << count << " second steps container " << containerNameInNS);
665 while (CORBA::is_nil(ret) && count)
669 MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
670 CORBA::Object_var obj(_NS->Resolve(containerNameInNS.c_str()));
671 ret=Engines::Container::_narrow(obj);
673 if (CORBA::is_nil(ret))
675 INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
679 // Setting log file name
680 logFilename=":"+logFilename;
681 logFilename="@"+Kernel_Utils::GetHostname()+logFilename;//threadsafe
682 logFilename=user+logFilename;
683 ret->logfilename(logFilename.c_str());
684 RmTmpFile(tmpFileName); // command file can be removed here
690 //=============================================================================
691 //! Find a container given constraints (params) on a list of machines (possibleComputers)
692 //! agy : this method is ThreadSafe
696 //=============================================================================
698 Engines::Container_ptr SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const Engines::ResourceList& possibleResources)
700 MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
701 for(unsigned int i=0; i < possibleResources.length();i++)
703 Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
704 if(!CORBA::is_nil(cont))
707 MESSAGE("[FindContainer] no container found");
708 return Engines::Container::_nil();
711 //=============================================================================
712 //! Find a container given constraints (params) on a machine (theMachine)
713 //! agy : this method is ThreadSafe
717 //=============================================================================
719 Engines::Container_ptr
720 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const std::string& resource)
722 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource);
723 std::string hostname(resource_definition.HostName);
724 std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
725 MESSAGE("[FindContainer] Try to find a container " << containerNameInNS << " on resource " << resource);
726 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
729 if(obj->_non_existent())
730 return Engines::Container::_nil();
732 return Engines::Container::_narrow(obj);
734 catch(const CORBA::Exception&)
736 return Engines::Container::_nil();
741 bool isPythonContainer(const char* ContainerName);
743 //=============================================================================
745 * This is no longer valid (C++ container are also python containers)
747 //=============================================================================
748 bool isPythonContainer(const char* ContainerName)
750 return false; // VSR 02/08/2013: Python containers are no more supported
752 size_t len = strlen(ContainerName);
755 if (strcmp(ContainerName + len - 2, "Py") == 0)
761 //=============================================================================
763 * Builds the script to be launched
765 * If SALOME Application not defined ($APPLI),
766 * see BuildTempFileToLaunchRemoteContainer()
768 * Else rely on distant configuration. Command is under the form (example):
769 * ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
770 * SALOME_Container containerName &"
772 * - where user is omitted if not specified in CatalogResources,
773 * - where distant path is always relative to user@machine $HOME, and
774 * equal to $APPLI if not specified in CatalogResources,
775 * - where hostNS is the hostname of CORBA naming server (set by scripts to
776 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
777 * - where portNS is the port used by CORBA naming server (set by scripts to
778 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
779 * - where workingdir is the requested working directory for the container.
780 * If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
782 //=============================================================================
785 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
787 std::string command,tmpFileName;
788 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
789 std::string wdir = params.workingdir.in();
790 if (!_isAppliSalomeDefined)
792 command = getCommandToRunRemoteProcessNoAppli(resInfo.Protocol, resInfo.HostName,
793 resInfo.UserName, resInfo.AppliPath,
798 // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
799 // SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
801 // "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
802 // -- SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
803 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
804 resInfo.UserName, resInfo.AppliPath,
809 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
810 command += " mpirun -np ";
811 std::ostringstream o;
815 command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
816 #elif defined(OPEN_MPI)
817 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
818 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
820 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
821 command += GetenvThreadSafeAsString("OMPI_URI_FILE");
824 command += "-nameserver " + Kernel_Utils::GetHostname();
826 command += " SALOME_MPIContainer ";
829 command += " " +container_exe+ " ";
831 command += _NS->ContainerName(params) + " ";
834 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
835 CORBA::String_var iorNS = _orb->object_to_string(ns);
836 command += std::string(iorNS);
838 else //if(!this->_isSSL)
841 AddOmninamesParams(command);
843 MESSAGE("command =" << command);
848 //=============================================================================
849 //! Return a path to the directory with scripts templates
851 * \return the path pointed by SALOME_KERNEL_SCRIPTS_DIR environment variable, if it is defined,
852 * ${KERNEL_ROOT_DIR}/share/salome/resources/separator/kernel/ScriptsTemplate - otherwise
854 //=============================================================================
855 std::string getScriptTemplateFilePath()
857 auto parseScriptTemplateFilePath = []() -> std::string
859 std::string scriptTemplateFilePath = SALOME_ContainerManager::GetenvThreadSafeAsString("SALOME_KERNEL_SCRIPTS_DIR");
860 if (!scriptTemplateFilePath.empty())
862 return scriptTemplateFilePath;
865 return SALOME_ContainerManager::GetenvThreadSafeAsString("KERNEL_ROOT_DIR") +
866 "/share/salome/resources/kernel/ScriptsTemplate";
870 static const std::string scriptTemplateFilePath = parseScriptTemplateFilePath();
871 return scriptTemplateFilePath;
874 //=============================================================================
875 //! Return a command line constructed based on Python scripts templates
877 * \param theScriptName the name of Python script template
878 * \param theScriptParameters the queue of parameter values
879 * \return the command line constructed according to the given parameters
881 //=============================================================================
882 std::string GetCommandFromTemplate(const std::string& theScriptName,
883 std::queue<std::string>& theScriptParameters)
889 PyObject* mod(PyImport_ImportModule(theScriptName.c_str()));
892 PyObject* sys = PyImport_ImportModule("sys");
893 PyObject* sys_path = PyObject_GetAttrString(sys, "path");
894 PyObject* folder_path = PyUnicode_FromString(getScriptTemplateFilePath().c_str());
895 PyList_Append(sys_path, folder_path);
897 mod = PyImport_ImportModule(theScriptName.c_str());
899 Py_XDECREF(folder_path);
900 Py_XDECREF(sys_path);
906 PyObject* meth(PyObject_GetAttrString(mod, "command"));
914 PyObject* tuple(PyTuple_New(theScriptParameters.size()));
916 auto insert_parameter = [&tuple, &theScriptParameters, &id]()
918 if (!theScriptParameters.empty())
920 PyTuple_SetItem(tuple, ++id, PyUnicode_FromString(theScriptParameters.front().c_str()));
921 theScriptParameters.pop();
925 while (!theScriptParameters.empty())
930 PyObject *args(PyTuple_New(1));
931 PyTuple_SetItem(args, 0, tuple);
933 PyObject *res(PyObject_CallObject(meth, args));
936 command = PyUnicode_AsUTF8(res);
947 MESSAGE("Command from template is ... " << command << std::endl);
950 //=============================================================================
952 //=============================================================================
954 * builds the command to be launched.
956 //=============================================================================
957 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
959 // Prepare name of the script to be used
960 std::string script_name = "SALOME_CM_LOCAL_NO_MPI";
964 script_name = "SALOME_CM_LOCAL_MPI_LAN";
965 #elif defined(OPEN_MPI)
966 script_name = "SALOME_CM_LOCAL_MPI_OPENMPI";
968 script_name = "SALOME_CM_LOCAL_MPI_MPICH";
972 // Prepare parameters to use in the Python script:
973 // 1. All parameters are strings.
974 // 2. For some booleans use "1" = True, "0" = False.
975 // 3. If a parameter is NULL, then its value is "NULL".
977 std::queue<std::string> script_parameters;
979 // ===== Number of processes (key = "nb_proc")
980 script_parameters.push(params.isMPI ? std::to_string(params.nb_proc <= 0 ? 1 : params.nb_proc) : "NULL");
982 // ===== Working directory (key = "workdir") and temporary directory flag (key = "isTmpDir")
983 // A working directory is requested
984 std::string workdir = params.workingdir.in();
985 std::string isTmpDir = std::to_string(0);
986 if (workdir == "$TEMPDIR")
988 // A new temporary directory is requested
989 isTmpDir = std::to_string(1);
990 workdir = Kernel_Utils::GetTmpDir();
992 script_parameters.push(workdir);
993 script_parameters.push(isTmpDir);
995 // ===== Server name (key = "name_server")
996 script_parameters.push(Kernel_Utils::GetHostname());
998 // ===== Container (key = "container")
999 std::string container;
1002 container = isPythonContainer(params.container_name) ? "pyMPI SALOME_ContainerPy.py" : "SALOME_MPIContainer";
1006 container = isPythonContainer(params.container_name) ? "SALOME_ContainerPy.py" : container_exe;
1008 script_parameters.push(container);
1010 // ===== Container name (key = "container_name")
1011 script_parameters.push(_NS->ContainerName(params));
1013 // ===== LIBBATCH node file (key = "libbatch_nodefile")
1014 script_parameters.push(std::to_string(GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL ? 1 : 0));
1016 // ===== Machine file (key = "machine_file")
1017 script_parameters.push(machinesFile.empty() ? "NULL" : machinesFile);
1019 // ===== OMPI uri file (key = "ompi_uri_file")
1020 std::string ompi_uri_file = GetenvThreadSafeAsString("OMPI_URI_FILE");
1021 script_parameters.push(ompi_uri_file.empty() ? "NULL" : ompi_uri_file);
1023 std::string command_from_template = GetCommandFromTemplate(script_name, script_parameters);
1025 std::ostringstream o;
1026 o << command_from_template << " ";
1028 //==================================================================================== */
1032 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1033 CORBA::String_var iorNS = _orb->object_to_string(ns);
1039 AddOmninamesParams(o);
1042 tmpFileName = BuildTemporaryFileName();
1043 std::ofstream command_file( tmpFileName.c_str() );
1044 command_file << o.str();
1045 command_file.close();
1048 chmod(tmpFileName.c_str(), 0x1ED);
1051 std::string command = tmpFileName;
1052 MESSAGE("Command is file ... " << command);
1053 MESSAGE("Command is ... " << o.str());
1058 //=============================================================================
1060 * removes the generated temporary file in case of a remote launch.
1061 * This method is thread safe
1063 //=============================================================================
1065 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
1067 size_t length = tmpFileName.size();
1071 std::string command = "del /F ";
1073 std::string command = "rm ";
1076 command += tmpFileName.substr(0, length - 3 );
1078 command += tmpFileName;
1080 SystemThreadSafe(command.c_str());
1081 //if dir is empty - remove it
1082 std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
1083 if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
1086 command = "del /F " + tmp_dir;
1088 command = "rmdir " + tmp_dir;
1090 SystemThreadSafe(command.c_str());
1095 //=============================================================================
1097 * add to command all options relative to naming service.
1099 //=============================================================================
1101 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
1103 std::ostringstream oss;
1104 AddOmninamesParams(oss);
1108 //=============================================================================
1110 * add to command all options relative to naming service.
1112 //=============================================================================
1114 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
1116 AddOmninamesParams(fileStream,_NS);
1119 //=============================================================================
1121 * add to command all options relative to naming service.
1123 //=============================================================================
1125 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
1127 SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
1130 CORBA::String_var iorstr(nsTrad->getIORaddr());
1131 fileStream << "ORBInitRef NameService=";
1132 fileStream << iorstr;
1136 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
1139 command = "%PYTHONBIN% -c \"import subprocess ; subprocess.Popen(r'" + command + "').pid\"";
1145 int SALOME_ContainerManager::GetTimeOutToLoaunchServer()
1147 int count(TIME_OUT_TO_LAUNCH_CONT);
1148 if (GetenvThreadSafe("TIMEOUT_TO_LAUNCH_CONTAINER") != 0)
1150 std::string new_count_str(GetenvThreadSafeAsString("TIMEOUT_TO_LAUNCH_CONTAINER"));
1152 std::istringstream ss(new_count_str);
1153 if (!(ss >> new_count))
1155 INFOS("[LaunchContainer] TIMEOUT_TO_LAUNCH_CONTAINER should be an int");
1163 void SALOME_ContainerManager::SleepInSecond(int ellapseTimeInSecond)
1166 sleep( ellapseTimeInSecond ) ;
1168 int timeInMS(1000*ellapseTimeInSecond);
1173 //=============================================================================
1175 * generate a file name in /tmp directory
1177 //=============================================================================
1179 std::string SALOME_ContainerManager::BuildTemporaryFileName()
1181 //build more complex file name to support multiple salome session
1182 std::string aFileName = Kernel_Utils::GetTmpFileName();
1183 std::ostringstream str_pid;
1184 str_pid << ::getpid();
1185 aFileName = aFileName + "-" + str_pid.str();
1189 aFileName += ".bat";
1194 //=============================================================================
1196 * Builds in a temporary file the script to be launched.
1198 * Used if SALOME Application ($APPLI) is not defined.
1199 * The command is build with data from CatalogResources, in which every path
1200 * used on remote computer must be defined.
1202 //=============================================================================
1204 std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const std::string& resource_name, const Engines::ContainerParameters& params, std::string& tmpFileName) const
1208 tmpFileName = BuildTemporaryFileName();
1209 std::ofstream tempOutputFile;
1210 tempOutputFile.open(tmpFileName.c_str(), std::ofstream::out );
1211 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
1212 tempOutputFile << "#! /bin/sh" << std::endl;
1216 tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1217 //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1223 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
1225 tempOutputFile << "mpirun -np ";
1227 tempOutputFile << nbproc << " ";
1229 tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1230 #elif defined(OPEN_MPI)
1231 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
1232 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1234 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1235 tempOutputFile << GetenvThreadSafeAsString("OMPI_URI_FILE");
1237 #elif defined(MPICH)
1238 tempOutputFile << "-nameserver " + Kernel_Utils::GetHostname();
1242 tempOutputFile << GetenvThreadSafeAsString("KERNEL_ROOT_DIR") << "/bin/salome/";
1246 if (isPythonContainer(params.container_name))
1247 tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1249 tempOutputFile << " SALOME_MPIContainer ";
1254 if (isPythonContainer(params.container_name))
1255 tempOutputFile << "SALOME_ContainerPy.py ";
1257 tempOutputFile << "SALOME_Container ";
1260 tempOutputFile << _NS->ContainerName(params) << " -";
1261 AddOmninamesParams(tempOutputFile);
1262 tempOutputFile << " &" << std::endl;
1263 tempOutputFile.flush();
1264 tempOutputFile.close();
1266 chmod(tmpFileName.c_str(), 0x1ED);
1269 // --- Build command
1271 std::string command;
1273 if (resInfo.Protocol == rsh)
1276 std::string commandRcp = "rcp ";
1277 commandRcp += tmpFileName;
1279 commandRcp += resInfo.HostName;
1281 commandRcp += tmpFileName;
1282 status = SystemThreadSafe(commandRcp.c_str());
1285 else if (resInfo.Protocol == ssh)
1288 std::string commandRcp = "scp ";
1289 commandRcp += tmpFileName;
1291 commandRcp += resInfo.HostName;
1293 commandRcp += tmpFileName;
1294 status = SystemThreadSafe(commandRcp.c_str());
1297 else if (resInfo.Protocol == srun)
1299 command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
1300 std::string commandRcp = "rcp ";
1301 commandRcp += tmpFileName;
1303 commandRcp += resInfo.HostName;
1305 commandRcp += tmpFileName;
1306 status = SystemThreadSafe(commandRcp.c_str());
1309 throw SALOME_Exception("Unknown protocol");
1312 throw SALOME_Exception("Error of connection on remote host");
1314 command += resInfo.HostName;
1316 command += tmpFileName;
1324 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile) const
1327 std::string zeronode;
1328 std::string command;
1329 std::string tmpFile = BuildTemporaryFileName();
1330 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(machine));
1332 if(resInfo.Protocol == sh)
1334 return resInfo.HostName;
1337 if( GetenvThreadSafe("LIBBATCH_NODEFILE") == NULL )
1339 if (_isAppliSalomeDefined)
1341 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
1342 resInfo.UserName, resInfo.AppliPath);
1343 command += " mpirun -np 1 hostname -s > " + tmpFile;
1346 command = "mpirun -np 1 hostname -s > " + tmpFile;
1349 command = "mpirun -np 1 -machinefile " + machinesFile + " hostname -s > " + tmpFile;
1351 status = SystemThreadSafe(command.c_str());
1353 std::ifstream fp(tmpFile.c_str(),std::ios::in);
1354 while(fp >> zeronode);
1362 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1365 std::string nodesFile = GetenvThreadSafeAsString("LIBBATCH_NODEFILE");
1366 std::string machinesFile = Kernel_Utils::GetTmpFileName();
1367 std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1368 std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1370 _numInstanceMutex.lock();
1372 for(int i=0;i<_nbprocUsed;i++)
1375 for(int i=0;i<nbproc;i++)
1377 fpo << tmp << std::endl;
1379 throw SALOME_Exception("You need more processors than batch session have allocated for you! Unable to launch the mpi container: ");
1381 _nbprocUsed += nbproc;
1385 _numInstanceMutex.unlock();
1387 return machinesFile;
1391 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessNoAppli(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1393 return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE","salome shell --",protocol,hostname,username,applipath,workdir);
1396 std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1398 return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE_OLD",this->GetRunRemoteExecutableScript(),protocol,hostname,username,applipath,workdir);
1401 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessCommon(const std::string& templateName,
1402 const std::string& remoteScript,
1403 AccessProtocolType protocol,
1404 const std::string & hostname,
1405 const std::string & username,
1406 const std::string & applipath,
1407 const std::string & workdir) const
1409 std::ostringstream command;
1411 // Prepare parameters to use in the Python script:
1412 // 1. All parameters are strings.
1413 // 2. For some booleans use "1" = True, "0" = False.
1414 // 3. If a parameter is NULL, then its value is "NULL".
1416 std::queue<std::string> script_parameters;
1418 // ===== Protocol (key = "protocol")
1419 std::string strProtocol;
1422 case rsh: strProtocol = "rsh"; break;
1423 case ssh: strProtocol = "ssh"; break;
1424 case srun: strProtocol = "srun"; break;
1425 case pbsdsh: strProtocol = "pbsdsh"; break;
1426 case blaunch: strProtocol = "blaunch"; break;
1428 throw SALOME_Exception("Unknown protocol");
1430 script_parameters.push(strProtocol);
1432 // ===== User name (key = "user")
1433 script_parameters.push(username.empty() ? "NULL" : username);
1435 // ===== Host name (key = "host")
1436 script_parameters.push(hostname.empty() ? "NULL" : hostname);
1439 // ===== Remote APPLI path (key = "appli")
1440 script_parameters.push(applipath.empty() ? GetenvThreadSafeAsString("APPLI") : applipath);
1444 ASSERT(GetenvThreadSafe("NSHOST"));
1445 ASSERT(GetenvThreadSafe("NSPORT"));
1448 struct stat statbuf;
1449 std::string appli_mode = (stat(GetenvThreadSafe("APPLI"), &statbuf) == 0 && S_ISREG(statbuf.st_mode)) ? "launcher" : "dir";
1451 // ===== Working directory (key = "workdir")
1452 script_parameters.push(workdir == "$TEMPDIR" ? "\\$TEMPDIR" : workdir);
1454 // ===== SSL (key = "ssl")
1455 script_parameters.push(this->_isSSL ? "1" : "0");
1457 // ===== Hostname of CORBA name server (key = "nshost")
1458 std::string nshost = GetenvThreadSafeAsString("NSHOST");
1459 script_parameters.push(nshost.empty() ? "NULL" : nshost);
1461 // ===== Port of CORBA name server (key = "nsport")
1462 std::string nsport = GetenvThreadSafeAsString("NSPORT");
1463 script_parameters.push(nsport.empty() ? "NULL" : nsport);
1465 // ===== Remote script (key = "remote_script")
1466 script_parameters.push(remoteScript.empty() ? "NONE" : remoteScript);
1468 // ===== Naming service (key = "naming_service")
1469 std::string namingService = "NONE";
1472 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1473 CORBA::String_var iorNS = _orb->object_to_string(ns);
1474 namingService = iorNS;
1476 script_parameters.push(namingService);
1478 // ===== APPLI mode (key = "appli_mode")
1479 // $APPLI points either to an application directory, or to a salome launcher file
1480 // we prepare the remote command according to the case
1481 script_parameters.push(appli_mode);
1483 command << GetCommandFromTemplate(templateName, script_parameters);
1485 return command.str();
1489 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1493 // Step 1 : check ContainerParameters
1494 // Check container_name, has to be defined
1495 if (std::string(params.container_name.in()) == "")
1497 INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1500 // Check parallelLib
1501 std::string parallelLib = params.parallelLib.in();
1502 if (parallelLib != "Mpi" && parallelLib != "Dummy")
1504 INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1505 INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1506 INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1510 if (params.nb_proc <= 0)
1512 INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1516 // Step 2 : check resource_selected
1517 const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1518 //std::string protocol = resource_definition->protocol.in();
1519 std::string username = resource_definition.UserName;
1520 std::string applipath = resource_definition.AppliPath;
1522 //if (protocol == "" || username == "" || applipath == "")
1523 if (username == "" || applipath == "")
1525 INFOS("[checkPaCOParameters] resource selected is not well defined");
1526 INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1527 INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1528 INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1529 INFOS("[checkPaCOParameters] resource username: " << username);
1530 INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1538 * :WARNING: Do not directly convert returned value to std::string
1539 * This function may return NULL if env variable is not defined.
1540 * And std::string(NULL) causes undefined behavior.
1541 * Use GetenvThreadSafeAsString to properly get a std::string.
1543 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1544 {// getenv is not thread safe. See man 7 pthread.
1545 Utils_Locker lock (&_getenvMutex);
1546 return getenv(name);
1550 * Return env variable as a std::string.
1551 * Return empty string if env variable is not set.
1553 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1555 char* var = GetenvThreadSafe(name);
1556 return var ? std::string(var) : std::string();
1559 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1561 Utils_Locker lock (&_systemMutex);
1562 return system(command);
1565 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1567 Utils_Locker lock(&_systemMutex);
1568 if(command.size()<1)
1569 throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1571 pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1573 pid_t pid = -1; //Throw SALOME_Exception on Windows
1575 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1577 std::size_t sz(command.size());
1578 char **args = new char *[sz+1];
1579 for(std::size_t i=0;i<sz;i++)
1580 args[i] = strdup(command[i].c_str());
1582 execvp( command[0].c_str() , args );
1583 std::ostringstream oss;
1584 oss << "Error when launching " << command[0];
1585 throw SALOME_Exception(oss.str().c_str()); // execvp failed
1589 throw SALOME_Exception("fork() failed");
1591 else // I'm a parent
1597 #ifdef WITH_PACO_PARALLEL
1599 //=============================================================================
1601 * Start a suitable PaCO++ Parallel Container in a list of machines.
1602 * \param params Container Parameters required for the container
1603 * \return CORBA container reference.
1605 //=============================================================================
1606 Engines::Container_ptr
1607 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1608 std::string resource_selected)
1610 CORBA::Object_var obj;
1611 PaCO::InterfaceManager_var container_proxy;
1612 Engines::Container_ptr ret = Engines::Container::_nil();
1613 Engines::ContainerParameters params(params_const);
1614 params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1616 // Step 0 : Check parameters
1617 if (!checkPaCOParameters(params, resource_selected))
1619 INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1623 // Step 1 : Starting a new parallel container !
1624 INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1625 INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1627 // Step 2 : Get a MachineFile for the parallel container
1628 std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1630 params.parallelLib.in());
1632 if (machine_file_name == "")
1634 INFOS("[StartPaCOPPContainer] Machine file generation failed");
1638 // Step 3 : starting parallel container proxy
1639 std::string command_proxy("");
1640 std::string proxy_machine;
1643 command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1645 catch(const SALOME_Exception & ex)
1647 INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1651 obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1652 if (CORBA::is_nil(obj))
1654 INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1657 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1658 MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1660 // Step 4 : starting parallel container nodes
1661 std::string command_nodes("");
1662 SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1665 command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1667 catch(const SALOME_Exception & ex)
1669 INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1674 std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1675 bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1678 INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1679 // Il faut tuer le proxy
1682 Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1687 INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1692 // Step 4 : connecting nodes and the proxy to actually create a parallel container
1693 for (int i = 0; i < params.nb_proc; i++)
1695 std::ostringstream tmp;
1697 std::string proc_number = tmp.str();
1698 std::string container_node_name = container_generic_node_name + proc_number;
1700 std::string theNodeMachine(nodes_machines[i]);
1701 std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1702 obj = _NS->Resolve(containerNameInNS.c_str());
1703 if (CORBA::is_nil(obj))
1705 INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1706 INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1711 MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1712 PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1714 MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1716 catch(CORBA::SystemException& e)
1718 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1719 INFOS("CORBA::SystemException : " << e);
1722 catch(CORBA::Exception& e)
1724 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1725 INFOS("CORBA::Exception" << e);
1730 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1731 INFOS("Unknown exception !");
1736 // Step 5 : starting parallel container
1739 MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1740 container_proxy->start();
1741 MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1742 ret = Engines::Container::_narrow(container_proxy);
1744 catch(CORBA::SystemException& e)
1746 INFOS("Caught CORBA::SystemException. : " << e);
1748 catch(PortableServer::POA::ServantAlreadyActive&)
1750 INFOS("Caught CORBA::ServantAlreadyActiveException");
1752 catch(CORBA::Exception&)
1754 INFOS("Caught CORBA::Exception.");
1756 catch(std::exception& exc)
1758 INFOS("Caught std::exception - "<<exc.what());
1762 INFOS("Caught unknown exception.");
1768 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1769 std::string machine_file_name,
1770 std::string & proxy_hostname)
1772 // In the proxy case, we always launch a Dummy Proxy
1773 std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1774 std::string container_name = params.container_name.in();
1776 // Convert nb_proc in string
1777 std::ostringstream tmp_string;
1778 tmp_string << params.nb_proc;
1779 std::string nb_proc_str = tmp_string.str();
1781 // Get resource definition
1782 ParserResourcesType resource_definition =
1783 _resManager->GetResourceDefinition(params.resource_params.name.in());
1786 std::string hostname;
1787 std::ifstream machine_file(machine_file_name.c_str());
1788 std::getline(machine_file, hostname, ' ');
1789 size_t found = hostname.find('\n');
1790 if (found!=std::string::npos)
1791 hostname.erase(found, 1); // Remove \n
1792 proxy_hostname = hostname;
1793 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1796 bool remote_execution = false;
1797 if (hostname != std::string(Kernel_Utils::GetHostname()))
1799 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1800 remote_execution = true;
1804 std::string log_type("");
1805 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1809 // Generating the command
1810 std::string command_begin("");
1811 std::string command_end("");
1812 std::ostringstream command;
1814 LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1815 command << command_begin;
1817 // Adding connection command
1818 // We can only have a remote execution with
1819 // a SALOME application
1820 if (remote_execution)
1822 ASSERT(GetenvThreadSafe("NSHOST"));
1823 ASSERT(GetenvThreadSafe("NSPORT"));
1825 command << resource_definition.getAccessProtocolTypeStr();
1827 command << resource_definition.UserName;
1828 command << " " << hostname;
1829 command << " " << resource_definition.AppliPath;
1830 command << "/runRemote.sh ";
1831 command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1832 command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1835 command << exe_name;
1836 command << " " << container_name;
1837 command << " Dummy";
1838 command << " " << hostname;
1839 command << " " << nb_proc_str;
1841 AddOmninamesParams(command);
1844 command << command_end;
1845 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1847 return command.str();
1851 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1852 const std::string & machine_file_name,
1853 SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1854 const std::string & proxy_hostname)
1857 std::string exe_name = "SALOME_ParallelContainerNode";
1858 exe_name += params.parallelLib.in();
1859 std::string container_name = params.container_name.in();
1861 // Convert nb_proc in string
1862 std::ostringstream nb_proc_stream;
1863 nb_proc_stream << params.nb_proc;
1865 // Get resource definition
1866 ParserResourcesType resource_definition =
1867 _resManager->GetResourceDefinition(params.resource_params.name.in());
1870 std::string log_type("");
1871 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1875 // Now the command is different according to paralleLib
1876 std::ostringstream command_nodes;
1877 std::ifstream machine_file(machine_file_name.c_str());
1878 if (std::string(params.parallelLib.in()) == "Dummy")
1880 for (int i= 0; i < params.nb_proc; i++)
1883 std::string hostname;
1884 std::getline(machine_file, hostname);
1885 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1888 bool remote_execution = false;
1889 if (hostname != std::string(Kernel_Utils::GetHostname()))
1891 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1892 remote_execution = true;
1895 // For each node we have a new command
1896 // Generating the command
1897 std::ostringstream command_node_stream;
1898 std::string command_node_begin("");
1899 std::string command_node_end("");
1900 std::ostringstream node_number;
1902 std::string container_node_name = container_name + node_number.str();
1903 LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1905 // Adding connection command
1906 // We can only have a remote execution with
1907 // a SALOME application
1908 if (remote_execution)
1910 ASSERT(GetenvThreadSafe("NSHOST"));
1911 ASSERT(GetenvThreadSafe("NSPORT"));
1913 command_node_stream << resource_definition.getAccessProtocolTypeStr();
1914 command_node_stream << " -l ";
1915 command_node_stream << resource_definition.UserName;
1916 command_node_stream << " " << hostname;
1917 command_node_stream << " " << resource_definition.AppliPath;
1918 command_node_stream << "/runRemote.sh ";
1919 command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1920 command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1923 command_node_stream << exe_name;
1924 command_node_stream << " " << container_name;
1925 command_node_stream << " " << params.parallelLib.in();
1926 command_node_stream << " " << proxy_hostname;
1927 command_node_stream << " " << node_number.str();
1928 command_node_stream << " -";
1929 AddOmninamesParams(command_node_stream);
1931 command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1932 vect_machine.push_back(hostname);
1936 else if (std::string(params.parallelLib.in()) == "Mpi")
1939 std::string hostname;
1940 std::getline(machine_file, hostname, ' ');
1941 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1944 bool remote_execution = false;
1945 if (hostname != std::string(Kernel_Utils::GetHostname()))
1947 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1948 remote_execution = true;
1951 // In case of Mpi and Remote, we copy machine_file in the applipath
1952 // scp mpi_machine_file user@machine:Path
1953 std::ostringstream command_remote_stream;
1954 std::string::size_type last = machine_file_name.find_last_of("/");
1955 if (last == std::string::npos)
1958 if (resource_definition.Protocol == rsh)
1959 command_remote_stream << "rcp ";
1961 command_remote_stream << "scp ";
1962 command_remote_stream << machine_file_name << " ";
1963 command_remote_stream << resource_definition.UserName << "@";
1964 command_remote_stream << hostname << ":" << resource_definition.AppliPath;
1965 command_remote_stream << "/" << machine_file_name.substr(last+1);
1967 int status = SystemThreadSafe(command_remote_stream.str().c_str());
1970 INFOS("copy of the MPI machine file failed ! - sorry !");
1974 // Generating the command
1975 std::string command_begin("");
1976 std::string command_end("");
1978 LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1979 command_nodes << command_begin;
1981 // Adding connection command
1982 // We can only have a remote execution with
1983 // a SALOME application
1984 if (remote_execution)
1986 ASSERT(GetenvThreadSafe("NSHOST"));
1987 ASSERT(GetenvThreadSafe("NSPORT"));
1989 command_nodes << resource_definition.getAccessProtocolTypeStr();
1990 command_nodes << " -l ";
1991 command_nodes << resource_definition.UserName;
1992 command_nodes << " " << hostname;
1993 command_nodes << " " << resource_definition.AppliPath;
1994 command_nodes << "/runRemote.sh ";
1995 command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1996 command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1999 if (resource_definition.mpi == lam)
2001 command_nodes << "mpiexec -ssi boot ";
2002 command_nodes << "-machinefile " << machine_file_name << " ";
2003 command_nodes << "-n " << params.nb_proc;
2007 command_nodes << "mpirun -np " << params.nb_proc;
2009 command_nodes << " " << exe_name;
2010 command_nodes << " " << container_name;
2011 command_nodes << " " << params.parallelLib.in();
2012 command_nodes << " " << proxy_hostname;
2013 command_nodes << " -";
2014 AddOmninamesParams(command_nodes);
2016 // We don't put hostname, because nodes are registered in the resource of the proxy
2017 for (int i= 0; i < params.nb_proc; i++)
2018 vect_machine.push_back(proxy_hostname);
2020 command_nodes << command_end;
2022 return command_nodes.str();
2026 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
2027 const std::string & exe_type,
2028 const std::string & container_name,
2029 const std::string & hostname,
2030 std::string & begin,
2033 if(log_type == "xterm")
2035 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2038 else if(log_type == "xterm_debug")
2040 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2045 // default into a file...
2046 std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
2047 std::string user = GetenvThreadSafeAsString("USER");
2049 user = GetenvThreadSafeAsString("LOGNAME");
2050 logFilename += user + ".log";
2051 end = " > " + logFilename + " 2>&1 & ";
2056 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
2057 const Engines::ContainerParameters& params,
2058 const std::string & hostname)
2060 PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
2062 MESSAGE("[LaunchPaCOProxyContainer] Launch command");
2063 int status = SystemThreadSafe(command.c_str());
2065 INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
2066 return container_proxy;
2068 else if (status == 217) {
2069 INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
2070 return container_proxy;
2073 int count(GetTimeOutToLoaunchServer());
2074 CORBA::Object_var obj = CORBA::Object::_nil();
2075 std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
2077 MESSAGE("[LaunchParallelContainer] Waiting for Parallel Container proxy : " << containerNameInNS);
2079 while (CORBA::is_nil(obj) && count)
2083 obj = _NS->Resolve(containerNameInNS.c_str());
2088 container_proxy = PaCO::InterfaceManager::_narrow(obj);
2090 catch(CORBA::SystemException& e)
2092 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2093 INFOS("CORBA::SystemException : " << e);
2094 return container_proxy;
2096 catch(CORBA::Exception& e)
2098 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2099 INFOS("CORBA::Exception" << e);
2100 return container_proxy;
2104 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2105 INFOS("Unknown exception !");
2106 return container_proxy;
2108 if (CORBA::is_nil(container_proxy))
2110 INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
2111 return container_proxy;
2116 //=============================================================================
2117 /*! This method launches the parallel container.
2118 * It will may be placed on the resources manager.
2120 * \param command to launch
2121 * \param container's parameters
2122 * \param name of the container
2124 * \return CORBA container reference
2126 //=============================================================================
2128 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
2129 const Engines::ContainerParameters& params,
2130 const std::string& name,
2131 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
2133 INFOS("[LaunchPaCONodeContainer] Launch command");
2134 int status = SystemThreadSafe(command.c_str());
2136 INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
2139 else if (status == 217) {
2140 INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
2144 INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
2145 // We are waiting all the nodes
2146 for (int i = 0; i < params.nb_proc; i++)
2148 CORBA::Object_var obj = CORBA::Object::_nil();
2149 std::string theMachine(vect_machine[i]);
2151 std::ostringstream tmp;
2153 std::string proc_number = tmp.str();
2154 std::string container_node_name = name + proc_number;
2155 std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
2156 INFOS("[LaunchPaCONodeContainer] Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
2157 int count(GetTimeOutToLoaunchServer());
2158 while (CORBA::is_nil(obj) && count) {
2161 obj = _NS->Resolve(containerNameInNS.c_str());
2163 if (CORBA::is_nil(obj))
2165 INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2174 Engines::Container_ptr
2175 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2176 std::string /*resource_selected*/)
2178 Engines::Container_ptr ret = Engines::Container::_nil();
2179 INFOS("[StarPaCOPPContainer] is disabled !");
2180 INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2185 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2186 std::string /*machine_file_name*/,
2187 std::string & /*proxy_hostname*/)
2193 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2194 const std::string & /*machine_file_name*/,
2195 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2196 const std::string & /*proxy_hostname*/)
2201 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2202 const std::string & /*exe_type*/,
2203 const std::string & /*container_name*/,
2204 const std::string & /*hostname*/,
2205 std::string & /*begin*/,
2206 std::string & /*end*/)
2211 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2212 const Engines::ContainerParameters& /*params*/,
2213 const std::string& /*hostname*/)
2215 CORBA::Object_ptr ret = CORBA::Object::_nil();
2220 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2221 const Engines::ContainerParameters& /*params*/,
2222 const std::string& /*name*/,
2223 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)