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"
47 #include <SALOMEconfig.h>
48 #include CORBA_CLIENT_HEADER(SALOME_Session)
57 #define getpid _getpid
60 #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
65 #ifdef WITH_PACO_PARALLEL
69 const int SALOME_ContainerManager::TIME_OUT_TO_LAUNCH_CONT=60;
71 const int SALOME_ContainerManager::DFT_DELTA_TIME_NS_LOOKUP_IN_MS=1000;
73 const char *SALOME_ContainerManager::_ContainerManagerNameInNS = "/ContainerManager";
75 omni_mutex SALOME_ContainerManager::_numInstanceMutex;
77 Utils_Mutex SALOME_ContainerManager::_getenvMutex;
79 Utils_Mutex SALOME_ContainerManager::_systemMutex;
81 //=============================================================================
85 * Define a CORBA single thread policy for the server, which avoid to deal
86 * with non thread-safe usage like Change_Directory in SALOME naming service
88 //=============================================================================
90 SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_NamingService_Abstract *ns)
91 : _nbprocUsed(1),_delta_time_ns_lookup_in_ms(DFT_DELTA_TIME_NS_LOOKUP_IN_MS)
93 MESSAGE("constructor");
95 _resManager = new SALOME_ResourcesManager_Client(ns);
96 _time_out_in_second = GetTimeOutToLoaunchServer();
98 PortableServer::POAManager_var pman = poa->the_POAManager();
99 _orb = CORBA::ORB::_duplicate(orb) ;
100 CORBA::PolicyList policies;
102 PortableServer::ThreadPolicy_var threadPol(poa->create_thread_policy(PortableServer::ORB_CTRL_MODEL));
103 policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
105 _poa = poa->create_POA("MThreadPOA",pman,policies);
106 threadPol->destroy();
107 PortableServer::ObjectId_var id = _poa->activate_object(this);
108 CORBA::Object_var obj = _poa->id_to_reference(id);
109 Engines::ContainerManager_var refContMan = Engines::ContainerManager::_narrow(obj);
111 _NS->Register(refContMan,_ContainerManagerNameInNS);
112 _isAppliSalomeDefined = (GetenvThreadSafe("APPLI") != 0);
117 // the urifile name depends on pid of the process
118 std::stringstream urifile;
119 urifile << GetenvThreadSafeAsString("HOME") << "/.urifile_" << getpid();
120 setenv("OMPI_URI_FILE",urifile.str().c_str(),1);
121 if( GetenvThreadSafe("OMPI_URI_FILE") != NULL ){
122 // Linux specific code
123 pid_t pid = fork(); // spawn a child process, following code is executed in both processes
124 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
126 std::string uriarg = GetenvThreadSafeAsString("OMPI_URI_FILE");
127 execlp( "ompi-server", "ompi-server", "-r", uriarg.c_str(), NULL );
128 throw SALOME_Exception("Error when launching ompi-server"); // execlp failed
132 throw SALOME_Exception("fork() failed");
136 //wait(NULL); // wait(?) for a child end
137 _pid_mpiServer = pid;
142 // Linux specific code
143 pid_t pid = fork(); // spawn a child process, following code is executed in both processes
144 if ( pid == 0 ) // I'm a child, replace myself with a new hydra_nameserver
146 execlp( "hydra_nameserver", "hydra_nameserver", NULL );
147 throw SALOME_Exception("Error when launching hydra_nameserver"); // execlp failed
151 throw SALOME_Exception("fork() failed");
156 _pid_mpiServer = pid;
161 MESSAGE("constructor end");
164 //=============================================================================
168 //=============================================================================
170 SALOME_ContainerManager::~SALOME_ContainerManager()
172 MESSAGE("destructor");
176 if( GetenvThreadSafe("OMPI_URI_FILE") != NULL ){
177 // kill my ompi-server
178 if( kill(_pid_mpiServer,SIGTERM) != 0 )
179 throw SALOME_Exception("Error when killing ompi-server");
181 int status=SystemThreadSafe("rm -f ${OMPI_URI_FILE}");
183 throw SALOME_Exception("Error when removing urifile");
186 // kill my hydra_nameserver
187 if(_pid_mpiServer > -1)
188 if( kill(_pid_mpiServer,SIGTERM) != 0 )
189 throw SALOME_Exception("Error when killing hydra_nameserver");
194 //=============================================================================
195 //! shutdown all the containers, then the ContainerManager servant
198 //=============================================================================
200 void SALOME_ContainerManager::Shutdown()
203 ShutdownContainers();
205 _NS->Destroy_Name(_ContainerManagerNameInNS);
206 PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
207 _poa->deactivate_object(oid);
210 CORBA::Long SALOME_ContainerManager::GetTimeOutToLaunchServerInSecond()
212 return this->_time_out_in_second;
215 void SALOME_ContainerManager::SetTimeOutToLaunchServerInSecond(CORBA::Long timeInSecond)
217 this->_time_out_in_second = timeInSecond;
220 CORBA::Long SALOME_ContainerManager::GetDeltaTimeBetweenNSLookupAtLaunchTimeInMilliSecond()
222 return this->_delta_time_ns_lookup_in_ms;
225 void SALOME_ContainerManager::SetDeltaTimeBetweenNSLookupAtLaunchTimeInMilliSecond(CORBA::Long timeInMS)
227 this->_delta_time_ns_lookup_in_ms = timeInMS;
230 //=============================================================================
231 //! Loop on all the containers listed in naming service, ask shutdown on each
234 //=============================================================================
236 void SALOME_ContainerManager::ShutdownContainers()
238 MESSAGE("ShutdownContainers");
241 SALOME::Session_var session = SALOME::Session::_nil();
243 CORBA::Object_var objS = _NS->Resolve("/Kernel/Session");
244 if (!CORBA::is_nil(objS))
246 session = SALOME::Session::_narrow(objS);
247 if (!CORBA::is_nil(session))
248 pid = session->getPID();
252 isOK = _NS->Change_Directory("/Containers");
254 std::vector<std::string> vec = _NS->list_directory_recurs();
255 std::list<std::string> lstCont;
256 for(std::vector<std::string>::iterator iter = vec.begin();iter!=vec.end();iter++)
259 CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
262 Engines::Container_var cont=Engines::Container::_narrow(obj);
263 if(!CORBA::is_nil(cont) && pid != cont->getPID())
264 lstCont.push_back((*iter));
266 catch(const CORBA::Exception&)
268 // ignore this entry and continue
271 MESSAGE("Container list: ");
272 for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
275 for(std::list<std::string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++)
280 CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
281 Engines::Container_var cont=Engines::Container::_narrow(obj);
282 if(!CORBA::is_nil(cont))
284 MESSAGE("ShutdownContainers: " << (*iter));
288 MESSAGE("ShutdownContainers: no container ref for " << (*iter));
290 catch(CORBA::SystemException& e)
292 INFOS("CORBA::SystemException ignored : " << e);
294 catch(CORBA::Exception&)
296 INFOS("CORBA::Exception ignored.");
300 INFOS("Unknown exception ignored.");
306 void SALOME_ContainerManager::SetOverrideEnvForContainers(const Engines::KeyValDict& env)
308 this->_override_env.clear();
309 auto sz = env.length();
310 for(auto i = 0 ; i < sz ; ++i)
311 _override_env.emplace_back( std::pair<std::string, std::string>(env[i].key,env[i].val) );
314 Engines::KeyValDict *SALOME_ContainerManager::GetOverrideEnvForContainers()
316 std::unique_ptr<Engines::KeyValDict> ret( new Engines::KeyValDict );
317 auto sz = _override_env.size();
319 for(auto i = 0 ; i < sz ; ++i)
321 (*ret)[i].key = CORBA::string_dup( _override_env[i].first.c_str() );
322 (*ret)[i].val = CORBA::string_dup( _override_env[i].second.c_str() );
324 return ret.release();
327 //=============================================================================
328 //! Give a suitable Container given constraints
330 * \param params Container Parameters required for the container
331 * \return the container or nil
333 //=============================================================================
334 Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::ContainerParameters& params)
336 std::string machFile;
337 Engines::Container_ptr ret(Engines::Container::_nil());
339 // Step 0: Default mode is start
340 Engines::ContainerParameters local_params(params);
341 if (std::string(local_params.mode.in()) == "")
342 local_params.mode = CORBA::string_dup("start");
343 std::string mode = local_params.mode.in();
344 MESSAGE("[GiveContainer] starting with mode: " << mode);
346 // Step 1: Find Container for find and findorstart mode
347 if (mode == "find" || mode == "findorstart")
349 ret = FindContainer(params, params.resource_params.resList);
350 if(!CORBA::is_nil(ret))
356 MESSAGE("[GiveContainer] no container found");
366 // Step 2: Get all possibleResources from the parameters
367 // Consider only resources that can run containers
368 resourceParams resource_params = resourceParameters_CORBAtoCPP(local_params.resource_params);
369 resource_params.can_run_containers = true;
370 std::vector<std::string> possibleResources = _resManager->GetFittingResources(resource_params);
371 MESSAGE("[GiveContainer] - length of possible resources " << possibleResources.size());
372 std::vector<std::string> local_resources;
374 // Step 3: if mode is "get" keep only machines with existing containers
377 for(unsigned int i=0; i < possibleResources.size(); i++)
379 Engines::Container_ptr cont = FindContainer(params, possibleResources[i]);
382 if(!cont->_non_existent())
383 local_resources.push_back(possibleResources[i]);
385 catch(CORBA::Exception&) {}
388 // if local_resources is empty, we cannot give a container
389 if (local_resources.size() == 0)
391 MESSAGE("[GiveContainer] cannot find a container for mode get");
396 local_resources = possibleResources;
398 // Step 4: select the resource where to get/start the container
399 bool resource_available = true;
400 std::string resource_selected;
401 std::vector<std::string> resources = local_resources;
402 while (resource_available)
404 if (resources.size() == 0)
405 resource_available = false;
410 resource_selected = _resManager->Find(params.resource_params.policy.in(), resources);
411 // Remove resource_selected from vector
412 std::vector<std::string>::iterator it;
413 for (it=resources.begin() ; it < resources.end(); it++ )
414 if (*it == resource_selected)
420 catch(const SALOME_Exception &ex) //!< TODO: unused variable
422 MESSAGE("[GiveContainer] Exception in ResourceManager find !: " << ex.what());
425 MESSAGE("[GiveContainer] Resource selected is: " << resource_selected);
427 // Step 5: Create container name
428 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
429 std::string hostname(resource_definition.HostName);
430 std::string containerNameInNS;
432 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
435 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
436 machFile = machinesFile(nbproc);
438 catch(const SALOME_Exception & ex)
440 std::string err_msg = ex.what();
441 err_msg += params.container_name;
442 INFOS(err_msg.c_str());
445 // A mpi parallel container register on zero node in NS
446 std::string mpiZeroNode = GetMPIZeroNode(resource_selected,machFile).c_str();
447 containerNameInNS = _NS->BuildContainerNameForNS(params, mpiZeroNode.c_str());
450 containerNameInNS = _NS->BuildContainerNameForNS(params, hostname.c_str());
451 MESSAGE("[GiveContainer] Container name in the naming service: " << containerNameInNS);
453 // Step 6: check if the name exists in naming service
454 //if params.mode == "getorstart" or "get" use the existing container
455 //if params.mode == "start" shutdown the existing container before launching a new one with that name
457 { // critical section
458 Utils_Locker lock (&_giveContainerMutex1);
459 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
460 if (!CORBA::is_nil(obj))
464 Engines::Container_var cont=Engines::Container::_narrow(obj);
465 if(!cont->_non_existent())
467 if(std::string(params.mode.in())=="getorstart" || std::string(params.mode.in())=="get"){
468 return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
472 INFOS("[GiveContainer] A container is already registered with the name: " << containerNameInNS << ", shutdown the existing container");
473 cont->Shutdown(); // shutdown the registered container if it exists
477 catch(CORBA::Exception&)
479 INFOS("[GiveContainer] CORBA::Exception ignored when trying to get the container - we start a new one");
482 } // end critical section
483 Engines::Container_var cont = LaunchContainer(params, resource_selected, hostname, machFile, containerNameInNS);
484 if (!CORBA::is_nil(cont))
486 INFOS("[GiveContainer] container " << containerNameInNS << " launched");
487 std::ostringstream envInfo;
488 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; } );
489 INFOS("[GiveContainer] container " << containerNameInNS << " override " << envInfo.str());
490 Engines::FieldsDict envCorba;
492 auto sz = _override_env.size();
494 for(auto i = 0 ; i < sz ; ++i)
496 envCorba[i].key = CORBA::string_dup( _override_env[i].first.c_str() );
497 envCorba[i].value <<= CORBA::string_dup( _override_env[i].second.c_str() );
500 cont->override_environment_python( envCorba );
505 INFOS("[GiveContainer] Failed to launch container on resource " << resource_selected);
510 // We were not able to launch the container
511 INFOS("[GiveContainer] Cannot launch the container on the following selected resources:")
512 std::vector<std::string>::iterator it;
513 for (it=local_resources.begin() ; it < local_resources.end(); it++ )
514 INFOS("[GiveContainer] " << *it)
518 std::string SALOME_ContainerManager::GetCppBinaryOfKernelContainer() const
520 std::string ret = this->_isSSL ? "SALOME_Container_No_NS_Serv" : "SALOME_Container";
524 std::string SALOME_ContainerManager::GetRunRemoteExecutableScript() const
526 std::string ret = this->_isSSL ? "runRemoteSSL.sh" : "runRemote.sh";
530 Engines::Container_ptr
531 SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& params,
532 const std::string & resource_selected,
533 const std::string & hostname,
534 const std::string & machFile,
535 const std::string & containerNameInNS)
537 std::string user,command,logFilename,tmpFileName;
539 Engines::Container_ptr ret(Engines::Container::_nil());
540 {//start of critical section
541 Utils_Locker lock (&_giveContainerMutex1);
542 // Step 1: type of container: PaCO, Exe, Mpi or Classic
543 // Mpi already tested in step 5, specific code on BuildCommandToLaunch Local/Remote Container methods
544 // TODO -> separates Mpi from Classic/Exe
546 std::string container_exe = this->GetCppBinaryOfKernelContainer();
547 Engines::ContainerParameters local_params(params);
551 CORBA::String_var container_exe_tmp;
552 CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
553 SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
554 if (CORBA::is_nil (Catalog))
556 INFOS("[GiveContainer] Module Catalog is not found -> cannot launch a container");
559 // Loop through component list
560 for(unsigned int i=0; i < local_params.resource_params.componentList.length(); i++)
562 const char* compoi = local_params.resource_params.componentList[i];
563 SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
564 if (CORBA::is_nil (compoInfo))
568 SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
569 container_exe_tmp=compoInfo->implementation_name();
570 if(impl==SALOME_ModuleCatalog::CEXE)
574 INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
575 return Engines::Container::_nil();
577 MESSAGE("[GiveContainer] Exe container found !: " << container_exe_tmp);
578 container_exe = container_exe_tmp.in();
583 catch (ServiceUnreachable&)
585 INFOS("Caught exception: Naming Service Unreachable");
590 INFOS("Caught unknown exception.");
594 // Step 2: test resource
595 // Only if an application directory is set
596 if(hostname != Kernel_Utils::GetHostname() && _isAppliSalomeDefined)
599 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_selected));
600 std::string command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
601 resInfo.UserName, resInfo.AppliPath);
603 // Launch remote command
604 command += " \"ls /tmp >/dev/null 2>&1\"";
605 // Anthony : command is NO MORE launched to improve dramatically time to launch containers
609 // Error on resource - cannot launch commands
610 INFOS("[LaunchContainer] Cannot launch commands on machine " << hostname);
611 INFOS("[LaunchContainer] Command was " << command);
613 INFOS("[LaunchContainer] Command status is " << WEXITSTATUS(status));
615 return Engines::Container::_nil();
619 // Step 3: start a new container
620 // Check if a PaCO container
622 if (std::string(local_params.parallelLib.in()) != "")
624 ret = StartPaCOPPContainer(params, resource_selected);
627 // Other type of containers...
628 MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
629 // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
630 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL && params.isMPI )
632 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
633 MESSAGE("[LaunchContainer] LIBBATCH_NODEFILE : \"" << command << "\"");
635 // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
636 else if(hostname == Kernel_Utils::GetHostname())
638 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
639 MESSAGE("[LaunchContainer] hostname local : \"" << command << "\"");
641 // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
644 command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
645 MESSAGE("[LaunchContainer] remote : \"" << command << "\"");
648 //redirect stdout and stderr in a file
650 logFilename=GetenvThreadSafeAsString("TEMP");
652 user = GetenvThreadSafeAsString( "USERNAME" );
654 user = GetenvThreadSafeAsString( "USER" );
656 user = GetenvThreadSafeAsString( "LOGNAME" );
658 char* val = GetenvThreadSafe("SALOME_TMP_DIR");
661 struct stat file_info;
662 stat(val, &file_info);
663 bool is_dir = S_ISDIR(file_info.st_mode);
664 if (is_dir)logFilename=val;
665 else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
669 logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
670 std::ostringstream tmp;
671 tmp << "_" << getpid();
672 logFilename += tmp.str();
673 logFilename += ".log" ;
674 command += " > " + logFilename + " 2>&1";
675 MakeTheCommandToBeLaunchedASync(command);
677 MESSAGE("[LaunchContainer] SYSTEM COMMAND that will be launched : \"" << command << "\"");
678 // launch container with a system call
679 status=SystemThreadSafe(command.c_str());
680 }//end of critical of section
684 INFOS("[LaunchContainer] command failed (system command status -1): " << command);
685 RmTmpFile(tmpFileName); // command file can be removed here
686 return Engines::Container::_nil();
688 else if (status == 217)
690 INFOS("[LaunchContainer] command failed (system command status 217): " << command);
691 RmTmpFile(tmpFileName); // command file can be removed here
692 return Engines::Container::_nil();
696 // Step 4: Wait for the container
697 double nbTurn = ( (double)this->_time_out_in_second ) * ( 1000.0 / ( (double) this->_delta_time_ns_lookup_in_ms) );
698 int count( (int)nbTurn );
699 INFOS("[GiveContainer] # attempts : " << count << " name in NS : \"" << containerNameInNS << "\"");
700 INFOS("[GiveContainer] # attempts : Time in second before time out : " << this->_time_out_in_second << " Delta time in ms between NS lookup : " << this->_delta_time_ns_lookup_in_ms);
701 while (CORBA::is_nil(ret) && count)
703 std::this_thread::sleep_for(std::chrono::milliseconds(_delta_time_ns_lookup_in_ms));
705 MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected << " with entry in NS = \"" << containerNameInNS << "\"" );
706 CORBA::Object_var obj(_NS->Resolve(containerNameInNS.c_str()));
707 ret=Engines::Container::_narrow(obj);
709 if (CORBA::is_nil(ret))
711 INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
715 // Setting log file name
716 logFilename=":"+logFilename;
717 logFilename="@"+Kernel_Utils::GetHostname()+logFilename;//threadsafe
718 logFilename=user+logFilename;
719 ret->logfilename(logFilename.c_str());
720 RmTmpFile(tmpFileName); // command file can be removed here
726 //=============================================================================
727 //! Find a container given constraints (params) on a list of machines (possibleComputers)
728 //! agy : this method is ThreadSafe
732 //=============================================================================
734 Engines::Container_ptr SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const Engines::ResourceList& possibleResources)
736 MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
737 for(unsigned int i=0; i < possibleResources.length();i++)
739 Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
740 if(!CORBA::is_nil(cont))
743 MESSAGE("[FindContainer] no container found");
744 return Engines::Container::_nil();
747 //=============================================================================
748 //! Find a container given constraints (params) on a machine (theMachine)
749 //! agy : this method is ThreadSafe
753 //=============================================================================
755 Engines::Container_ptr
756 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const std::string& resource)
758 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource);
759 std::string hostname(resource_definition.HostName);
760 std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
761 MESSAGE("[FindContainer] Try to find a container " << containerNameInNS << " on resource " << resource);
762 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
765 if(obj->_non_existent())
766 return Engines::Container::_nil();
768 return Engines::Container::_narrow(obj);
770 catch(const CORBA::Exception&)
772 return Engines::Container::_nil();
777 bool isPythonContainer(const char* ContainerName);
779 //=============================================================================
781 * This is no longer valid (C++ container are also python containers)
783 //=============================================================================
784 bool isPythonContainer(const char* ContainerName)
786 return false; // VSR 02/08/2013: Python containers are no more supported
788 size_t len = strlen(ContainerName);
791 if (strcmp(ContainerName + len - 2, "Py") == 0)
797 //=============================================================================
799 * Builds the script to be launched
801 * If SALOME Application not defined ($APPLI),
802 * see BuildTempFileToLaunchRemoteContainer()
804 * Else rely on distant configuration. Command is under the form (example):
805 * ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
806 * SALOME_Container containerName &"
808 * - where user is omitted if not specified in CatalogResources,
809 * - where distant path is always relative to user@machine $HOME, and
810 * equal to $APPLI if not specified in CatalogResources,
811 * - where hostNS is the hostname of CORBA naming server (set by scripts to
812 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
813 * - where portNS is the port used by CORBA naming server (set by scripts to
814 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
815 * - where workingdir is the requested working directory for the container.
816 * If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
818 //=============================================================================
821 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
823 std::string command,tmpFileName;
824 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
825 std::string wdir = params.workingdir.in();
826 if (!_isAppliSalomeDefined)
828 MESSAGE("[BuildCommandToLaunchRemoteContainer] NO APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
829 command = getCommandToRunRemoteProcessNoAppli(resInfo.Protocol, resInfo.HostName,
830 resInfo.UserName, resInfo.AppliPath,
835 MESSAGE("[BuildCommandToLaunchRemoteContainer] WITH APPLI MODE : " << " Protocol :" << resInfo.Protocol << " hostname :" << resInfo.HostName << " username : " << resInfo.UserName << " appli : " << resInfo.AppliPath << " wdir : \"" << wdir << "\"");
836 // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
837 // SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
839 // "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
840 // -- SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
841 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
842 resInfo.UserName, resInfo.AppliPath,
847 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
848 command += " mpirun -np ";
849 std::ostringstream o;
853 command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
854 #elif defined(OPEN_MPI)
855 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
856 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
858 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
859 command += GetenvThreadSafeAsString("OMPI_URI_FILE");
862 command += "-nameserver " + Kernel_Utils::GetHostname();
864 command += " SALOME_MPIContainer ";
867 command += " " +container_exe+ " ";
869 command += _NS->ContainerName(params) + " ";
872 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
873 CORBA::String_var iorNS = _orb->object_to_string(ns);
874 command += std::string(iorNS);
876 else //if(!this->_isSSL)
879 AddOmninamesParams(command);
881 MESSAGE("command =" << command);
886 //=============================================================================
887 //! Return a path to the directory with scripts templates
889 * \return the path pointed by SALOME_KERNEL_SCRIPTS_DIR environment variable, if it is defined,
890 * ${KERNEL_ROOT_DIR}/share/salome/resources/separator/kernel/ScriptsTemplate - otherwise
892 //=============================================================================
893 std::string getScriptTemplateFilePath()
895 auto parseScriptTemplateFilePath = []() -> std::string
897 std::string scriptTemplateFilePath = SALOME_ContainerManager::GetenvThreadSafeAsString("SALOME_KERNEL_SCRIPTS_DIR");
898 if (!scriptTemplateFilePath.empty())
900 return scriptTemplateFilePath;
903 return SALOME_ContainerManager::GetenvThreadSafeAsString("KERNEL_ROOT_DIR") +
904 "/share/salome/resources/kernel/ScriptsTemplate";
908 static const std::string scriptTemplateFilePath = parseScriptTemplateFilePath();
909 return scriptTemplateFilePath;
912 //=============================================================================
913 //! Return a command line constructed based on Python scripts templates
915 * \param theScriptName the name of Python script template
916 * \param theScriptParameters the queue of parameter values
917 * \return the command line constructed according to the given parameters
919 //=============================================================================
920 std::string GetCommandFromTemplate(const std::string& theScriptName,
921 std::queue<std::string>& theScriptParameters)
927 PyObject* mod(PyImport_ImportModule(theScriptName.c_str()));
930 PyObject* sys = PyImport_ImportModule("sys");
931 PyObject* sys_path = PyObject_GetAttrString(sys, "path");
932 PyObject* folder_path = PyUnicode_FromString(getScriptTemplateFilePath().c_str());
933 PyList_Append(sys_path, folder_path);
935 mod = PyImport_ImportModule(theScriptName.c_str());
937 Py_XDECREF(folder_path);
938 Py_XDECREF(sys_path);
944 PyObject* meth(PyObject_GetAttrString(mod, "command"));
952 PyObject* tuple(PyTuple_New(theScriptParameters.size()));
954 auto insert_parameter = [&tuple, &theScriptParameters, &id]()
956 if (!theScriptParameters.empty())
958 PyTuple_SetItem(tuple, ++id, PyUnicode_FromString(theScriptParameters.front().c_str()));
959 theScriptParameters.pop();
963 while (!theScriptParameters.empty())
968 PyObject *args(PyTuple_New(1));
969 PyTuple_SetItem(args, 0, tuple);
971 PyObject *res(PyObject_CallObject(meth, args));
974 command = PyUnicode_AsUTF8(res);
985 MESSAGE("Command from template is ... " << command << std::endl);
988 //=============================================================================
990 //=============================================================================
992 * builds the command to be launched.
994 //=============================================================================
995 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
997 // Prepare name of the script to be used
998 std::string script_name = "SALOME_CM_LOCAL_NO_MPI";
1002 script_name = "SALOME_CM_LOCAL_MPI_LAN";
1003 #elif defined(OPEN_MPI)
1004 script_name = "SALOME_CM_LOCAL_MPI_OPENMPI";
1005 #elif defined(MPICH)
1006 script_name = "SALOME_CM_LOCAL_MPI_MPICH";
1010 // Prepare parameters to use in the Python script:
1011 // 1. All parameters are strings.
1012 // 2. For some booleans use "1" = True, "0" = False.
1013 // 3. If a parameter is NULL, then its value is "NULL".
1015 std::queue<std::string> script_parameters;
1017 // ===== Number of processes (key = "nb_proc")
1018 script_parameters.push(params.isMPI ? std::to_string(params.nb_proc <= 0 ? 1 : params.nb_proc) : "NULL");
1020 // ===== Working directory (key = "workdir") and temporary directory flag (key = "isTmpDir")
1021 // A working directory is requested
1022 std::string workdir = params.workingdir.in();
1023 std::string isTmpDir = std::to_string(0);
1024 if (workdir == "$TEMPDIR")
1026 // A new temporary directory is requested
1027 isTmpDir = std::to_string(1);
1028 workdir = Kernel_Utils::GetTmpDir();
1030 script_parameters.push(workdir);
1031 script_parameters.push(isTmpDir);
1033 // ===== Server name (key = "name_server")
1034 script_parameters.push(Kernel_Utils::GetHostname());
1036 // ===== Container (key = "container")
1037 std::string container;
1040 container = isPythonContainer(params.container_name) ? "pyMPI SALOME_ContainerPy.py" : "SALOME_MPIContainer";
1044 container = isPythonContainer(params.container_name) ? "SALOME_ContainerPy.py" : container_exe;
1046 script_parameters.push(container);
1048 // ===== Container name (key = "container_name")
1049 script_parameters.push(_NS->ContainerName(params));
1051 // ===== LIBBATCH node file (key = "libbatch_nodefile")
1052 script_parameters.push(std::to_string(GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL ? 1 : 0));
1054 // ===== Machine file (key = "machine_file")
1055 script_parameters.push(machinesFile.empty() ? "NULL" : machinesFile);
1057 // ===== OMPI uri file (key = "ompi_uri_file")
1058 std::string ompi_uri_file = GetenvThreadSafeAsString("OMPI_URI_FILE");
1059 script_parameters.push(ompi_uri_file.empty() ? "NULL" : ompi_uri_file);
1061 std::string command_from_template = GetCommandFromTemplate(script_name, script_parameters);
1063 std::ostringstream o;
1064 o << command_from_template << " ";
1066 //==================================================================================== */
1070 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1071 CORBA::String_var iorNS = _orb->object_to_string(ns);
1077 AddOmninamesParams(o);
1080 tmpFileName = BuildTemporaryFileName();
1081 std::ofstream command_file( tmpFileName.c_str() );
1082 command_file << o.str();
1083 command_file.close();
1086 chmod(tmpFileName.c_str(), 0x1ED);
1089 std::string command = tmpFileName;
1090 MESSAGE("Command is file ... " << command);
1091 MESSAGE("Command is ... " << o.str());
1096 //=============================================================================
1098 * removes the generated temporary file in case of a remote launch.
1099 * This method is thread safe
1101 //=============================================================================
1103 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
1105 size_t length = tmpFileName.size();
1109 std::string command = "del /F ";
1111 std::string command = "rm ";
1114 command += tmpFileName.substr(0, length - 3 );
1116 command += tmpFileName;
1118 SystemThreadSafe(command.c_str());
1119 //if dir is empty - remove it
1120 std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
1121 if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
1124 command = "del /F " + tmp_dir;
1126 command = "rmdir " + tmp_dir;
1128 SystemThreadSafe(command.c_str());
1133 //=============================================================================
1135 * add to command all options relative to naming service.
1137 //=============================================================================
1139 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
1141 std::ostringstream oss;
1142 AddOmninamesParams(oss);
1146 //=============================================================================
1148 * add to command all options relative to naming service.
1150 //=============================================================================
1152 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
1154 AddOmninamesParams(fileStream,_NS);
1157 //=============================================================================
1159 * add to command all options relative to naming service.
1161 //=============================================================================
1163 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
1165 SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
1168 CORBA::String_var iorstr(nsTrad->getIORaddr());
1169 fileStream << "ORBInitRef NameService=";
1170 fileStream << iorstr;
1174 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
1177 command = "%PYTHONBIN% -c \"import subprocess ; subprocess.Popen(r'" + command + "').pid\"";
1184 * Return in second the time out to give chance to server to be launched and
1185 * to register into NS
1187 int SALOME_ContainerManager::GetTimeOutToLoaunchServer()
1189 int count(TIME_OUT_TO_LAUNCH_CONT);
1190 if (GetenvThreadSafe("TIMEOUT_TO_LAUNCH_CONTAINER") != 0)
1192 std::string new_count_str(GetenvThreadSafeAsString("TIMEOUT_TO_LAUNCH_CONTAINER"));
1194 std::istringstream ss(new_count_str);
1195 if (!(ss >> new_count))
1197 INFOS("[LaunchContainer] TIMEOUT_TO_LAUNCH_CONTAINER should be an int");
1205 void SALOME_ContainerManager::SleepInSecond(int ellapseTimeInSecond)
1208 sleep( ellapseTimeInSecond ) ;
1210 int timeInMS(1000*ellapseTimeInSecond);
1215 //=============================================================================
1217 * generate a file name in /tmp directory
1219 //=============================================================================
1221 std::string SALOME_ContainerManager::BuildTemporaryFileName()
1223 //build more complex file name to support multiple salome session
1224 std::string aFileName = Kernel_Utils::GetTmpFileName();
1225 std::ostringstream str_pid;
1226 str_pid << ::getpid();
1227 aFileName = aFileName + "-" + str_pid.str();
1231 aFileName += ".bat";
1236 //=============================================================================
1238 * Builds in a temporary file the script to be launched.
1240 * Used if SALOME Application ($APPLI) is not defined.
1241 * The command is build with data from CatalogResources, in which every path
1242 * used on remote computer must be defined.
1244 //=============================================================================
1246 std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const std::string& resource_name, const Engines::ContainerParameters& params, std::string& tmpFileName) const
1250 tmpFileName = BuildTemporaryFileName();
1251 std::ofstream tempOutputFile;
1252 tempOutputFile.open(tmpFileName.c_str(), std::ofstream::out );
1253 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
1254 tempOutputFile << "#! /bin/sh" << std::endl;
1258 tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1259 //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1265 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
1267 tempOutputFile << "mpirun -np ";
1269 tempOutputFile << nbproc << " ";
1271 tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1272 #elif defined(OPEN_MPI)
1273 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
1274 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1276 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1277 tempOutputFile << GetenvThreadSafeAsString("OMPI_URI_FILE");
1279 #elif defined(MPICH)
1280 tempOutputFile << "-nameserver " + Kernel_Utils::GetHostname();
1284 tempOutputFile << GetenvThreadSafeAsString("KERNEL_ROOT_DIR") << "/bin/salome/";
1288 if (isPythonContainer(params.container_name))
1289 tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1291 tempOutputFile << " SALOME_MPIContainer ";
1296 if (isPythonContainer(params.container_name))
1297 tempOutputFile << "SALOME_ContainerPy.py ";
1299 tempOutputFile << "SALOME_Container ";
1302 tempOutputFile << _NS->ContainerName(params) << " -";
1303 AddOmninamesParams(tempOutputFile);
1304 tempOutputFile << " &" << std::endl;
1305 tempOutputFile.flush();
1306 tempOutputFile.close();
1308 chmod(tmpFileName.c_str(), 0x1ED);
1311 // --- Build command
1313 std::string command;
1315 if (resInfo.Protocol == rsh)
1318 std::string commandRcp = "rcp ";
1319 commandRcp += tmpFileName;
1321 commandRcp += resInfo.HostName;
1323 commandRcp += tmpFileName;
1324 status = SystemThreadSafe(commandRcp.c_str());
1327 else if (resInfo.Protocol == ssh)
1330 std::string commandRcp = "scp ";
1331 commandRcp += tmpFileName;
1333 commandRcp += resInfo.HostName;
1335 commandRcp += tmpFileName;
1336 status = SystemThreadSafe(commandRcp.c_str());
1339 else if (resInfo.Protocol == srun)
1341 command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
1342 std::string commandRcp = "rcp ";
1343 commandRcp += tmpFileName;
1345 commandRcp += resInfo.HostName;
1347 commandRcp += tmpFileName;
1348 status = SystemThreadSafe(commandRcp.c_str());
1351 throw SALOME_Exception("Unknown protocol");
1354 throw SALOME_Exception("Error of connection on remote host");
1356 command += resInfo.HostName;
1358 command += tmpFileName;
1366 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile) const
1369 std::string zeronode;
1370 std::string command;
1371 std::string tmpFile = BuildTemporaryFileName();
1372 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(machine));
1374 if(resInfo.Protocol == sh)
1376 return resInfo.HostName;
1379 if( GetenvThreadSafe("LIBBATCH_NODEFILE") == NULL )
1381 if (_isAppliSalomeDefined)
1383 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
1384 resInfo.UserName, resInfo.AppliPath);
1385 command += " mpirun -np 1 hostname -s > " + tmpFile;
1388 command = "mpirun -np 1 hostname -s > " + tmpFile;
1391 command = "mpirun -np 1 -machinefile " + machinesFile + " hostname -s > " + tmpFile;
1393 status = SystemThreadSafe(command.c_str());
1395 std::ifstream fp(tmpFile.c_str(),std::ios::in);
1396 while(fp >> zeronode);
1404 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1407 std::string nodesFile = GetenvThreadSafeAsString("LIBBATCH_NODEFILE");
1408 std::string machinesFile = Kernel_Utils::GetTmpFileName();
1409 std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1410 std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1412 _numInstanceMutex.lock();
1414 for(int i=0;i<_nbprocUsed;i++)
1417 for(int i=0;i<nbproc;i++)
1419 fpo << tmp << std::endl;
1421 throw SALOME_Exception("You need more processors than batch session have allocated for you! Unable to launch the mpi container: ");
1423 _nbprocUsed += nbproc;
1427 _numInstanceMutex.unlock();
1429 return machinesFile;
1433 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessNoAppli(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1435 return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE","salome shell --",protocol,hostname,username,applipath,workdir);
1438 std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol, const std::string & hostname, const std::string & username, const std::string & applipath, const std::string & workdir) const
1440 return getCommandToRunRemoteProcessCommon("SALOME_CM_REMOTE_OLD",this->GetRunRemoteExecutableScript(),protocol,hostname,username,applipath,workdir);
1443 std::string SALOME_ContainerManager::getCommandToRunRemoteProcessCommon(const std::string& templateName,
1444 const std::string& remoteScript,
1445 AccessProtocolType protocol,
1446 const std::string & hostname,
1447 const std::string & username,
1448 const std::string & applipath,
1449 const std::string & workdir) const
1451 std::ostringstream command;
1453 // Prepare parameters to use in the Python script:
1454 // 1. All parameters are strings.
1455 // 2. For some booleans use "1" = True, "0" = False.
1456 // 3. If a parameter is NULL, then its value is "NULL".
1458 std::queue<std::string> script_parameters;
1460 // ===== Protocol (key = "protocol")
1461 std::string strProtocol;
1464 case rsh: strProtocol = "rsh"; break;
1465 case ssh: strProtocol = "ssh"; break;
1466 case srun: strProtocol = "srun"; break;
1467 case pbsdsh: strProtocol = "pbsdsh"; break;
1468 case blaunch: strProtocol = "blaunch"; break;
1470 throw SALOME_Exception("Unknown protocol");
1472 script_parameters.push(strProtocol);
1474 // ===== User name (key = "user")
1475 script_parameters.push(username.empty() ? "NULL" : username);
1477 // ===== Host name (key = "host")
1478 script_parameters.push(hostname.empty() ? "NULL" : hostname);
1481 // ===== Remote APPLI path (key = "appli")
1482 script_parameters.push(applipath.empty() ? GetenvThreadSafeAsString("APPLI") : applipath);
1486 ASSERT(GetenvThreadSafe("NSHOST"));
1487 ASSERT(GetenvThreadSafe("NSPORT"));
1490 struct stat statbuf;
1491 std::string appli_mode = (stat(GetenvThreadSafe("APPLI"), &statbuf) == 0 && S_ISREG(statbuf.st_mode)) ? "launcher" : "dir";
1493 // ===== Working directory (key = "workdir")
1494 script_parameters.push(workdir == "$TEMPDIR" ? "\\$TEMPDIR" : workdir);
1496 // ===== SSL (key = "ssl")
1497 script_parameters.push(this->_isSSL ? "1" : "0");
1499 // ===== Hostname of CORBA name server (key = "nshost")
1500 std::string nshost = GetenvThreadSafeAsString("NSHOST");
1501 script_parameters.push(nshost.empty() ? "NULL" : nshost);
1503 // ===== Port of CORBA name server (key = "nsport")
1504 std::string nsport = GetenvThreadSafeAsString("NSPORT");
1505 script_parameters.push(nsport.empty() ? "NULL" : nsport);
1507 // ===== Remote script (key = "remote_script")
1508 script_parameters.push(remoteScript.empty() ? "NONE" : remoteScript);
1510 // ===== Naming service (key = "naming_service")
1511 std::string namingService = "NONE";
1514 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1515 CORBA::String_var iorNS = _orb->object_to_string(ns);
1516 namingService = iorNS;
1518 script_parameters.push(namingService);
1520 // ===== APPLI mode (key = "appli_mode")
1521 // $APPLI points either to an application directory, or to a salome launcher file
1522 // we prepare the remote command according to the case
1523 script_parameters.push(appli_mode);
1525 command << GetCommandFromTemplate(templateName, script_parameters);
1527 return command.str();
1531 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1535 // Step 1 : check ContainerParameters
1536 // Check container_name, has to be defined
1537 if (std::string(params.container_name.in()) == "")
1539 INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1542 // Check parallelLib
1543 std::string parallelLib = params.parallelLib.in();
1544 if (parallelLib != "Mpi" && parallelLib != "Dummy")
1546 INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1547 INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1548 INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1552 if (params.nb_proc <= 0)
1554 INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1558 // Step 2 : check resource_selected
1559 const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1560 //std::string protocol = resource_definition->protocol.in();
1561 std::string username = resource_definition.UserName;
1562 std::string applipath = resource_definition.AppliPath;
1564 //if (protocol == "" || username == "" || applipath == "")
1565 if (username == "" || applipath == "")
1567 INFOS("[checkPaCOParameters] resource selected is not well defined");
1568 INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1569 INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1570 INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1571 INFOS("[checkPaCOParameters] resource username: " << username);
1572 INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1580 * :WARNING: Do not directly convert returned value to std::string
1581 * This function may return NULL if env variable is not defined.
1582 * And std::string(NULL) causes undefined behavior.
1583 * Use GetenvThreadSafeAsString to properly get a std::string.
1585 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1586 {// getenv is not thread safe. See man 7 pthread.
1587 Utils_Locker lock (&_getenvMutex);
1588 return getenv(name);
1592 * Return env variable as a std::string.
1593 * Return empty string if env variable is not set.
1595 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1597 char* var = GetenvThreadSafe(name);
1598 return var ? std::string(var) : std::string();
1601 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1603 Utils_Locker lock (&_systemMutex);
1604 return system(command);
1607 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1609 Utils_Locker lock(&_systemMutex);
1610 if(command.size()<1)
1611 throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1613 pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1615 pid_t pid = -1; //Throw SALOME_Exception on Windows
1617 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1619 std::size_t sz(command.size());
1620 char **args = new char *[sz+1];
1621 for(std::size_t i=0;i<sz;i++)
1622 args[i] = strdup(command[i].c_str());
1624 execvp( command[0].c_str() , args );
1625 std::ostringstream oss;
1626 oss << "Error when launching " << command[0];
1627 throw SALOME_Exception(oss.str().c_str()); // execvp failed
1631 throw SALOME_Exception("fork() failed");
1633 else // I'm a parent
1639 #ifdef WITH_PACO_PARALLEL
1641 //=============================================================================
1643 * Start a suitable PaCO++ Parallel Container in a list of machines.
1644 * \param params Container Parameters required for the container
1645 * \return CORBA container reference.
1647 //=============================================================================
1648 Engines::Container_ptr
1649 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1650 std::string resource_selected)
1652 CORBA::Object_var obj;
1653 PaCO::InterfaceManager_var container_proxy;
1654 Engines::Container_ptr ret = Engines::Container::_nil();
1655 Engines::ContainerParameters params(params_const);
1656 params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1658 // Step 0 : Check parameters
1659 if (!checkPaCOParameters(params, resource_selected))
1661 INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1665 // Step 1 : Starting a new parallel container !
1666 INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1667 INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1669 // Step 2 : Get a MachineFile for the parallel container
1670 std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1672 params.parallelLib.in());
1674 if (machine_file_name == "")
1676 INFOS("[StartPaCOPPContainer] Machine file generation failed");
1680 // Step 3 : starting parallel container proxy
1681 std::string command_proxy("");
1682 std::string proxy_machine;
1685 command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1687 catch(const SALOME_Exception & ex)
1689 INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1693 obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1694 if (CORBA::is_nil(obj))
1696 INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1699 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1700 MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1702 // Step 4 : starting parallel container nodes
1703 std::string command_nodes("");
1704 SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1707 command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1709 catch(const SALOME_Exception & ex)
1711 INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1716 std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1717 bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1720 INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1721 // Il faut tuer le proxy
1724 Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1729 INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1734 // Step 4 : connecting nodes and the proxy to actually create a parallel container
1735 for (int i = 0; i < params.nb_proc; i++)
1737 std::ostringstream tmp;
1739 std::string proc_number = tmp.str();
1740 std::string container_node_name = container_generic_node_name + proc_number;
1742 std::string theNodeMachine(nodes_machines[i]);
1743 std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1744 obj = _NS->Resolve(containerNameInNS.c_str());
1745 if (CORBA::is_nil(obj))
1747 INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1748 INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1753 MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1754 PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1756 MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1758 catch(CORBA::SystemException& e)
1760 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1761 INFOS("CORBA::SystemException : " << e);
1764 catch(CORBA::Exception& e)
1766 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1767 INFOS("CORBA::Exception" << e);
1772 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1773 INFOS("Unknown exception !");
1778 // Step 5 : starting parallel container
1781 MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1782 container_proxy->start();
1783 MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1784 ret = Engines::Container::_narrow(container_proxy);
1786 catch(CORBA::SystemException& e)
1788 INFOS("Caught CORBA::SystemException. : " << e);
1790 catch(PortableServer::POA::ServantAlreadyActive&)
1792 INFOS("Caught CORBA::ServantAlreadyActiveException");
1794 catch(CORBA::Exception&)
1796 INFOS("Caught CORBA::Exception.");
1798 catch(std::exception& exc)
1800 INFOS("Caught std::exception - "<<exc.what());
1804 INFOS("Caught unknown exception.");
1810 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1811 std::string machine_file_name,
1812 std::string & proxy_hostname)
1814 // In the proxy case, we always launch a Dummy Proxy
1815 std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1816 std::string container_name = params.container_name.in();
1818 // Convert nb_proc in string
1819 std::ostringstream tmp_string;
1820 tmp_string << params.nb_proc;
1821 std::string nb_proc_str = tmp_string.str();
1823 // Get resource definition
1824 ParserResourcesType resource_definition =
1825 _resManager->GetResourceDefinition(params.resource_params.name.in());
1828 std::string hostname;
1829 std::ifstream machine_file(machine_file_name.c_str());
1830 std::getline(machine_file, hostname, ' ');
1831 size_t found = hostname.find('\n');
1832 if (found!=std::string::npos)
1833 hostname.erase(found, 1); // Remove \n
1834 proxy_hostname = hostname;
1835 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1838 bool remote_execution = false;
1839 if (hostname != std::string(Kernel_Utils::GetHostname()))
1841 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1842 remote_execution = true;
1846 std::string log_type("");
1847 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1851 // Generating the command
1852 std::string command_begin("");
1853 std::string command_end("");
1854 std::ostringstream command;
1856 LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1857 command << command_begin;
1859 // Adding connection command
1860 // We can only have a remote execution with
1861 // a SALOME application
1862 if (remote_execution)
1864 ASSERT(GetenvThreadSafe("NSHOST"));
1865 ASSERT(GetenvThreadSafe("NSPORT"));
1867 command << resource_definition.getAccessProtocolTypeStr();
1869 command << resource_definition.UserName;
1870 command << " " << hostname;
1871 command << " " << resource_definition.AppliPath;
1872 command << "/runRemote.sh ";
1873 command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1874 command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1877 command << exe_name;
1878 command << " " << container_name;
1879 command << " Dummy";
1880 command << " " << hostname;
1881 command << " " << nb_proc_str;
1883 AddOmninamesParams(command);
1886 command << command_end;
1887 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1889 return command.str();
1893 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1894 const std::string & machine_file_name,
1895 SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1896 const std::string & proxy_hostname)
1899 std::string exe_name = "SALOME_ParallelContainerNode";
1900 exe_name += params.parallelLib.in();
1901 std::string container_name = params.container_name.in();
1903 // Convert nb_proc in string
1904 std::ostringstream nb_proc_stream;
1905 nb_proc_stream << params.nb_proc;
1907 // Get resource definition
1908 ParserResourcesType resource_definition =
1909 _resManager->GetResourceDefinition(params.resource_params.name.in());
1912 std::string log_type("");
1913 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1917 // Now the command is different according to paralleLib
1918 std::ostringstream command_nodes;
1919 std::ifstream machine_file(machine_file_name.c_str());
1920 if (std::string(params.parallelLib.in()) == "Dummy")
1922 for (int i= 0; i < params.nb_proc; i++)
1925 std::string hostname;
1926 std::getline(machine_file, hostname);
1927 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1930 bool remote_execution = false;
1931 if (hostname != std::string(Kernel_Utils::GetHostname()))
1933 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1934 remote_execution = true;
1937 // For each node we have a new command
1938 // Generating the command
1939 std::ostringstream command_node_stream;
1940 std::string command_node_begin("");
1941 std::string command_node_end("");
1942 std::ostringstream node_number;
1944 std::string container_node_name = container_name + node_number.str();
1945 LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1947 // Adding connection command
1948 // We can only have a remote execution with
1949 // a SALOME application
1950 if (remote_execution)
1952 ASSERT(GetenvThreadSafe("NSHOST"));
1953 ASSERT(GetenvThreadSafe("NSPORT"));
1955 command_node_stream << resource_definition.getAccessProtocolTypeStr();
1956 command_node_stream << " -l ";
1957 command_node_stream << resource_definition.UserName;
1958 command_node_stream << " " << hostname;
1959 command_node_stream << " " << resource_definition.AppliPath;
1960 command_node_stream << "/runRemote.sh ";
1961 command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1962 command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1965 command_node_stream << exe_name;
1966 command_node_stream << " " << container_name;
1967 command_node_stream << " " << params.parallelLib.in();
1968 command_node_stream << " " << proxy_hostname;
1969 command_node_stream << " " << node_number.str();
1970 command_node_stream << " -";
1971 AddOmninamesParams(command_node_stream);
1973 command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1974 vect_machine.push_back(hostname);
1978 else if (std::string(params.parallelLib.in()) == "Mpi")
1981 std::string hostname;
1982 std::getline(machine_file, hostname, ' ');
1983 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1986 bool remote_execution = false;
1987 if (hostname != std::string(Kernel_Utils::GetHostname()))
1989 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1990 remote_execution = true;
1993 // In case of Mpi and Remote, we copy machine_file in the applipath
1994 // scp mpi_machine_file user@machine:Path
1995 std::ostringstream command_remote_stream;
1996 std::string::size_type last = machine_file_name.find_last_of("/");
1997 if (last == std::string::npos)
2000 if (resource_definition.Protocol == rsh)
2001 command_remote_stream << "rcp ";
2003 command_remote_stream << "scp ";
2004 command_remote_stream << machine_file_name << " ";
2005 command_remote_stream << resource_definition.UserName << "@";
2006 command_remote_stream << hostname << ":" << resource_definition.AppliPath;
2007 command_remote_stream << "/" << machine_file_name.substr(last+1);
2009 int status = SystemThreadSafe(command_remote_stream.str().c_str());
2012 INFOS("copy of the MPI machine file failed ! - sorry !");
2016 // Generating the command
2017 std::string command_begin("");
2018 std::string command_end("");
2020 LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
2021 command_nodes << command_begin;
2023 // Adding connection command
2024 // We can only have a remote execution with
2025 // a SALOME application
2026 if (remote_execution)
2028 ASSERT(GetenvThreadSafe("NSHOST"));
2029 ASSERT(GetenvThreadSafe("NSPORT"));
2031 command_nodes << resource_definition.getAccessProtocolTypeStr();
2032 command_nodes << " -l ";
2033 command_nodes << resource_definition.UserName;
2034 command_nodes << " " << hostname;
2035 command_nodes << " " << resource_definition.AppliPath;
2036 command_nodes << "/runRemote.sh ";
2037 command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
2038 command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
2041 if (resource_definition.mpi == lam)
2043 command_nodes << "mpiexec -ssi boot ";
2044 command_nodes << "-machinefile " << machine_file_name << " ";
2045 command_nodes << "-n " << params.nb_proc;
2049 command_nodes << "mpirun -np " << params.nb_proc;
2051 command_nodes << " " << exe_name;
2052 command_nodes << " " << container_name;
2053 command_nodes << " " << params.parallelLib.in();
2054 command_nodes << " " << proxy_hostname;
2055 command_nodes << " -";
2056 AddOmninamesParams(command_nodes);
2058 // We don't put hostname, because nodes are registered in the resource of the proxy
2059 for (int i= 0; i < params.nb_proc; i++)
2060 vect_machine.push_back(proxy_hostname);
2062 command_nodes << command_end;
2064 return command_nodes.str();
2068 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
2069 const std::string & exe_type,
2070 const std::string & container_name,
2071 const std::string & hostname,
2072 std::string & begin,
2075 if(log_type == "xterm")
2077 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2080 else if(log_type == "xterm_debug")
2082 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2087 // default into a file...
2088 std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
2089 std::string user = GetenvThreadSafeAsString("USER");
2091 user = GetenvThreadSafeAsString("LOGNAME");
2092 logFilename += user + ".log";
2093 end = " > " + logFilename + " 2>&1 & ";
2098 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
2099 const Engines::ContainerParameters& params,
2100 const std::string & hostname)
2102 PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
2104 MESSAGE("[LaunchPaCOProxyContainer] Launch command");
2105 int status = SystemThreadSafe(command.c_str());
2107 INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
2108 return container_proxy;
2110 else if (status == 217) {
2111 INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
2112 return container_proxy;
2115 int count(GetTimeOutToLoaunchServer());
2116 CORBA::Object_var obj = CORBA::Object::_nil();
2117 std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
2119 MESSAGE("[LaunchParallelContainer] Waiting for Parallel Container proxy : " << containerNameInNS);
2121 while (CORBA::is_nil(obj) && count)
2125 obj = _NS->Resolve(containerNameInNS.c_str());
2130 container_proxy = PaCO::InterfaceManager::_narrow(obj);
2132 catch(CORBA::SystemException& e)
2134 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2135 INFOS("CORBA::SystemException : " << e);
2136 return container_proxy;
2138 catch(CORBA::Exception& e)
2140 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2141 INFOS("CORBA::Exception" << e);
2142 return container_proxy;
2146 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2147 INFOS("Unknown exception !");
2148 return container_proxy;
2150 if (CORBA::is_nil(container_proxy))
2152 INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
2153 return container_proxy;
2158 //=============================================================================
2159 /*! This method launches the parallel container.
2160 * It will may be placed on the resources manager.
2162 * \param command to launch
2163 * \param container's parameters
2164 * \param name of the container
2166 * \return CORBA container reference
2168 //=============================================================================
2170 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
2171 const Engines::ContainerParameters& params,
2172 const std::string& name,
2173 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
2175 INFOS("[LaunchPaCONodeContainer] Launch command");
2176 int status = SystemThreadSafe(command.c_str());
2178 INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
2181 else if (status == 217) {
2182 INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
2186 INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
2187 // We are waiting all the nodes
2188 for (int i = 0; i < params.nb_proc; i++)
2190 CORBA::Object_var obj = CORBA::Object::_nil();
2191 std::string theMachine(vect_machine[i]);
2193 std::ostringstream tmp;
2195 std::string proc_number = tmp.str();
2196 std::string container_node_name = name + proc_number;
2197 std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
2198 INFOS("[LaunchPaCONodeContainer] Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
2199 int count(GetTimeOutToLoaunchServer());
2200 while (CORBA::is_nil(obj) && count) {
2203 obj = _NS->Resolve(containerNameInNS.c_str());
2205 if (CORBA::is_nil(obj))
2207 INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2216 Engines::Container_ptr
2217 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2218 std::string /*resource_selected*/)
2220 Engines::Container_ptr ret = Engines::Container::_nil();
2221 INFOS("[StarPaCOPPContainer] is disabled !");
2222 INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2227 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2228 std::string /*machine_file_name*/,
2229 std::string & /*proxy_hostname*/)
2235 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2236 const std::string & /*machine_file_name*/,
2237 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2238 const std::string & /*proxy_hostname*/)
2243 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2244 const std::string & /*exe_type*/,
2245 const std::string & /*container_name*/,
2246 const std::string & /*hostname*/,
2247 std::string & /*begin*/,
2248 std::string & /*end*/)
2253 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2254 const Engines::ContainerParameters& /*params*/,
2255 const std::string& /*hostname*/)
2257 CORBA::Object_ptr ret = CORBA::Object::_nil();
2262 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2263 const Engines::ContainerParameters& /*params*/,
2264 const std::string& /*name*/,
2265 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)