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 )
608 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
609 MESSAGE("[LaunchContainer] LIBBATCH_NODEFILE : \"" << command << "\"");
611 // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
612 else if(hostname == Kernel_Utils::GetHostname())
614 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
615 MESSAGE("[LaunchContainer] hostname local : \"" << command << "\"");
617 // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
620 command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
621 MESSAGE("[LaunchContainer] remote : \"" << command << "\"");
624 //redirect stdout and stderr in a file
626 logFilename=GetenvThreadSafeAsString("TEMP");
628 user = GetenvThreadSafeAsString( "USERNAME" );
630 user = GetenvThreadSafeAsString( "USER" );
632 user = GetenvThreadSafeAsString( "LOGNAME" );
634 char* val = GetenvThreadSafe("SALOME_TMP_DIR");
637 struct stat file_info;
638 stat(val, &file_info);
639 bool is_dir = S_ISDIR(file_info.st_mode);
640 if (is_dir)logFilename=val;
641 else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
645 logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
646 std::ostringstream tmp;
647 tmp << "_" << getpid();
648 logFilename += tmp.str();
649 logFilename += ".log" ;
650 command += " > " + logFilename + " 2>&1";
651 MakeTheCommandToBeLaunchedASync(command);
653 MESSAGE("[LaunchContainer] SYSTEM COMMAND that will be launched : \"" << command << "\"");
654 // launch container with a system call
655 status=SystemThreadSafe(command.c_str());
656 }//end of critical of section
660 INFOS("[LaunchContainer] command failed (system command status -1): " << command);
661 RmTmpFile(tmpFileName); // command file can be removed here
662 return Engines::Container::_nil();
664 else if (status == 217)
666 INFOS("[LaunchContainer] command failed (system command status 217): " << command);
667 RmTmpFile(tmpFileName); // command file can be removed here
668 return Engines::Container::_nil();
672 // Step 4: Wait for the container
673 int count(GetTimeOutToLoaunchServer());
674 INFOS("[GiveContainer] waiting " << count << " second steps container " << containerNameInNS);
675 while (CORBA::is_nil(ret) && count)
679 MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
680 CORBA::Object_var obj(_NS->Resolve(containerNameInNS.c_str()));
681 ret=Engines::Container::_narrow(obj);
683 if (CORBA::is_nil(ret))
685 INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
689 // Setting log file name
690 logFilename=":"+logFilename;
691 logFilename="@"+Kernel_Utils::GetHostname()+logFilename;//threadsafe
692 logFilename=user+logFilename;
693 ret->logfilename(logFilename.c_str());
694 RmTmpFile(tmpFileName); // command file can be removed here
700 //=============================================================================
701 //! Find a container given constraints (params) on a list of machines (possibleComputers)
702 //! agy : this method is ThreadSafe
706 //=============================================================================
708 Engines::Container_ptr SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const Engines::ResourceList& possibleResources)
710 MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
711 for(unsigned int i=0; i < possibleResources.length();i++)
713 Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
714 if(!CORBA::is_nil(cont))
717 MESSAGE("[FindContainer] no container found");
718 return Engines::Container::_nil();
721 //=============================================================================
722 //! Find a container given constraints (params) on a machine (theMachine)
723 //! agy : this method is ThreadSafe
727 //=============================================================================
729 Engines::Container_ptr
730 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const std::string& resource)
732 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource);
733 std::string hostname(resource_definition.HostName);
734 std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
735 MESSAGE("[FindContainer] Try to find a container " << containerNameInNS << " on resource " << resource);
736 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
739 if(obj->_non_existent())
740 return Engines::Container::_nil();
742 return Engines::Container::_narrow(obj);
744 catch(const CORBA::Exception&)
746 return Engines::Container::_nil();
751 bool isPythonContainer(const char* ContainerName);
753 //=============================================================================
755 * This is no longer valid (C++ container are also python containers)
757 //=============================================================================
758 bool isPythonContainer(const char* ContainerName)
760 return false; // VSR 02/08/2013: Python containers are no more supported
762 size_t len = strlen(ContainerName);
765 if (strcmp(ContainerName + len - 2, "Py") == 0)
771 //=============================================================================
773 * Builds the script to be launched
775 * If SALOME Application not defined ($APPLI),
776 * see BuildTempFileToLaunchRemoteContainer()
778 * Else rely on distant configuration. Command is under the form (example):
779 * ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
780 * SALOME_Container containerName &"
782 * - where user is omitted if not specified in CatalogResources,
783 * - where distant path is always relative to user@machine $HOME, and
784 * equal to $APPLI if not specified in CatalogResources,
785 * - where hostNS is the hostname of CORBA naming server (set by scripts to
786 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
787 * - where portNS is the port used by CORBA naming server (set by scripts to
788 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
789 * - where workingdir is the requested working directory for the container.
790 * If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
792 //=============================================================================
795 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
797 std::string command,tmpFileName;
798 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
799 std::string wdir = params.workingdir.in();
800 if (!_isAppliSalomeDefined)
802 MESSAGE("[BuildCommandToLaunchRemoteContainer] NO APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
803 command = getCommandToRunRemoteProcessNoAppli(resInfo.Protocol, resInfo.HostName,
804 resInfo.UserName, resInfo.AppliPath,
809 MESSAGE("[BuildCommandToLaunchRemoteContainer] WITH APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
810 // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
811 // SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
813 // "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
814 // -- SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
815 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
816 resInfo.UserName, resInfo.AppliPath,
821 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
822 command += " mpirun -np ";
823 std::ostringstream o;
827 command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
828 #elif defined(OPEN_MPI)
829 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
830 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
832 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
833 command += GetenvThreadSafeAsString("OMPI_URI_FILE");
836 command += "-nameserver " + Kernel_Utils::GetHostname();
838 command += " SALOME_MPIContainer ";
841 command += " " +container_exe+ " ";
843 command += _NS->ContainerName(params) + " ";
846 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
847 CORBA::String_var iorNS = _orb->object_to_string(ns);
848 command += std::string(iorNS);
850 else //if(!this->_isSSL)
853 AddOmninamesParams(command);
855 MESSAGE("command =" << command);
860 //=============================================================================
861 //! Return a path to the directory with scripts templates
863 * \return the path pointed by SALOME_KERNEL_SCRIPTS_DIR environment variable, if it is defined,
864 * ${KERNEL_ROOT_DIR}/share/salome/resources/separator/kernel/ScriptsTemplate - otherwise
866 //=============================================================================
867 std::string getScriptTemplateFilePath()
869 auto parseScriptTemplateFilePath = []() -> std::string
871 std::string scriptTemplateFilePath = SALOME_ContainerManager::GetenvThreadSafeAsString("SALOME_KERNEL_SCRIPTS_DIR");
872 if (!scriptTemplateFilePath.empty())
874 return scriptTemplateFilePath;
877 return SALOME_ContainerManager::GetenvThreadSafeAsString("KERNEL_ROOT_DIR") +
878 "/share/salome/resources/kernel/ScriptsTemplate";
882 static const std::string scriptTemplateFilePath = parseScriptTemplateFilePath();
883 return scriptTemplateFilePath;
886 //=============================================================================
887 //! Return a command line constructed based on Python scripts templates
889 * \param theScriptName the name of Python script template
890 * \param theScriptParameters the queue of parameter values
891 * \return the command line constructed according to the given parameters
893 //=============================================================================
894 std::string GetCommandFromTemplate(const std::string& theScriptName,
895 std::queue<std::string>& theScriptParameters)
901 PyObject* mod(PyImport_ImportModule(theScriptName.c_str()));
904 PyObject* sys = PyImport_ImportModule("sys");
905 PyObject* sys_path = PyObject_GetAttrString(sys, "path");
906 PyObject* folder_path = PyUnicode_FromString(getScriptTemplateFilePath().c_str());
907 PyList_Append(sys_path, folder_path);
909 mod = PyImport_ImportModule(theScriptName.c_str());
911 Py_XDECREF(folder_path);
912 Py_XDECREF(sys_path);
918 PyObject* meth(PyObject_GetAttrString(mod, "command"));
926 PyObject* tuple(PyTuple_New(theScriptParameters.size()));
928 auto insert_parameter = [&tuple, &theScriptParameters, &id]()
930 if (!theScriptParameters.empty())
932 PyTuple_SetItem(tuple, ++id, PyUnicode_FromString(theScriptParameters.front().c_str()));
933 theScriptParameters.pop();
937 while (!theScriptParameters.empty())
942 PyObject *args(PyTuple_New(1));
943 PyTuple_SetItem(args, 0, tuple);
945 PyObject *res(PyObject_CallObject(meth, args));
948 command = PyUnicode_AsUTF8(res);
959 MESSAGE("Command from template is ... " << command << std::endl);
962 //=============================================================================
964 //=============================================================================
966 * builds the command to be launched.
968 //=============================================================================
969 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
971 // Prepare name of the script to be used
972 std::string script_name = "SALOME_CM_LOCAL_NO_MPI";
976 script_name = "SALOME_CM_LOCAL_MPI_LAN";
977 #elif defined(OPEN_MPI)
978 script_name = "SALOME_CM_LOCAL_MPI_OPENMPI";
980 script_name = "SALOME_CM_LOCAL_MPI_MPICH";
984 // Prepare parameters to use in the Python script:
985 // 1. All parameters are strings.
986 // 2. For some booleans use "1" = True, "0" = False.
987 // 3. If a parameter is NULL, then its value is "NULL".
989 std::queue<std::string> script_parameters;
991 // ===== Number of processes (key = "nb_proc")
992 script_parameters.push(params.isMPI ? std::to_string(params.nb_proc <= 0 ? 1 : params.nb_proc) : "NULL");
994 // ===== Working directory (key = "workdir") and temporary directory flag (key = "isTmpDir")
995 // A working directory is requested
996 std::string workdir = params.workingdir.in();
997 std::string isTmpDir = std::to_string(0);
998 if (workdir == "$TEMPDIR")
1000 // A new temporary directory is requested
1001 isTmpDir = std::to_string(1);
1002 workdir = Kernel_Utils::GetTmpDir();
1004 script_parameters.push(workdir);
1005 script_parameters.push(isTmpDir);
1007 // ===== Server name (key = "name_server")
1008 script_parameters.push(Kernel_Utils::GetHostname());
1010 // ===== Container (key = "container")
1011 std::string container;
1014 container = isPythonContainer(params.container_name) ? "pyMPI SALOME_ContainerPy.py" : "SALOME_MPIContainer";
1018 container = isPythonContainer(params.container_name) ? "SALOME_ContainerPy.py" : container_exe;
1020 script_parameters.push(container);
1022 // ===== Container name (key = "container_name")
1023 script_parameters.push(_NS->ContainerName(params));
1025 // ===== LIBBATCH node file (key = "libbatch_nodefile")
1026 script_parameters.push(std::to_string(GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL ? 1 : 0));
1028 // ===== Machine file (key = "machine_file")
1029 script_parameters.push(machinesFile.empty() ? "NULL" : machinesFile);
1031 // ===== OMPI uri file (key = "ompi_uri_file")
1032 std::string ompi_uri_file = GetenvThreadSafeAsString("OMPI_URI_FILE");
1033 script_parameters.push(ompi_uri_file.empty() ? "NULL" : ompi_uri_file);
1035 std::string command_from_template = GetCommandFromTemplate(script_name, script_parameters);
1037 std::ostringstream o;
1038 o << command_from_template << " ";
1040 //==================================================================================== */
1044 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1045 CORBA::String_var iorNS = _orb->object_to_string(ns);
1051 AddOmninamesParams(o);
1054 tmpFileName = BuildTemporaryFileName();
1055 std::ofstream command_file( tmpFileName.c_str() );
1056 command_file << o.str();
1057 command_file.close();
1060 chmod(tmpFileName.c_str(), 0x1ED);
1063 std::string command = tmpFileName;
1064 MESSAGE("Command is file ... " << command);
1065 MESSAGE("Command is ... " << o.str());
1070 //=============================================================================
1072 * removes the generated temporary file in case of a remote launch.
1073 * This method is thread safe
1075 //=============================================================================
1077 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
1079 size_t length = tmpFileName.size();
1083 std::string command = "del /F ";
1085 std::string command = "rm ";
1088 command += tmpFileName.substr(0, length - 3 );
1090 command += tmpFileName;
1092 SystemThreadSafe(command.c_str());
1093 //if dir is empty - remove it
1094 std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
1095 if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
1098 command = "del /F " + tmp_dir;
1100 command = "rmdir " + tmp_dir;
1102 SystemThreadSafe(command.c_str());
1107 //=============================================================================
1109 * add to command all options relative to naming service.
1111 //=============================================================================
1113 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
1115 std::ostringstream oss;
1116 AddOmninamesParams(oss);
1120 //=============================================================================
1122 * add to command all options relative to naming service.
1124 //=============================================================================
1126 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
1128 AddOmninamesParams(fileStream,_NS);
1131 //=============================================================================
1133 * add to command all options relative to naming service.
1135 //=============================================================================
1137 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
1139 SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
1142 CORBA::String_var iorstr(nsTrad->getIORaddr());
1143 fileStream << "ORBInitRef NameService=";
1144 fileStream << iorstr;
1148 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
1151 command = "%PYTHONBIN% -c \"import subprocess ; subprocess.Popen(r'" + command + "').pid\"";
1157 int SALOME_ContainerManager::GetTimeOutToLoaunchServer()
1159 int count(TIME_OUT_TO_LAUNCH_CONT);
1160 if (GetenvThreadSafe("TIMEOUT_TO_LAUNCH_CONTAINER") != 0)
1162 std::string new_count_str(GetenvThreadSafeAsString("TIMEOUT_TO_LAUNCH_CONTAINER"));
1164 std::istringstream ss(new_count_str);
1165 if (!(ss >> new_count))
1167 INFOS("[LaunchContainer] TIMEOUT_TO_LAUNCH_CONTAINER should be an int");
1175 void SALOME_ContainerManager::SleepInSecond(int ellapseTimeInSecond)
1178 sleep( ellapseTimeInSecond ) ;
1180 int timeInMS(1000*ellapseTimeInSecond);
1185 //=============================================================================
1187 * generate a file name in /tmp directory
1189 //=============================================================================
1191 std::string SALOME_ContainerManager::BuildTemporaryFileName()
1193 //build more complex file name to support multiple salome session
1194 std::string aFileName = Kernel_Utils::GetTmpFileName();
1195 std::ostringstream str_pid;
1196 str_pid << ::getpid();
1197 aFileName = aFileName + "-" + str_pid.str();
1201 aFileName += ".bat";
1206 //=============================================================================
1208 * Builds in a temporary file the script to be launched.
1210 * Used if SALOME Application ($APPLI) is not defined.
1211 * The command is build with data from CatalogResources, in which every path
1212 * used on remote computer must be defined.
1214 //=============================================================================
1216 std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const std::string& resource_name, const Engines::ContainerParameters& params, std::string& tmpFileName) const
1220 tmpFileName = BuildTemporaryFileName();
1221 std::ofstream tempOutputFile;
1222 tempOutputFile.open(tmpFileName.c_str(), std::ofstream::out );
1223 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
1224 tempOutputFile << "#! /bin/sh" << std::endl;
1228 tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1229 //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1235 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
1237 tempOutputFile << "mpirun -np ";
1239 tempOutputFile << nbproc << " ";
1241 tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1242 #elif defined(OPEN_MPI)
1243 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
1244 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1246 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1247 tempOutputFile << GetenvThreadSafeAsString("OMPI_URI_FILE");
1249 #elif defined(MPICH)
1250 tempOutputFile << "-nameserver " + Kernel_Utils::GetHostname();
1254 tempOutputFile << GetenvThreadSafeAsString("KERNEL_ROOT_DIR") << "/bin/salome/";
1258 if (isPythonContainer(params.container_name))
1259 tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1261 tempOutputFile << " SALOME_MPIContainer ";
1266 if (isPythonContainer(params.container_name))
1267 tempOutputFile << "SALOME_ContainerPy.py ";
1269 tempOutputFile << "SALOME_Container ";
1272 tempOutputFile << _NS->ContainerName(params) << " -";
1273 AddOmninamesParams(tempOutputFile);
1274 tempOutputFile << " &" << std::endl;
1275 tempOutputFile.flush();
1276 tempOutputFile.close();
1278 chmod(tmpFileName.c_str(), 0x1ED);
1281 // --- Build command
1283 std::string command;
1285 if (resInfo.Protocol == rsh)
1288 std::string commandRcp = "rcp ";
1289 commandRcp += tmpFileName;
1291 commandRcp += resInfo.HostName;
1293 commandRcp += tmpFileName;
1294 status = SystemThreadSafe(commandRcp.c_str());
1297 else if (resInfo.Protocol == ssh)
1300 std::string commandRcp = "scp ";
1301 commandRcp += tmpFileName;
1303 commandRcp += resInfo.HostName;
1305 commandRcp += tmpFileName;
1306 status = SystemThreadSafe(commandRcp.c_str());
1309 else if (resInfo.Protocol == srun)
1311 command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
1312 std::string commandRcp = "rcp ";
1313 commandRcp += tmpFileName;
1315 commandRcp += resInfo.HostName;
1317 commandRcp += tmpFileName;
1318 status = SystemThreadSafe(commandRcp.c_str());
1321 throw SALOME_Exception("Unknown protocol");
1324 throw SALOME_Exception("Error of connection on remote host");
1326 command += resInfo.HostName;
1328 command += tmpFileName;
1336 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile) const
1339 std::string zeronode;
1340 std::string command;
1341 std::string tmpFile = BuildTemporaryFileName();
1342 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(machine));
1344 if(resInfo.Protocol == sh)
1346 return resInfo.HostName;
1349 if( GetenvThreadSafe("LIBBATCH_NODEFILE") == NULL )
1351 if (_isAppliSalomeDefined)
1353 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
1354 resInfo.UserName, resInfo.AppliPath);
1355 command += " mpirun -np 1 hostname -s > " + tmpFile;
1358 command = "mpirun -np 1 hostname -s > " + tmpFile;
1361 command = "mpirun -np 1 -machinefile " + machinesFile + " hostname -s > " + tmpFile;
1363 status = SystemThreadSafe(command.c_str());
1365 std::ifstream fp(tmpFile.c_str(),std::ios::in);
1366 while(fp >> zeronode);
1374 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1377 std::string nodesFile = GetenvThreadSafeAsString("LIBBATCH_NODEFILE");
1378 std::string machinesFile = Kernel_Utils::GetTmpFileName();
1379 std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1380 std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1382 _numInstanceMutex.lock();
1384 for(int i=0;i<_nbprocUsed;i++)
1387 for(int i=0;i<nbproc;i++)
1389 fpo << tmp << std::endl;
1391 throw SALOME_Exception("You need more processors than batch session have allocated for you! Unable to launch the mpi container: ");
1393 _nbprocUsed += nbproc;
1397 _numInstanceMutex.unlock();
1399 return machinesFile;
1403 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessNoAppli(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1405 return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE","salome shell --",protocol,hostname,username,applipath,workdir);
1408 std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1410 return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE_OLD",this->GetRunRemoteExecutableScript(),protocol,hostname,username,applipath,workdir);
1413 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessCommon(const std::string& templateName,
1414 const std::string& remoteScript,
1415 AccessProtocolType protocol,
1416 const std::string & hostname,
1417 const std::string & username,
1418 const std::string & applipath,
1419 const std::string & workdir) const
1421 std::ostringstream command;
1423 // Prepare parameters to use in the Python script:
1424 // 1. All parameters are strings.
1425 // 2. For some booleans use "1" = True, "0" = False.
1426 // 3. If a parameter is NULL, then its value is "NULL".
1428 std::queue<std::string> script_parameters;
1430 // ===== Protocol (key = "protocol")
1431 std::string strProtocol;
1434 case rsh: strProtocol = "rsh"; break;
1435 case ssh: strProtocol = "ssh"; break;
1436 case srun: strProtocol = "srun"; break;
1437 case pbsdsh: strProtocol = "pbsdsh"; break;
1438 case blaunch: strProtocol = "blaunch"; break;
1440 throw SALOME_Exception("Unknown protocol");
1442 script_parameters.push(strProtocol);
1444 // ===== User name (key = "user")
1445 script_parameters.push(username.empty() ? "NULL" : username);
1447 // ===== Host name (key = "host")
1448 script_parameters.push(hostname.empty() ? "NULL" : hostname);
1451 // ===== Remote APPLI path (key = "appli")
1452 script_parameters.push(applipath.empty() ? GetenvThreadSafeAsString("APPLI") : applipath);
1456 ASSERT(GetenvThreadSafe("NSHOST"));
1457 ASSERT(GetenvThreadSafe("NSPORT"));
1460 struct stat statbuf;
1461 std::string appli_mode = (stat(GetenvThreadSafe("APPLI"), &statbuf) == 0 && S_ISREG(statbuf.st_mode)) ? "launcher" : "dir";
1463 // ===== Working directory (key = "workdir")
1464 script_parameters.push(workdir == "$TEMPDIR" ? "\\$TEMPDIR" : workdir);
1466 // ===== SSL (key = "ssl")
1467 script_parameters.push(this->_isSSL ? "1" : "0");
1469 // ===== Hostname of CORBA name server (key = "nshost")
1470 std::string nshost = GetenvThreadSafeAsString("NSHOST");
1471 script_parameters.push(nshost.empty() ? "NULL" : nshost);
1473 // ===== Port of CORBA name server (key = "nsport")
1474 std::string nsport = GetenvThreadSafeAsString("NSPORT");
1475 script_parameters.push(nsport.empty() ? "NULL" : nsport);
1477 // ===== Remote script (key = "remote_script")
1478 script_parameters.push(remoteScript.empty() ? "NONE" : remoteScript);
1480 // ===== Naming service (key = "naming_service")
1481 std::string namingService = "NONE";
1484 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1485 CORBA::String_var iorNS = _orb->object_to_string(ns);
1486 namingService = iorNS;
1488 script_parameters.push(namingService);
1490 // ===== APPLI mode (key = "appli_mode")
1491 // $APPLI points either to an application directory, or to a salome launcher file
1492 // we prepare the remote command according to the case
1493 script_parameters.push(appli_mode);
1495 command << GetCommandFromTemplate(templateName, script_parameters);
1497 return command.str();
1501 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1505 // Step 1 : check ContainerParameters
1506 // Check container_name, has to be defined
1507 if (std::string(params.container_name.in()) == "")
1509 INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1512 // Check parallelLib
1513 std::string parallelLib = params.parallelLib.in();
1514 if (parallelLib != "Mpi" && parallelLib != "Dummy")
1516 INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1517 INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1518 INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1522 if (params.nb_proc <= 0)
1524 INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1528 // Step 2 : check resource_selected
1529 const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1530 //std::string protocol = resource_definition->protocol.in();
1531 std::string username = resource_definition.UserName;
1532 std::string applipath = resource_definition.AppliPath;
1534 //if (protocol == "" || username == "" || applipath == "")
1535 if (username == "" || applipath == "")
1537 INFOS("[checkPaCOParameters] resource selected is not well defined");
1538 INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1539 INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1540 INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1541 INFOS("[checkPaCOParameters] resource username: " << username);
1542 INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1550 * :WARNING: Do not directly convert returned value to std::string
1551 * This function may return NULL if env variable is not defined.
1552 * And std::string(NULL) causes undefined behavior.
1553 * Use GetenvThreadSafeAsString to properly get a std::string.
1555 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1556 {// getenv is not thread safe. See man 7 pthread.
1557 Utils_Locker lock (&_getenvMutex);
1558 return getenv(name);
1562 * Return env variable as a std::string.
1563 * Return empty string if env variable is not set.
1565 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1567 char* var = GetenvThreadSafe(name);
1568 return var ? std::string(var) : std::string();
1571 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1573 Utils_Locker lock (&_systemMutex);
1574 return system(command);
1577 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1579 Utils_Locker lock(&_systemMutex);
1580 if(command.size()<1)
1581 throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1583 pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1585 pid_t pid = -1; //Throw SALOME_Exception on Windows
1587 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1589 std::size_t sz(command.size());
1590 char **args = new char *[sz+1];
1591 for(std::size_t i=0;i<sz;i++)
1592 args[i] = strdup(command[i].c_str());
1594 execvp( command[0].c_str() , args );
1595 std::ostringstream oss;
1596 oss << "Error when launching " << command[0];
1597 throw SALOME_Exception(oss.str().c_str()); // execvp failed
1601 throw SALOME_Exception("fork() failed");
1603 else // I'm a parent
1609 #ifdef WITH_PACO_PARALLEL
1611 //=============================================================================
1613 * Start a suitable PaCO++ Parallel Container in a list of machines.
1614 * \param params Container Parameters required for the container
1615 * \return CORBA container reference.
1617 //=============================================================================
1618 Engines::Container_ptr
1619 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1620 std::string resource_selected)
1622 CORBA::Object_var obj;
1623 PaCO::InterfaceManager_var container_proxy;
1624 Engines::Container_ptr ret = Engines::Container::_nil();
1625 Engines::ContainerParameters params(params_const);
1626 params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1628 // Step 0 : Check parameters
1629 if (!checkPaCOParameters(params, resource_selected))
1631 INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1635 // Step 1 : Starting a new parallel container !
1636 INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1637 INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1639 // Step 2 : Get a MachineFile for the parallel container
1640 std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1642 params.parallelLib.in());
1644 if (machine_file_name == "")
1646 INFOS("[StartPaCOPPContainer] Machine file generation failed");
1650 // Step 3 : starting parallel container proxy
1651 std::string command_proxy("");
1652 std::string proxy_machine;
1655 command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1657 catch(const SALOME_Exception & ex)
1659 INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1663 obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1664 if (CORBA::is_nil(obj))
1666 INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1669 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1670 MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1672 // Step 4 : starting parallel container nodes
1673 std::string command_nodes("");
1674 SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1677 command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1679 catch(const SALOME_Exception & ex)
1681 INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1686 std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1687 bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1690 INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1691 // Il faut tuer le proxy
1694 Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1699 INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1704 // Step 4 : connecting nodes and the proxy to actually create a parallel container
1705 for (int i = 0; i < params.nb_proc; i++)
1707 std::ostringstream tmp;
1709 std::string proc_number = tmp.str();
1710 std::string container_node_name = container_generic_node_name + proc_number;
1712 std::string theNodeMachine(nodes_machines[i]);
1713 std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1714 obj = _NS->Resolve(containerNameInNS.c_str());
1715 if (CORBA::is_nil(obj))
1717 INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1718 INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1723 MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1724 PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1726 MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1728 catch(CORBA::SystemException& e)
1730 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1731 INFOS("CORBA::SystemException : " << e);
1734 catch(CORBA::Exception& e)
1736 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1737 INFOS("CORBA::Exception" << e);
1742 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1743 INFOS("Unknown exception !");
1748 // Step 5 : starting parallel container
1751 MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1752 container_proxy->start();
1753 MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1754 ret = Engines::Container::_narrow(container_proxy);
1756 catch(CORBA::SystemException& e)
1758 INFOS("Caught CORBA::SystemException. : " << e);
1760 catch(PortableServer::POA::ServantAlreadyActive&)
1762 INFOS("Caught CORBA::ServantAlreadyActiveException");
1764 catch(CORBA::Exception&)
1766 INFOS("Caught CORBA::Exception.");
1768 catch(std::exception& exc)
1770 INFOS("Caught std::exception - "<<exc.what());
1774 INFOS("Caught unknown exception.");
1780 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1781 std::string machine_file_name,
1782 std::string & proxy_hostname)
1784 // In the proxy case, we always launch a Dummy Proxy
1785 std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1786 std::string container_name = params.container_name.in();
1788 // Convert nb_proc in string
1789 std::ostringstream tmp_string;
1790 tmp_string << params.nb_proc;
1791 std::string nb_proc_str = tmp_string.str();
1793 // Get resource definition
1794 ParserResourcesType resource_definition =
1795 _resManager->GetResourceDefinition(params.resource_params.name.in());
1798 std::string hostname;
1799 std::ifstream machine_file(machine_file_name.c_str());
1800 std::getline(machine_file, hostname, ' ');
1801 size_t found = hostname.find('\n');
1802 if (found!=std::string::npos)
1803 hostname.erase(found, 1); // Remove \n
1804 proxy_hostname = hostname;
1805 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1808 bool remote_execution = false;
1809 if (hostname != std::string(Kernel_Utils::GetHostname()))
1811 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1812 remote_execution = true;
1816 std::string log_type("");
1817 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1821 // Generating the command
1822 std::string command_begin("");
1823 std::string command_end("");
1824 std::ostringstream command;
1826 LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1827 command << command_begin;
1829 // Adding connection command
1830 // We can only have a remote execution with
1831 // a SALOME application
1832 if (remote_execution)
1834 ASSERT(GetenvThreadSafe("NSHOST"));
1835 ASSERT(GetenvThreadSafe("NSPORT"));
1837 command << resource_definition.getAccessProtocolTypeStr();
1839 command << resource_definition.UserName;
1840 command << " " << hostname;
1841 command << " " << resource_definition.AppliPath;
1842 command << "/runRemote.sh ";
1843 command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1844 command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1847 command << exe_name;
1848 command << " " << container_name;
1849 command << " Dummy";
1850 command << " " << hostname;
1851 command << " " << nb_proc_str;
1853 AddOmninamesParams(command);
1856 command << command_end;
1857 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1859 return command.str();
1863 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1864 const std::string & machine_file_name,
1865 SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1866 const std::string & proxy_hostname)
1869 std::string exe_name = "SALOME_ParallelContainerNode";
1870 exe_name += params.parallelLib.in();
1871 std::string container_name = params.container_name.in();
1873 // Convert nb_proc in string
1874 std::ostringstream nb_proc_stream;
1875 nb_proc_stream << params.nb_proc;
1877 // Get resource definition
1878 ParserResourcesType resource_definition =
1879 _resManager->GetResourceDefinition(params.resource_params.name.in());
1882 std::string log_type("");
1883 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1887 // Now the command is different according to paralleLib
1888 std::ostringstream command_nodes;
1889 std::ifstream machine_file(machine_file_name.c_str());
1890 if (std::string(params.parallelLib.in()) == "Dummy")
1892 for (int i= 0; i < params.nb_proc; i++)
1895 std::string hostname;
1896 std::getline(machine_file, hostname);
1897 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1900 bool remote_execution = false;
1901 if (hostname != std::string(Kernel_Utils::GetHostname()))
1903 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1904 remote_execution = true;
1907 // For each node we have a new command
1908 // Generating the command
1909 std::ostringstream command_node_stream;
1910 std::string command_node_begin("");
1911 std::string command_node_end("");
1912 std::ostringstream node_number;
1914 std::string container_node_name = container_name + node_number.str();
1915 LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1917 // Adding connection command
1918 // We can only have a remote execution with
1919 // a SALOME application
1920 if (remote_execution)
1922 ASSERT(GetenvThreadSafe("NSHOST"));
1923 ASSERT(GetenvThreadSafe("NSPORT"));
1925 command_node_stream << resource_definition.getAccessProtocolTypeStr();
1926 command_node_stream << " -l ";
1927 command_node_stream << resource_definition.UserName;
1928 command_node_stream << " " << hostname;
1929 command_node_stream << " " << resource_definition.AppliPath;
1930 command_node_stream << "/runRemote.sh ";
1931 command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1932 command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1935 command_node_stream << exe_name;
1936 command_node_stream << " " << container_name;
1937 command_node_stream << " " << params.parallelLib.in();
1938 command_node_stream << " " << proxy_hostname;
1939 command_node_stream << " " << node_number.str();
1940 command_node_stream << " -";
1941 AddOmninamesParams(command_node_stream);
1943 command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1944 vect_machine.push_back(hostname);
1948 else if (std::string(params.parallelLib.in()) == "Mpi")
1951 std::string hostname;
1952 std::getline(machine_file, hostname, ' ');
1953 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1956 bool remote_execution = false;
1957 if (hostname != std::string(Kernel_Utils::GetHostname()))
1959 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1960 remote_execution = true;
1963 // In case of Mpi and Remote, we copy machine_file in the applipath
1964 // scp mpi_machine_file user@machine:Path
1965 std::ostringstream command_remote_stream;
1966 std::string::size_type last = machine_file_name.find_last_of("/");
1967 if (last == std::string::npos)
1970 if (resource_definition.Protocol == rsh)
1971 command_remote_stream << "rcp ";
1973 command_remote_stream << "scp ";
1974 command_remote_stream << machine_file_name << " ";
1975 command_remote_stream << resource_definition.UserName << "@";
1976 command_remote_stream << hostname << ":" << resource_definition.AppliPath;
1977 command_remote_stream << "/" << machine_file_name.substr(last+1);
1979 int status = SystemThreadSafe(command_remote_stream.str().c_str());
1982 INFOS("copy of the MPI machine file failed ! - sorry !");
1986 // Generating the command
1987 std::string command_begin("");
1988 std::string command_end("");
1990 LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
1991 command_nodes << command_begin;
1993 // Adding connection command
1994 // We can only have a remote execution with
1995 // a SALOME application
1996 if (remote_execution)
1998 ASSERT(GetenvThreadSafe("NSHOST"));
1999 ASSERT(GetenvThreadSafe("NSPORT"));
2001 command_nodes << resource_definition.getAccessProtocolTypeStr();
2002 command_nodes << " -l ";
2003 command_nodes << resource_definition.UserName;
2004 command_nodes << " " << hostname;
2005 command_nodes << " " << resource_definition.AppliPath;
2006 command_nodes << "/runRemote.sh ";
2007 command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
2008 command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
2011 if (resource_definition.mpi == lam)
2013 command_nodes << "mpiexec -ssi boot ";
2014 command_nodes << "-machinefile " << machine_file_name << " ";
2015 command_nodes << "-n " << params.nb_proc;
2019 command_nodes << "mpirun -np " << params.nb_proc;
2021 command_nodes << " " << exe_name;
2022 command_nodes << " " << container_name;
2023 command_nodes << " " << params.parallelLib.in();
2024 command_nodes << " " << proxy_hostname;
2025 command_nodes << " -";
2026 AddOmninamesParams(command_nodes);
2028 // We don't put hostname, because nodes are registered in the resource of the proxy
2029 for (int i= 0; i < params.nb_proc; i++)
2030 vect_machine.push_back(proxy_hostname);
2032 command_nodes << command_end;
2034 return command_nodes.str();
2038 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
2039 const std::string & exe_type,
2040 const std::string & container_name,
2041 const std::string & hostname,
2042 std::string & begin,
2045 if(log_type == "xterm")
2047 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2050 else if(log_type == "xterm_debug")
2052 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2057 // default into a file...
2058 std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
2059 std::string user = GetenvThreadSafeAsString("USER");
2061 user = GetenvThreadSafeAsString("LOGNAME");
2062 logFilename += user + ".log";
2063 end = " > " + logFilename + " 2>&1 & ";
2068 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
2069 const Engines::ContainerParameters& params,
2070 const std::string & hostname)
2072 PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
2074 MESSAGE("[LaunchPaCOProxyContainer] Launch command");
2075 int status = SystemThreadSafe(command.c_str());
2077 INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
2078 return container_proxy;
2080 else if (status == 217) {
2081 INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
2082 return container_proxy;
2085 int count(GetTimeOutToLoaunchServer());
2086 CORBA::Object_var obj = CORBA::Object::_nil();
2087 std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
2089 MESSAGE("[LaunchParallelContainer] Waiting for Parallel Container proxy : " << containerNameInNS);
2091 while (CORBA::is_nil(obj) && count)
2095 obj = _NS->Resolve(containerNameInNS.c_str());
2100 container_proxy = PaCO::InterfaceManager::_narrow(obj);
2102 catch(CORBA::SystemException& e)
2104 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2105 INFOS("CORBA::SystemException : " << e);
2106 return container_proxy;
2108 catch(CORBA::Exception& e)
2110 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2111 INFOS("CORBA::Exception" << e);
2112 return container_proxy;
2116 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2117 INFOS("Unknown exception !");
2118 return container_proxy;
2120 if (CORBA::is_nil(container_proxy))
2122 INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
2123 return container_proxy;
2128 //=============================================================================
2129 /*! This method launches the parallel container.
2130 * It will may be placed on the resources manager.
2132 * \param command to launch
2133 * \param container's parameters
2134 * \param name of the container
2136 * \return CORBA container reference
2138 //=============================================================================
2140 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
2141 const Engines::ContainerParameters& params,
2142 const std::string& name,
2143 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
2145 INFOS("[LaunchPaCONodeContainer] Launch command");
2146 int status = SystemThreadSafe(command.c_str());
2148 INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
2151 else if (status == 217) {
2152 INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
2156 INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
2157 // We are waiting all the nodes
2158 for (int i = 0; i < params.nb_proc; i++)
2160 CORBA::Object_var obj = CORBA::Object::_nil();
2161 std::string theMachine(vect_machine[i]);
2163 std::ostringstream tmp;
2165 std::string proc_number = tmp.str();
2166 std::string container_node_name = name + proc_number;
2167 std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
2168 INFOS("[LaunchPaCONodeContainer] Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
2169 int count(GetTimeOutToLoaunchServer());
2170 while (CORBA::is_nil(obj) && count) {
2173 obj = _NS->Resolve(containerNameInNS.c_str());
2175 if (CORBA::is_nil(obj))
2177 INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2186 Engines::Container_ptr
2187 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2188 std::string /*resource_selected*/)
2190 Engines::Container_ptr ret = Engines::Container::_nil();
2191 INFOS("[StarPaCOPPContainer] is disabled !");
2192 INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2197 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2198 std::string /*machine_file_name*/,
2199 std::string & /*proxy_hostname*/)
2205 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2206 const std::string & /*machine_file_name*/,
2207 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2208 const std::string & /*proxy_hostname*/)
2213 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2214 const std::string & /*exe_type*/,
2215 const std::string & /*container_name*/,
2216 const std::string & /*hostname*/,
2217 std::string & /*begin*/,
2218 std::string & /*end*/)
2223 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2224 const Engines::ContainerParameters& /*params*/,
2225 const std::string& /*hostname*/)
2227 CORBA::Object_ptr ret = CORBA::Object::_nil();
2232 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2233 const Engines::ContainerParameters& /*params*/,
2234 const std::string& /*name*/,
2235 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)