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 //=============================================================================
283 //! Give a suitable Container given constraints
285 * \param params Container Parameters required for the container
286 * \return the container or nil
288 //=============================================================================
289 Engines::Container_ptr SALOME_ContainerManager::GiveContainer(const Engines::ContainerParameters& params)
291 std::string machFile;
292 Engines::Container_ptr ret(Engines::Container::_nil());
294 // Step 0: Default mode is start
295 Engines::ContainerParameters local_params(params);
296 if (std::string(local_params.mode.in()) == "")
297 local_params.mode = CORBA::string_dup("start");
298 std::string mode = local_params.mode.in();
299 MESSAGE("[GiveContainer] starting with mode: " << mode);
301 // Step 1: Find Container for find and findorstart mode
302 if (mode == "find" || mode == "findorstart")
304 ret = FindContainer(params, params.resource_params.resList);
305 if(!CORBA::is_nil(ret))
311 MESSAGE("[GiveContainer] no container found");
321 // Step 2: Get all possibleResources from the parameters
322 // Consider only resources that can run containers
323 resourceParams resource_params = resourceParameters_CORBAtoCPP(local_params.resource_params);
324 resource_params.can_run_containers = true;
325 std::vector<std::string> possibleResources = _resManager->GetFittingResources(resource_params);
326 MESSAGE("[GiveContainer] - length of possible resources " << possibleResources.size());
327 std::vector<std::string> local_resources;
329 // Step 3: if mode is "get" keep only machines with existing containers
332 for(unsigned int i=0; i < possibleResources.size(); i++)
334 Engines::Container_ptr cont = FindContainer(params, possibleResources[i]);
337 if(!cont->_non_existent())
338 local_resources.push_back(possibleResources[i]);
340 catch(CORBA::Exception&) {}
343 // if local_resources is empty, we cannot give a container
344 if (local_resources.size() == 0)
346 MESSAGE("[GiveContainer] cannot find a container for mode get");
351 local_resources = possibleResources;
353 // Step 4: select the resource where to get/start the container
354 bool resource_available = true;
355 std::string resource_selected;
356 std::vector<std::string> resources = local_resources;
357 while (resource_available)
359 if (resources.size() == 0)
360 resource_available = false;
365 resource_selected = _resManager->Find(params.resource_params.policy.in(), resources);
366 // Remove resource_selected from vector
367 std::vector<std::string>::iterator it;
368 for (it=resources.begin() ; it < resources.end(); it++ )
369 if (*it == resource_selected)
375 catch(const SALOME_Exception &ex) //!< TODO: unused variable
377 MESSAGE("[GiveContainer] Exception in ResourceManager find !: " << ex.what());
380 MESSAGE("[GiveContainer] Resource selected is: " << resource_selected);
382 // Step 5: Create container name
383 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
384 std::string hostname(resource_definition.HostName);
385 std::string containerNameInNS;
387 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
390 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL )
391 machFile = machinesFile(nbproc);
393 catch(const SALOME_Exception & ex)
395 std::string err_msg = ex.what();
396 err_msg += params.container_name;
397 INFOS(err_msg.c_str());
400 // A mpi parallel container register on zero node in NS
401 std::string mpiZeroNode = GetMPIZeroNode(resource_selected,machFile).c_str();
402 containerNameInNS = _NS->BuildContainerNameForNS(params, mpiZeroNode.c_str());
405 containerNameInNS = _NS->BuildContainerNameForNS(params, hostname.c_str());
406 MESSAGE("[GiveContainer] Container name in the naming service: " << containerNameInNS);
408 // Step 6: check if the name exists in naming service
409 //if params.mode == "getorstart" or "get" use the existing container
410 //if params.mode == "start" shutdown the existing container before launching a new one with that name
412 { // critical section
413 Utils_Locker lock (&_giveContainerMutex1);
414 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
415 if (!CORBA::is_nil(obj))
419 Engines::Container_var cont=Engines::Container::_narrow(obj);
420 if(!cont->_non_existent())
422 if(std::string(params.mode.in())=="getorstart" || std::string(params.mode.in())=="get"){
423 return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
427 INFOS("[GiveContainer] A container is already registered with the name: " << containerNameInNS << ", shutdown the existing container");
428 cont->Shutdown(); // shutdown the registered container if it exists
432 catch(CORBA::Exception&)
434 INFOS("[GiveContainer] CORBA::Exception ignored when trying to get the container - we start a new one");
437 } // end critical section
438 Engines::Container_var cont = LaunchContainer(params, resource_selected, hostname, machFile, containerNameInNS);
439 if (!CORBA::is_nil(cont))
441 INFOS("[GiveContainer] container " << containerNameInNS << " launched");
446 INFOS("[GiveContainer] Failed to launch container on resource " << resource_selected);
451 // We were not able to launch the container
452 INFOS("[GiveContainer] Cannot launch the container on the following selected resources:")
453 std::vector<std::string>::iterator it;
454 for (it=local_resources.begin() ; it < local_resources.end(); it++ )
455 INFOS("[GiveContainer] " << *it)
459 std::string SALOME_ContainerManager::GetCppBinaryOfKernelContainer() const
461 std::string ret = this->_isSSL ? "SALOME_Container_No_NS_Serv" : "SALOME_Container";
465 std::string SALOME_ContainerManager::GetRunRemoteExecutableScript() const
467 std::string ret = this->_isSSL ? "runRemoteSSL.sh" : "runRemote.sh";
471 Engines::Container_ptr
472 SALOME_ContainerManager::LaunchContainer(const Engines::ContainerParameters& params,
473 const std::string & resource_selected,
474 const std::string & hostname,
475 const std::string & machFile,
476 const std::string & containerNameInNS)
478 std::string user,command,logFilename,tmpFileName;
480 Engines::Container_ptr ret(Engines::Container::_nil());
481 {//start of critical section
482 Utils_Locker lock (&_giveContainerMutex1);
483 // Step 1: type of container: PaCO, Exe, Mpi or Classic
484 // Mpi already tested in step 5, specific code on BuildCommandToLaunch Local/Remote Container methods
485 // TODO -> separates Mpi from Classic/Exe
487 std::string container_exe = this->GetCppBinaryOfKernelContainer();
488 Engines::ContainerParameters local_params(params);
492 CORBA::String_var container_exe_tmp;
493 CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
494 SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
495 if (CORBA::is_nil (Catalog))
497 INFOS("[GiveContainer] Module Catalog is not found -> cannot launch a container");
500 // Loop through component list
501 for(unsigned int i=0; i < local_params.resource_params.componentList.length(); i++)
503 const char* compoi = local_params.resource_params.componentList[i];
504 SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
505 if (CORBA::is_nil (compoInfo))
509 SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
510 container_exe_tmp=compoInfo->implementation_name();
511 if(impl==SALOME_ModuleCatalog::CEXE)
515 INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
516 return Engines::Container::_nil();
518 MESSAGE("[GiveContainer] Exe container found !: " << container_exe_tmp);
519 container_exe = container_exe_tmp.in();
524 catch (ServiceUnreachable&)
526 INFOS("Caught exception: Naming Service Unreachable");
531 INFOS("Caught unknown exception.");
535 // Step 2: test resource
536 // Only if an application directory is set
537 if(hostname != Kernel_Utils::GetHostname() && _isAppliSalomeDefined)
540 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_selected));
541 std::string command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
542 resInfo.UserName, resInfo.AppliPath);
544 // Launch remote command
545 command += " \"ls /tmp >/dev/null 2>&1\"";
546 // Anthony : command is NO MORE launched to improve dramatically time to launch containers
550 // Error on resource - cannot launch commands
551 INFOS("[LaunchContainer] Cannot launch commands on machine " << hostname);
552 INFOS("[LaunchContainer] Command was " << command);
554 INFOS("[LaunchContainer] Command status is " << WEXITSTATUS(status));
556 return Engines::Container::_nil();
560 // Step 3: start a new container
561 // Check if a PaCO container
563 if (std::string(local_params.parallelLib.in()) != "")
565 ret = StartPaCOPPContainer(params, resource_selected);
568 // Other type of containers...
569 MESSAGE("[GiveContainer] Try to launch a new container on " << resource_selected);
570 // if a parallel container is launched in batch job, command is: "mpirun -np nbproc -machinefile nodesfile SALOME_MPIContainer"
571 if( GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL && params.isMPI )
572 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
573 // if a container is launched on localhost, command is "SALOME_Container" or "mpirun -np nbproc SALOME_MPIContainer"
574 else if(hostname == Kernel_Utils::GetHostname())
575 command = BuildCommandToLaunchLocalContainer(params, machFile, container_exe, tmpFileName);
576 // if a container is launched in remote mode, command is "ssh resource_selected SALOME_Container" or "ssh resource_selected mpirun -np nbproc SALOME_MPIContainer"
578 command = BuildCommandToLaunchRemoteContainer(resource_selected, params, container_exe);
580 //redirect stdout and stderr in a file
582 logFilename=GetenvThreadSafeAsString("TEMP");
584 user = GetenvThreadSafeAsString( "USERNAME" );
586 user = GetenvThreadSafeAsString( "USER" );
588 user = GetenvThreadSafeAsString( "LOGNAME" );
590 char* val = GetenvThreadSafe("SALOME_TMP_DIR");
593 struct stat file_info;
594 stat(val, &file_info);
595 bool is_dir = S_ISDIR(file_info.st_mode);
596 if (is_dir)logFilename=val;
597 else std::cerr << "SALOME_TMP_DIR environment variable is not a directory use /tmp instead" << std::endl;
601 logFilename += _NS->ContainerName(params)+"_"+ resource_selected +"_"+user;
602 std::ostringstream tmp;
603 tmp << "_" << getpid();
604 logFilename += tmp.str();
605 logFilename += ".log" ;
606 command += " > " + logFilename + " 2>&1";
607 MakeTheCommandToBeLaunchedASync(command);
609 // launch container with a system call
610 status=SystemThreadSafe(command.c_str());
611 }//end of critical of section
615 INFOS("[LaunchContainer] command failed (system command status -1): " << command);
616 RmTmpFile(tmpFileName); // command file can be removed here
617 return Engines::Container::_nil();
619 else if (status == 217)
621 INFOS("[LaunchContainer] command failed (system command status 217): " << command);
622 RmTmpFile(tmpFileName); // command file can be removed here
623 return Engines::Container::_nil();
627 // Step 4: Wait for the container
628 int count(GetTimeOutToLoaunchServer());
629 INFOS("[GiveContainer] waiting " << count << " second steps container " << containerNameInNS);
630 while (CORBA::is_nil(ret) && count)
634 MESSAGE("[GiveContainer] step " << count << " Waiting for container on " << resource_selected);
635 CORBA::Object_var obj(_NS->Resolve(containerNameInNS.c_str()));
636 ret=Engines::Container::_narrow(obj);
638 if (CORBA::is_nil(ret))
640 INFOS("[GiveContainer] was not able to launch container " << containerNameInNS);
644 // Setting log file name
645 logFilename=":"+logFilename;
646 logFilename="@"+Kernel_Utils::GetHostname()+logFilename;//threadsafe
647 logFilename=user+logFilename;
648 ret->logfilename(logFilename.c_str());
649 RmTmpFile(tmpFileName); // command file can be removed here
655 //=============================================================================
656 //! Find a container given constraints (params) on a list of machines (possibleComputers)
657 //! agy : this method is ThreadSafe
661 //=============================================================================
663 Engines::Container_ptr SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const Engines::ResourceList& possibleResources)
665 MESSAGE("[FindContainer] FindContainer on " << possibleResources.length() << " resources");
666 for(unsigned int i=0; i < possibleResources.length();i++)
668 Engines::Container_ptr cont = FindContainer(params, possibleResources[i].in());
669 if(!CORBA::is_nil(cont))
672 MESSAGE("[FindContainer] no container found");
673 return Engines::Container::_nil();
676 //=============================================================================
677 //! Find a container given constraints (params) on a machine (theMachine)
678 //! agy : this method is ThreadSafe
682 //=============================================================================
684 Engines::Container_ptr
685 SALOME_ContainerManager::FindContainer(const Engines::ContainerParameters& params, const std::string& resource)
687 ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource);
688 std::string hostname(resource_definition.HostName);
689 std::string containerNameInNS(_NS->BuildContainerNameForNS(params, hostname.c_str()));
690 MESSAGE("[FindContainer] Try to find a container " << containerNameInNS << " on resource " << resource);
691 CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
694 if(obj->_non_existent())
695 return Engines::Container::_nil();
697 return Engines::Container::_narrow(obj);
699 catch(const CORBA::Exception&)
701 return Engines::Container::_nil();
706 bool isPythonContainer(const char* ContainerName);
708 //=============================================================================
710 * This is no longer valid (C++ container are also python containers)
712 //=============================================================================
713 bool isPythonContainer(const char* ContainerName)
715 return false; // VSR 02/08/2013: Python containers are no more supported
717 size_t len = strlen(ContainerName);
720 if (strcmp(ContainerName + len - 2, "Py") == 0)
726 //=============================================================================
728 * Builds the script to be launched
730 * If SALOME Application not defined ($APPLI),
731 * see BuildTempFileToLaunchRemoteContainer()
733 * Else rely on distant configuration. Command is under the form (example):
734 * ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
735 * SALOME_Container containerName &"
737 * - where user is omitted if not specified in CatalogResources,
738 * - where distant path is always relative to user@machine $HOME, and
739 * equal to $APPLI if not specified in CatalogResources,
740 * - where hostNS is the hostname of CORBA naming server (set by scripts to
741 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
742 * - where portNS is the port used by CORBA naming server (set by scripts to
743 * use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
744 * - where workingdir is the requested working directory for the container.
745 * If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
747 //=============================================================================
750 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer(const std::string& resource_name, const Engines::ContainerParameters& params, const std::string& container_exe) const
752 std::string command,tmpFileName;
753 if (!_isAppliSalomeDefined)
754 command = BuildTempFileToLaunchRemoteContainer(resource_name, params, tmpFileName);
757 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
759 std::string wdir = params.workingdir.in();
761 // "ssh -l user machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir
762 // SALOME_Container containerName -ORBInitRef NameService=IOR:01000..."
764 // "ssh -l user machine distantLauncher remote -p hostNS -m portNS -d dir
765 // -- SALOME_Container contName -ORBInitRef NameService=IOR:01000..."
766 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
767 resInfo.UserName, resInfo.AppliPath,
772 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
773 command += " mpirun -np ";
774 std::ostringstream o;
778 command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
779 #elif defined(OPEN_MPI)
780 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
781 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
783 command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
784 command += GetenvThreadSafeAsString("OMPI_URI_FILE");
787 command += "-nameserver " + Kernel_Utils::GetHostname();
789 command += " SALOME_MPIContainer ";
792 command += " " +container_exe+ " ";
794 command += _NS->ContainerName(params) + " ";
797 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
798 CORBA::String_var iorNS = _orb->object_to_string(ns);
799 command += std::string(iorNS);
801 else //if(!this->_isSSL)
804 AddOmninamesParams(command);
806 MESSAGE("command =" << command);
812 //=============================================================================
813 //! Return a path to the directory with scripts templates
815 * \return the path pointed by SALOME_KERNEL_SCRIPTS_DIR environment variable, if it is defined,
816 * ${KERNEL_ROOT_DIR}/share/salome/resources/separator/kernel/ScriptsTemplate - otherwise
818 //=============================================================================
819 std::string getScriptTemplateFilePath()
821 auto parseScriptTemplateFilePath = []() -> std::string
823 std::string scriptTemplateFilePath = SALOME_ContainerManager::GetenvThreadSafeAsString("SALOME_KERNEL_SCRIPTS_DIR");
824 if (!scriptTemplateFilePath.empty())
826 return scriptTemplateFilePath;
829 return SALOME_ContainerManager::GetenvThreadSafeAsString("KERNEL_ROOT_DIR") +
830 "/share/salome/resources/kernel/ScriptsTemplate";
834 static const std::string scriptTemplateFilePath = parseScriptTemplateFilePath();
835 return scriptTemplateFilePath;
838 //=============================================================================
839 //! Return a command line constructed based on Python scripts templates
841 * \param theScriptName the name of Python script template
842 * \param theScriptParameters the queue of parameter values
843 * \return the command line constructed according to the given parameters
845 //=============================================================================
846 std::string GetCommandFromTemplate(const std::string& theScriptName,
847 std::queue<std::string>& theScriptParameters)
853 PyObject* mod(PyImport_ImportModule(theScriptName.c_str()));
856 PyObject* sys = PyImport_ImportModule("sys");
857 PyObject* sys_path = PyObject_GetAttrString(sys, "path");
858 PyObject* folder_path = PyUnicode_FromString(getScriptTemplateFilePath().c_str());
859 PyList_Append(sys_path, folder_path);
861 mod = PyImport_ImportModule(theScriptName.c_str());
863 Py_XDECREF(folder_path);
864 Py_XDECREF(sys_path);
870 PyObject* meth(PyObject_GetAttrString(mod, "command"));
878 PyObject* tuple(PyTuple_New(theScriptParameters.size()));
880 auto insert_parameter = [&tuple, &theScriptParameters, &id]()
882 if (!theScriptParameters.empty())
884 PyTuple_SetItem(tuple, ++id, PyUnicode_FromString(theScriptParameters.front().c_str()));
885 theScriptParameters.pop();
889 while (!theScriptParameters.empty())
894 PyObject *args(PyTuple_New(1));
895 PyTuple_SetItem(args, 0, tuple);
897 PyObject *res(PyObject_CallObject(meth, args));
900 command = PyUnicode_AsUTF8(res);
911 MESSAGE("Command from template is ... " << command << std::endl);
914 //=============================================================================
916 //=============================================================================
918 * builds the command to be launched.
920 //=============================================================================
921 std::string SALOME_ContainerManager::BuildCommandToLaunchLocalContainer(const Engines::ContainerParameters& params, const std::string& machinesFile, const std::string& container_exe, std::string& tmpFileName) const
923 // Prepare name of the script to be used
924 std::string script_name = "SALOME_CM_LOCAL_NO_MPI";
928 script_name = "SALOME_CM_LOCAL_MPI_LAN";
929 #elif defined(OPEN_MPI)
930 script_name = "SALOME_CM_LOCAL_MPI_OPENMPI";
932 script_name = "SALOME_CM_LOCAL_MPI_MPICH";
936 // Prepare parameters to use in the Python script:
937 // 1. All parameters are strings.
938 // 2. For some booleans use "1" = True, "0" = False.
939 // 3. If a parameter is NULL, then its value is "NULL".
941 std::queue<std::string> script_parameters;
943 // ===== Number of processes (key = "nb_proc")
944 script_parameters.push(params.isMPI ? std::to_string(params.nb_proc <= 0 ? 1 : params.nb_proc) : "NULL");
946 // ===== Working directory (key = "workdir") and temporary directory flag (key = "isTmpDir")
947 // A working directory is requested
948 std::string workdir = params.workingdir.in();
949 std::string isTmpDir = std::to_string(0);
950 if (workdir == "$TEMPDIR")
952 // A new temporary directory is requested
953 isTmpDir = std::to_string(1);
954 workdir = Kernel_Utils::GetTmpDir();
956 script_parameters.push(workdir);
957 script_parameters.push(isTmpDir);
959 // ===== Server name (key = "name_server")
960 script_parameters.push(Kernel_Utils::GetHostname());
962 // ===== Container (key = "container")
963 std::string container;
966 container = isPythonContainer(params.container_name) ? "pyMPI SALOME_ContainerPy.py" : "SALOME_MPIContainer";
970 container = isPythonContainer(params.container_name) ? "SALOME_ContainerPy.py" : container_exe;
972 script_parameters.push(container);
974 // ===== Container name (key = "container_name")
975 script_parameters.push(_NS->ContainerName(params));
977 // ===== LIBBATCH node file (key = "libbatch_nodefile")
978 script_parameters.push(std::to_string(GetenvThreadSafe("LIBBATCH_NODEFILE") != NULL ? 1 : 0));
980 // ===== Machine file (key = "machine_file")
981 script_parameters.push(machinesFile.empty() ? "NULL" : machinesFile);
983 // ===== OMPI uri file (key = "ompi_uri_file")
984 std::string ompi_uri_file = GetenvThreadSafeAsString("OMPI_URI_FILE");
985 script_parameters.push(ompi_uri_file.empty() ? "NULL" : ompi_uri_file);
987 std::string command_from_template = GetCommandFromTemplate(script_name, script_parameters);
989 std::ostringstream o;
990 o << command_from_template << " ";
992 //==================================================================================== */
996 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
997 CORBA::String_var iorNS = _orb->object_to_string(ns);
1003 AddOmninamesParams(o);
1006 tmpFileName = BuildTemporaryFileName();
1007 std::ofstream command_file( tmpFileName.c_str() );
1008 command_file << o.str();
1009 command_file.close();
1012 chmod(tmpFileName.c_str(), 0x1ED);
1015 std::string command = tmpFileName;
1016 MESSAGE("Command is file ... " << command);
1017 MESSAGE("Command is ... " << o.str());
1022 //=============================================================================
1024 * removes the generated temporary file in case of a remote launch.
1025 * This method is thread safe
1027 //=============================================================================
1029 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
1031 size_t length = tmpFileName.size();
1035 std::string command = "del /F ";
1037 std::string command = "rm ";
1040 command += tmpFileName.substr(0, length - 3 );
1042 command += tmpFileName;
1044 SystemThreadSafe(command.c_str());
1045 //if dir is empty - remove it
1046 std::string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
1047 if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
1050 command = "del /F " + tmp_dir;
1052 command = "rmdir " + tmp_dir;
1054 SystemThreadSafe(command.c_str());
1059 //=============================================================================
1061 * add to command all options relative to naming service.
1063 //=============================================================================
1065 void SALOME_ContainerManager::AddOmninamesParams(std::string& command) const
1067 std::ostringstream oss;
1068 AddOmninamesParams(oss);
1072 //=============================================================================
1074 * add to command all options relative to naming service.
1076 //=============================================================================
1078 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream) const
1080 AddOmninamesParams(fileStream,_NS);
1083 //=============================================================================
1085 * add to command all options relative to naming service.
1087 //=============================================================================
1089 void SALOME_ContainerManager::AddOmninamesParams(std::ostream& fileStream, SALOME_NamingService_Abstract *ns)
1091 SALOME_NamingService *nsTrad(dynamic_cast<SALOME_NamingService *>(ns));
1094 CORBA::String_var iorstr(nsTrad->getIORaddr());
1095 fileStream << "ORBInitRef NameService=";
1096 fileStream << iorstr;
1100 void SALOME_ContainerManager::MakeTheCommandToBeLaunchedASync(std::string& command)
1103 command = "%PYTHONBIN% -c \"import subprocess ; subprocess.Popen(r'" + command + "').pid\"";
1109 int SALOME_ContainerManager::GetTimeOutToLoaunchServer()
1111 int count(TIME_OUT_TO_LAUNCH_CONT);
1112 if (GetenvThreadSafe("TIMEOUT_TO_LAUNCH_CONTAINER") != 0)
1114 std::string new_count_str(GetenvThreadSafeAsString("TIMEOUT_TO_LAUNCH_CONTAINER"));
1116 std::istringstream ss(new_count_str);
1117 if (!(ss >> new_count))
1119 INFOS("[LaunchContainer] TIMEOUT_TO_LAUNCH_CONTAINER should be an int");
1127 void SALOME_ContainerManager::SleepInSecond(int ellapseTimeInSecond)
1130 sleep( ellapseTimeInSecond ) ;
1132 int timeInMS(1000*ellapseTimeInSecond);
1137 //=============================================================================
1139 * generate a file name in /tmp directory
1141 //=============================================================================
1143 std::string SALOME_ContainerManager::BuildTemporaryFileName()
1145 //build more complex file name to support multiple salome session
1146 std::string aFileName = Kernel_Utils::GetTmpFileName();
1147 std::ostringstream str_pid;
1148 str_pid << ::getpid();
1149 aFileName = aFileName + "-" + str_pid.str();
1153 aFileName += ".bat";
1158 //=============================================================================
1160 * Builds in a temporary file the script to be launched.
1162 * Used if SALOME Application ($APPLI) is not defined.
1163 * The command is build with data from CatalogResources, in which every path
1164 * used on remote computer must be defined.
1166 //=============================================================================
1168 std::string SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer (const std::string& resource_name, const Engines::ContainerParameters& params, std::string& tmpFileName) const
1172 tmpFileName = BuildTemporaryFileName();
1173 std::ofstream tempOutputFile;
1174 tempOutputFile.open(tmpFileName.c_str(), std::ofstream::out );
1175 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(resource_name));
1176 tempOutputFile << "#! /bin/sh" << std::endl;
1180 tempOutputFile << "export SALOME_trace=local" << std::endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1181 //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1187 int nbproc = params.nb_proc <= 0 ? 1 : params.nb_proc;
1189 tempOutputFile << "mpirun -np ";
1191 tempOutputFile << nbproc << " ";
1193 tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1194 #elif defined(OPEN_MPI)
1195 if( GetenvThreadSafe("OMPI_URI_FILE") == NULL )
1196 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1198 tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1199 tempOutputFile << GetenvThreadSafeAsString("OMPI_URI_FILE");
1201 #elif defined(MPICH)
1202 tempOutputFile << "-nameserver " + Kernel_Utils::GetHostname();
1206 tempOutputFile << GetenvThreadSafeAsString("KERNEL_ROOT_DIR") << "/bin/salome/";
1210 if (isPythonContainer(params.container_name))
1211 tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1213 tempOutputFile << " SALOME_MPIContainer ";
1218 if (isPythonContainer(params.container_name))
1219 tempOutputFile << "SALOME_ContainerPy.py ";
1221 tempOutputFile << "SALOME_Container ";
1224 tempOutputFile << _NS->ContainerName(params) << " -";
1225 AddOmninamesParams(tempOutputFile);
1226 tempOutputFile << " &" << std::endl;
1227 tempOutputFile.flush();
1228 tempOutputFile.close();
1230 chmod(tmpFileName.c_str(), 0x1ED);
1233 // --- Build command
1235 std::string command;
1237 if (resInfo.Protocol == rsh)
1240 std::string commandRcp = "rcp ";
1241 commandRcp += tmpFileName;
1243 commandRcp += resInfo.HostName;
1245 commandRcp += tmpFileName;
1246 status = SystemThreadSafe(commandRcp.c_str());
1249 else if (resInfo.Protocol == ssh)
1252 std::string commandRcp = "scp ";
1253 commandRcp += tmpFileName;
1255 commandRcp += resInfo.HostName;
1257 commandRcp += tmpFileName;
1258 status = SystemThreadSafe(commandRcp.c_str());
1261 else if (resInfo.Protocol == srun)
1263 command = "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=";
1264 std::string commandRcp = "rcp ";
1265 commandRcp += tmpFileName;
1267 commandRcp += resInfo.HostName;
1269 commandRcp += tmpFileName;
1270 status = SystemThreadSafe(commandRcp.c_str());
1273 throw SALOME_Exception("Unknown protocol");
1276 throw SALOME_Exception("Error of connection on remote host");
1278 command += resInfo.HostName;
1280 command += tmpFileName;
1288 std::string SALOME_ContainerManager::GetMPIZeroNode(const std::string machine, const std::string machinesFile) const
1291 std::string zeronode;
1292 std::string command;
1293 std::string tmpFile = BuildTemporaryFileName();
1294 const ParserResourcesType resInfo(_resManager->GetResourceDefinition(machine));
1296 if(resInfo.Protocol == sh)
1298 return resInfo.HostName;
1301 if( GetenvThreadSafe("LIBBATCH_NODEFILE") == NULL )
1303 if (_isAppliSalomeDefined)
1305 command = getCommandToRunRemoteProcess(resInfo.Protocol, resInfo.HostName,
1306 resInfo.UserName, resInfo.AppliPath);
1307 command += " mpirun -np 1 hostname -s > " + tmpFile;
1310 command = "mpirun -np 1 hostname -s > " + tmpFile;
1313 command = "mpirun -np 1 -machinefile " + machinesFile + " hostname -s > " + tmpFile;
1315 status = SystemThreadSafe(command.c_str());
1317 std::ifstream fp(tmpFile.c_str(),std::ios::in);
1318 while(fp >> zeronode);
1326 std::string SALOME_ContainerManager::machinesFile(const int nbproc)
1329 std::string nodesFile = GetenvThreadSafeAsString("LIBBATCH_NODEFILE");
1330 std::string machinesFile = Kernel_Utils::GetTmpFileName();
1331 std::ifstream fpi(nodesFile.c_str(),std::ios::in);
1332 std::ofstream fpo(machinesFile.c_str(),std::ios::out);
1334 _numInstanceMutex.lock();
1336 for(int i=0;i<_nbprocUsed;i++)
1339 for(int i=0;i<nbproc;i++)
1341 fpo << tmp << std::endl;
1343 throw SALOME_Exception("You need more processors than batch session have allocated for you! Unable to launch the mpi container: ");
1345 _nbprocUsed += nbproc;
1349 _numInstanceMutex.unlock();
1351 return machinesFile;
1355 std::string SALOME_ContainerManager::getCommandToRunRemoteProcess(AccessProtocolType protocol,
1356 const std::string & hostname,
1357 const std::string & username,
1358 const std::string & applipath,
1359 const std::string & workdir) const
1361 std::ostringstream command;
1363 // Prepare parameters to use in the Python script:
1364 // 1. All parameters are strings.
1365 // 2. For some booleans use "1" = True, "0" = False.
1366 // 3. If a parameter is NULL, then its value is "NULL".
1368 std::queue<std::string> script_parameters;
1370 // ===== Protocol (key = "protocol")
1371 std::string strProtocol;
1374 case rsh: strProtocol = "rsh"; break;
1375 case ssh: strProtocol = "ssh"; break;
1376 case srun: strProtocol = "srun"; break;
1377 case pbsdsh: strProtocol = "pbsdsh"; break;
1378 case blaunch: strProtocol = "blaunch"; break;
1380 throw SALOME_Exception("Unknown protocol");
1382 script_parameters.push(strProtocol);
1384 // ===== User name (key = "user")
1385 script_parameters.push(username.empty() ? "NULL" : username);
1387 // ===== Host name (key = "host")
1388 script_parameters.push(hostname.empty() ? "NULL" : hostname);
1391 // ===== Remote APPLI path (key = "appli")
1392 script_parameters.push(applipath.empty() ? GetenvThreadSafeAsString("APPLI") : applipath);
1396 ASSERT(GetenvThreadSafe("NSHOST"));
1397 ASSERT(GetenvThreadSafe("NSPORT"));
1400 struct stat statbuf;
1401 std::string appli_mode = (stat(GetenvThreadSafe("APPLI"), &statbuf) == 0 && S_ISREG(statbuf.st_mode)) ? "launcher" : "dir";
1403 // ===== Working directory (key = "workdir")
1404 script_parameters.push(workdir == "$TEMPDIR" ? "\\$TEMPDIR" : workdir);
1406 // ===== SSL (key = "ssl")
1407 script_parameters.push(this->_isSSL ? "1" : "0");
1409 // ===== Hostname of CORBA name server (key = "nshost")
1410 std::string nshost = GetenvThreadSafeAsString("NSHOST");
1411 script_parameters.push(nshost.empty() ? "NULL" : nshost);
1413 // ===== Port of CORBA name server (key = "nsport")
1414 std::string nsport = GetenvThreadSafeAsString("NSPORT");
1415 script_parameters.push(nsport.empty() ? "NULL" : nsport);
1417 // ===== Remote script (key = "remote_script")
1418 std::string remoteScript = this->GetRunRemoteExecutableScript();
1419 script_parameters.push(remoteScript.empty() ? "NONE" : remoteScript);
1421 // ===== Naming service (key = "naming_service")
1422 std::string namingService = "NONE";
1425 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1426 CORBA::String_var iorNS = _orb->object_to_string(ns);
1427 namingService = iorNS;
1429 script_parameters.push(namingService);
1431 // ===== APPLI mode (key = "appli_mode")
1432 // $APPLI points either to an application directory, or to a salome launcher file
1433 // we prepare the remote command according to the case
1434 script_parameters.push(appli_mode);
1436 command << GetCommandFromTemplate("SALOME_CM_REMOTE", script_parameters);
1438 /* //====================================================================================
1439 bool envd = true; // source the environment
1446 command << "-l " << username << " ";
1448 command << hostname << " ";
1454 command << "-l " << username << " ";
1456 command << hostname << " ";
1459 // no need to redefine the user with srun, the job user is taken by default
1460 // (note: for srun, user id can be specified with " --uid=<user>")
1461 command << "srun -n 1 -N 1 -s --mem-per-cpu=0 --cpu-bind=none --nodelist=" << hostname << " ";
1465 command << "pbsdsh -o -h " << hostname << " ";
1468 command << "blaunch -no-shell " << hostname << " ";
1471 throw SALOME_Exception("Unknown protocol");
1474 std::string remoteapplipath;
1476 remoteapplipath = GetenvThreadSafeAsString("APPLI");
1478 remoteapplipath = applipath;
1482 ASSERT(GetenvThreadSafe("NSHOST"));
1483 ASSERT(GetenvThreadSafe("NSPORT"));
1485 // $APPLI points either to an application directory, or to a salome launcher file
1486 // we prepare the remote command according to the case
1487 struct stat statbuf;
1488 if (stat(GetenvThreadSafe("APPLI"), &statbuf) ==0 && S_ISREG(statbuf.st_mode))
1490 // if $APPLI is a regular file, we asume it's a salome Launcher
1491 // generate a command with a salome launcher
1492 command << remoteapplipath
1497 << GetenvThreadSafeAsString("NSHOST") // hostname of CORBA name server
1499 << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1502 command << "-d " << workdir;
1505 else // we assume it's a salome application directory
1507 // generate a command with runRemote.sh
1508 command << remoteapplipath;
1509 command << "/" << this->GetRunRemoteExecutableScript() << " ";
1511 command << "--noenvd ";
1515 Engines::EmbeddedNamingService_var ns = GetEmbeddedNamingService();
1516 CORBA::String_var iorNS = _orb->object_to_string(ns);
1521 command << GetenvThreadSafeAsString("NSHOST"); // hostname of CORBA name server
1523 command << GetenvThreadSafeAsString("NSPORT"); // port of CORBA name server
1528 command << " WORKINGDIR ";
1530 if(workdir == "$TEMPDIR")
1531 command << "\\$TEMPDIR";
1533 command << workdir; // requested working directory
1537 //==================================================================================== */
1539 return command.str();
1543 SALOME_ContainerManager::checkPaCOParameters(Engines::ContainerParameters & params, std::string resource_selected)
1547 // Step 1 : check ContainerParameters
1548 // Check container_name, has to be defined
1549 if (std::string(params.container_name.in()) == "")
1551 INFOS("[checkPaCOParameters] You must define a container_name to launch a PaCO++ container");
1554 // Check parallelLib
1555 std::string parallelLib = params.parallelLib.in();
1556 if (parallelLib != "Mpi" && parallelLib != "Dummy")
1558 INFOS("[checkPaCOParameters] parallelLib is not correctly defined");
1559 INFOS("[checkPaCOParameters] you can chosse between: Mpi and Dummy");
1560 INFOS("[checkPaCOParameters] you entered: " << parallelLib);
1564 if (params.nb_proc <= 0)
1566 INFOS("[checkPaCOParameters] You must define a nb_proc > 0");
1570 // Step 2 : check resource_selected
1571 const ParserResourcesType resource_definition = _resManager->GetResourceDefinition(resource_selected);
1572 //std::string protocol = resource_definition->protocol.in();
1573 std::string username = resource_definition.UserName;
1574 std::string applipath = resource_definition.AppliPath;
1576 //if (protocol == "" || username == "" || applipath == "")
1577 if (username == "" || applipath == "")
1579 INFOS("[checkPaCOParameters] resource selected is not well defined");
1580 INFOS("[checkPaCOParameters] resource name: " << resource_definition.Name);
1581 INFOS("[checkPaCOParameters] resource hostname: " << resource_definition.HostName);
1582 INFOS("[checkPaCOParameters] resource protocol: " << resource_definition.getAccessProtocolTypeStr());
1583 INFOS("[checkPaCOParameters] resource username: " << username);
1584 INFOS("[checkPaCOParameters] resource applipath: " << applipath);
1592 * :WARNING: Do not directly convert returned value to std::string
1593 * This function may return NULL if env variable is not defined.
1594 * And std::string(NULL) causes undefined behavior.
1595 * Use GetenvThreadSafeAsString to properly get a std::string.
1597 char *SALOME_ContainerManager::GetenvThreadSafe(const char *name)
1598 {// getenv is not thread safe. See man 7 pthread.
1599 Utils_Locker lock (&_getenvMutex);
1600 return getenv(name);
1604 * Return env variable as a std::string.
1605 * Return empty string if env variable is not set.
1607 std::string SALOME_ContainerManager::GetenvThreadSafeAsString(const char *name)
1609 char* var = GetenvThreadSafe(name);
1610 return var ? std::string(var) : std::string();
1613 int SALOME_ContainerManager::SystemThreadSafe(const char *command)
1615 Utils_Locker lock (&_systemMutex);
1616 return system(command);
1619 long SALOME_ContainerManager::SystemWithPIDThreadSafe(const std::vector<std::string>& command)
1621 Utils_Locker lock(&_systemMutex);
1622 if(command.size()<1)
1623 throw SALOME_Exception("SystemWithPIDThreadSafe : command is expected to have a length of size 1 at least !");
1625 pid_t pid ( fork() ) ; // spawn a child process, following code is executed in both processes
1627 pid_t pid = -1; //Throw SALOME_Exception on Windows
1629 if ( pid == 0 ) // I'm a child, replace myself with a new ompi-server
1631 std::size_t sz(command.size());
1632 char **args = new char *[sz+1];
1633 for(std::size_t i=0;i<sz;i++)
1634 args[i] = strdup(command[i].c_str());
1636 execvp( command[0].c_str() , args );
1637 std::ostringstream oss;
1638 oss << "Error when launching " << command[0];
1639 throw SALOME_Exception(oss.str().c_str()); // execvp failed
1643 throw SALOME_Exception("fork() failed");
1645 else // I'm a parent
1651 #ifdef WITH_PACO_PARALLEL
1653 //=============================================================================
1655 * Start a suitable PaCO++ Parallel Container in a list of machines.
1656 * \param params Container Parameters required for the container
1657 * \return CORBA container reference.
1659 //=============================================================================
1660 Engines::Container_ptr
1661 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& params_const,
1662 std::string resource_selected)
1664 CORBA::Object_var obj;
1665 PaCO::InterfaceManager_var container_proxy;
1666 Engines::Container_ptr ret = Engines::Container::_nil();
1667 Engines::ContainerParameters params(params_const);
1668 params.resource_params.name = CORBA::string_dup(resource_selected.c_str());
1670 // Step 0 : Check parameters
1671 if (!checkPaCOParameters(params, resource_selected))
1673 INFOS("[StartPaCOPPContainer] check parameters failed ! see logs...");
1677 // Step 1 : Starting a new parallel container !
1678 INFOS("[StartPaCOPPContainer] Starting a PaCO++ parallel container");
1679 INFOS("[StartPaCOPPContainer] on resource : " << resource_selected);
1681 // Step 2 : Get a MachineFile for the parallel container
1682 std::string machine_file_name = _resManager->getMachineFile(resource_selected,
1684 params.parallelLib.in());
1686 if (machine_file_name == "")
1688 INFOS("[StartPaCOPPContainer] Machine file generation failed");
1692 // Step 3 : starting parallel container proxy
1693 std::string command_proxy("");
1694 std::string proxy_machine;
1697 command_proxy = BuildCommandToLaunchPaCOProxyContainer(params, machine_file_name, proxy_machine);
1699 catch(const SALOME_Exception & ex)
1701 INFOS("[StartPaCOPPContainer] Exception in BuildCommandToLaunchPaCOContainer");
1705 obj = LaunchPaCOProxyContainer(command_proxy, params, proxy_machine);
1706 if (CORBA::is_nil(obj))
1708 INFOS("[StartPaCOPPContainer] LaunchPaCOContainer for proxy returns NIL !");
1711 container_proxy = PaCO::InterfaceManager::_narrow(obj);
1712 MESSAGE("[StartPaCOPPContainer] PaCO container proxy is launched");
1714 // Step 4 : starting parallel container nodes
1715 std::string command_nodes("");
1716 SALOME_ContainerManager::actual_launch_machine_t nodes_machines;
1719 command_nodes = BuildCommandToLaunchPaCONodeContainer(params, machine_file_name, nodes_machines, proxy_machine);
1721 catch(const SALOME_Exception & ex)
1723 INFOS("[StarPaCOPPContainer] Exception in BuildCommandToLaunchPaCONodeContainer");
1728 std::string container_generic_node_name = std::string(params.container_name.in()) + std::string("Node");
1729 bool result = LaunchPaCONodeContainer(command_nodes, params, container_generic_node_name, nodes_machines);
1732 INFOS("[StarPaCOPPContainer] LaunchPaCONodeContainer failed !");
1733 // Il faut tuer le proxy
1736 Engines::Container_var proxy = Engines::Container::_narrow(container_proxy);
1741 INFOS("[StarPaCOPPContainer] Exception caught from proxy Shutdown...");
1746 // Step 4 : connecting nodes and the proxy to actually create a parallel container
1747 for (int i = 0; i < params.nb_proc; i++)
1749 std::ostringstream tmp;
1751 std::string proc_number = tmp.str();
1752 std::string container_node_name = container_generic_node_name + proc_number;
1754 std::string theNodeMachine(nodes_machines[i]);
1755 std::string containerNameInNS = _NS->BuildContainerNameForNS(container_node_name.c_str(), theNodeMachine.c_str());
1756 obj = _NS->Resolve(containerNameInNS.c_str());
1757 if (CORBA::is_nil(obj))
1759 INFOS("[StarPaCOPPContainer] CONNECTION FAILED From Naming Service !");
1760 INFOS("[StarPaCOPPContainer] Container name is " << containerNameInNS);
1765 MESSAGE("[StarPaCOPPContainer] Deploying node : " << container_node_name);
1766 PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
1768 MESSAGE("[StarPaCOPPContainer] node " << container_node_name << " is deployed");
1770 catch(CORBA::SystemException& e)
1772 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1773 INFOS("CORBA::SystemException : " << e);
1776 catch(CORBA::Exception& e)
1778 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1779 INFOS("CORBA::Exception" << e);
1784 INFOS("[StarPaCOPPContainer] Exception in deploying node : " << containerNameInNS);
1785 INFOS("Unknown exception !");
1790 // Step 5 : starting parallel container
1793 MESSAGE ("[StarPaCOPPContainer] Starting parallel object");
1794 container_proxy->start();
1795 MESSAGE ("[StarPaCOPPContainer] Parallel object is started");
1796 ret = Engines::Container::_narrow(container_proxy);
1798 catch(CORBA::SystemException& e)
1800 INFOS("Caught CORBA::SystemException. : " << e);
1802 catch(PortableServer::POA::ServantAlreadyActive&)
1804 INFOS("Caught CORBA::ServantAlreadyActiveException");
1806 catch(CORBA::Exception&)
1808 INFOS("Caught CORBA::Exception.");
1810 catch(std::exception& exc)
1812 INFOS("Caught std::exception - "<<exc.what());
1816 INFOS("Caught unknown exception.");
1822 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& params,
1823 std::string machine_file_name,
1824 std::string & proxy_hostname)
1826 // In the proxy case, we always launch a Dummy Proxy
1827 std::string exe_name = "SALOME_ParallelContainerProxyDummy";
1828 std::string container_name = params.container_name.in();
1830 // Convert nb_proc in string
1831 std::ostringstream tmp_string;
1832 tmp_string << params.nb_proc;
1833 std::string nb_proc_str = tmp_string.str();
1835 // Get resource definition
1836 ParserResourcesType resource_definition =
1837 _resManager->GetResourceDefinition(params.resource_params.name.in());
1840 std::string hostname;
1841 std::ifstream machine_file(machine_file_name.c_str());
1842 std::getline(machine_file, hostname, ' ');
1843 size_t found = hostname.find('\n');
1844 if (found!=std::string::npos)
1845 hostname.erase(found, 1); // Remove \n
1846 proxy_hostname = hostname;
1847 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] machine file name extracted is " << hostname);
1850 bool remote_execution = false;
1851 if (hostname != std::string(Kernel_Utils::GetHostname()))
1853 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] remote machine case detected !");
1854 remote_execution = true;
1858 std::string log_type("");
1859 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1863 // Generating the command
1864 std::string command_begin("");
1865 std::string command_end("");
1866 std::ostringstream command;
1868 LogConfiguration(log_type, "proxy", container_name, hostname, command_begin, command_end);
1869 command << command_begin;
1871 // Adding connection command
1872 // We can only have a remote execution with
1873 // a SALOME application
1874 if (remote_execution)
1876 ASSERT(GetenvThreadSafe("NSHOST"));
1877 ASSERT(GetenvThreadSafe("NSPORT"));
1879 command << resource_definition.getAccessProtocolTypeStr();
1881 command << resource_definition.UserName;
1882 command << " " << hostname;
1883 command << " " << resource_definition.AppliPath;
1884 command << "/runRemote.sh ";
1885 command << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1886 command << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1889 command << exe_name;
1890 command << " " << container_name;
1891 command << " Dummy";
1892 command << " " << hostname;
1893 command << " " << nb_proc_str;
1895 AddOmninamesParams(command);
1898 command << command_end;
1899 MESSAGE("[BuildCommandToLaunchPaCOProxyContainer] Command is: " << command.str());
1901 return command.str();
1905 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& params,
1906 const std::string & machine_file_name,
1907 SALOME_ContainerManager::actual_launch_machine_t & vect_machine,
1908 const std::string & proxy_hostname)
1911 std::string exe_name = "SALOME_ParallelContainerNode";
1912 exe_name += params.parallelLib.in();
1913 std::string container_name = params.container_name.in();
1915 // Convert nb_proc in string
1916 std::ostringstream nb_proc_stream;
1917 nb_proc_stream << params.nb_proc;
1919 // Get resource definition
1920 ParserResourcesType resource_definition =
1921 _resManager->GetResourceDefinition(params.resource_params.name.in());
1924 std::string log_type("");
1925 char * get_val = GetenvThreadSafe("PARALLEL_LOG");
1929 // Now the command is different according to paralleLib
1930 std::ostringstream command_nodes;
1931 std::ifstream machine_file(machine_file_name.c_str());
1932 if (std::string(params.parallelLib.in()) == "Dummy")
1934 for (int i= 0; i < params.nb_proc; i++)
1937 std::string hostname;
1938 std::getline(machine_file, hostname);
1939 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1942 bool remote_execution = false;
1943 if (hostname != std::string(Kernel_Utils::GetHostname()))
1945 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
1946 remote_execution = true;
1949 // For each node we have a new command
1950 // Generating the command
1951 std::ostringstream command_node_stream;
1952 std::string command_node_begin("");
1953 std::string command_node_end("");
1954 std::ostringstream node_number;
1956 std::string container_node_name = container_name + node_number.str();
1957 LogConfiguration(log_type, "node", container_node_name, hostname, command_node_begin, command_node_end);
1959 // Adding connection command
1960 // We can only have a remote execution with
1961 // a SALOME application
1962 if (remote_execution)
1964 ASSERT(GetenvThreadSafe("NSHOST"));
1965 ASSERT(GetenvThreadSafe("NSPORT"));
1967 command_node_stream << resource_definition.getAccessProtocolTypeStr();
1968 command_node_stream << " -l ";
1969 command_node_stream << resource_definition.UserName;
1970 command_node_stream << " " << hostname;
1971 command_node_stream << " " << resource_definition.AppliPath;
1972 command_node_stream << "/runRemote.sh ";
1973 command_node_stream << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
1974 command_node_stream << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
1977 command_node_stream << exe_name;
1978 command_node_stream << " " << container_name;
1979 command_node_stream << " " << params.parallelLib.in();
1980 command_node_stream << " " << proxy_hostname;
1981 command_node_stream << " " << node_number.str();
1982 command_node_stream << " -";
1983 AddOmninamesParams(command_node_stream);
1985 command_nodes << command_node_begin << command_node_stream.str() << command_node_end;
1986 vect_machine.push_back(hostname);
1990 else if (std::string(params.parallelLib.in()) == "Mpi")
1993 std::string hostname;
1994 std::getline(machine_file, hostname, ' ');
1995 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] machine file name extracted is " << hostname);
1998 bool remote_execution = false;
1999 if (hostname != std::string(Kernel_Utils::GetHostname()))
2001 MESSAGE("[BuildCommandToLaunchPaCONodeContainer] remote machine case detected !");
2002 remote_execution = true;
2005 // In case of Mpi and Remote, we copy machine_file in the applipath
2006 // scp mpi_machine_file user@machine:Path
2007 std::ostringstream command_remote_stream;
2008 std::string::size_type last = machine_file_name.find_last_of("/");
2009 if (last == std::string::npos)
2012 if (resource_definition.Protocol == rsh)
2013 command_remote_stream << "rcp ";
2015 command_remote_stream << "scp ";
2016 command_remote_stream << machine_file_name << " ";
2017 command_remote_stream << resource_definition.UserName << "@";
2018 command_remote_stream << hostname << ":" << resource_definition.AppliPath;
2019 command_remote_stream << "/" << machine_file_name.substr(last+1);
2021 int status = SystemThreadSafe(command_remote_stream.str().c_str());
2024 INFOS("copy of the MPI machine file failed ! - sorry !");
2028 // Generating the command
2029 std::string command_begin("");
2030 std::string command_end("");
2032 LogConfiguration(log_type, "nodes", container_name, hostname, command_begin, command_end);
2033 command_nodes << command_begin;
2035 // Adding connection command
2036 // We can only have a remote execution with
2037 // a SALOME application
2038 if (remote_execution)
2040 ASSERT(GetenvThreadSafe("NSHOST"));
2041 ASSERT(GetenvThreadSafe("NSPORT"));
2043 command_nodes << resource_definition.getAccessProtocolTypeStr();
2044 command_nodes << " -l ";
2045 command_nodes << resource_definition.UserName;
2046 command_nodes << " " << hostname;
2047 command_nodes << " " << resource_definition.AppliPath;
2048 command_nodes << "/runRemote.sh ";
2049 command_nodes << GetenvThreadSafeAsString("NSHOST") << " "; // hostname of CORBA name server
2050 command_nodes << GetenvThreadSafeAsString("NSPORT") << " "; // port of CORBA name server
2053 if (resource_definition.mpi == lam)
2055 command_nodes << "mpiexec -ssi boot ";
2056 command_nodes << "-machinefile " << machine_file_name << " ";
2057 command_nodes << "-n " << params.nb_proc;
2061 command_nodes << "mpirun -np " << params.nb_proc;
2063 command_nodes << " " << exe_name;
2064 command_nodes << " " << container_name;
2065 command_nodes << " " << params.parallelLib.in();
2066 command_nodes << " " << proxy_hostname;
2067 command_nodes << " -";
2068 AddOmninamesParams(command_nodes);
2070 // We don't put hostname, because nodes are registered in the resource of the proxy
2071 for (int i= 0; i < params.nb_proc; i++)
2072 vect_machine.push_back(proxy_hostname);
2074 command_nodes << command_end;
2076 return command_nodes.str();
2080 SALOME_ContainerManager::LogConfiguration(const std::string & log_type,
2081 const std::string & exe_type,
2082 const std::string & container_name,
2083 const std::string & hostname,
2084 std::string & begin,
2087 if(log_type == "xterm")
2089 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2092 else if(log_type == "xterm_debug")
2094 begin = "xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;";
2099 // default into a file...
2100 std::string logFilename = "/tmp/" + container_name + "_" + hostname + "_" + exe_type + "_";
2101 std::string user = GetenvThreadSafeAsString("USER");
2103 user = GetenvThreadSafeAsString("LOGNAME");
2104 logFilename += user + ".log";
2105 end = " > " + logFilename + " 2>&1 & ";
2110 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& command,
2111 const Engines::ContainerParameters& params,
2112 const std::string & hostname)
2114 PaCO::InterfaceManager_ptr container_proxy = PaCO::InterfaceManager::_nil();
2116 MESSAGE("[LaunchPaCOProxyContainer] Launch command");
2117 int status = SystemThreadSafe(command.c_str());
2119 INFOS("[LaunchPaCOProxyContainer] failed : system command status -1");
2120 return container_proxy;
2122 else if (status == 217) {
2123 INFOS("[LaunchPaCOProxyContainer] failed : system command status 217");
2124 return container_proxy;
2127 int count(GetTimeOutToLoaunchServer());
2128 CORBA::Object_var obj = CORBA::Object::_nil();
2129 std::string containerNameInNS = _NS->BuildContainerNameForNS(params.container_name.in(),
2131 MESSAGE("[LaunchParallelContainer] Waiting for Parallel Container proxy : " << containerNameInNS);
2133 while (CORBA::is_nil(obj) && count)
2137 obj = _NS->Resolve(containerNameInNS.c_str());
2142 container_proxy = PaCO::InterfaceManager::_narrow(obj);
2144 catch(CORBA::SystemException& e)
2146 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2147 INFOS("CORBA::SystemException : " << e);
2148 return container_proxy;
2150 catch(CORBA::Exception& e)
2152 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2153 INFOS("CORBA::Exception" << e);
2154 return container_proxy;
2158 INFOS("[StarPaCOPPContainer] Exception in _narrow after LaunchParallelContainer for proxy !");
2159 INFOS("Unknown exception !");
2160 return container_proxy;
2162 if (CORBA::is_nil(container_proxy))
2164 INFOS("[StarPaCOPPContainer] PaCO::InterfaceManager::_narrow returns NIL !");
2165 return container_proxy;
2170 //=============================================================================
2171 /*! This method launches the parallel container.
2172 * It will may be placed on the resources manager.
2174 * \param command to launch
2175 * \param container's parameters
2176 * \param name of the container
2178 * \return CORBA container reference
2180 //=============================================================================
2182 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& command,
2183 const Engines::ContainerParameters& params,
2184 const std::string& name,
2185 SALOME_ContainerManager::actual_launch_machine_t & vect_machine)
2187 INFOS("[LaunchPaCONodeContainer] Launch command");
2188 int status = SystemThreadSafe(command.c_str());
2190 INFOS("[LaunchPaCONodeContainer] failed : system command status -1");
2193 else if (status == 217) {
2194 INFOS("[LaunchPaCONodeContainer] failed : system command status 217");
2198 INFOS("[LaunchPaCONodeContainer] Waiting for the nodes of the parallel container");
2199 // We are waiting all the nodes
2200 for (int i = 0; i < params.nb_proc; i++)
2202 CORBA::Object_var obj = CORBA::Object::_nil();
2203 std::string theMachine(vect_machine[i]);
2205 std::ostringstream tmp;
2207 std::string proc_number = tmp.str();
2208 std::string container_node_name = name + proc_number;
2209 std::string containerNameInNS = _NS->BuildContainerNameForNS((char*) container_node_name.c_str(), theMachine.c_str());
2210 INFOS("[LaunchPaCONodeContainer] Waiting for Parallel Container node " << containerNameInNS << " on " << theMachine);
2211 int count(GetTimeOutToLoaunchServer());
2212 while (CORBA::is_nil(obj) && count) {
2215 obj = _NS->Resolve(containerNameInNS.c_str());
2217 if (CORBA::is_nil(obj))
2219 INFOS("[LaunchPaCONodeContainer] Launch of node failed (or not found) !");
2228 Engines::Container_ptr
2229 SALOME_ContainerManager::StartPaCOPPContainer(const Engines::ContainerParameters& /*params*/,
2230 std::string /*resource_selected*/)
2232 Engines::Container_ptr ret = Engines::Container::_nil();
2233 INFOS("[StarPaCOPPContainer] is disabled !");
2234 INFOS("[StarPaCOPPContainer] recompile SALOME Kernel to enable PaCO++ parallel extension");
2239 SALOME_ContainerManager::BuildCommandToLaunchPaCOProxyContainer(const Engines::ContainerParameters& /*params*/,
2240 std::string /*machine_file_name*/,
2241 std::string & /*proxy_hostname*/)
2247 SALOME_ContainerManager::BuildCommandToLaunchPaCONodeContainer(const Engines::ContainerParameters& /*params*/,
2248 const std::string & /*machine_file_name*/,
2249 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/,
2250 const std::string & /*proxy_hostname*/)
2255 SALOME_ContainerManager::LogConfiguration(const std::string & /*log_type*/,
2256 const std::string & /*exe_type*/,
2257 const std::string & /*container_name*/,
2258 const std::string & /*hostname*/,
2259 std::string & /*begin*/,
2260 std::string & /*end*/)
2265 SALOME_ContainerManager::LaunchPaCOProxyContainer(const std::string& /*command*/,
2266 const Engines::ContainerParameters& /*params*/,
2267 const std::string& /*hostname*/)
2269 CORBA::Object_ptr ret = CORBA::Object::_nil();
2274 SALOME_ContainerManager::LaunchPaCONodeContainer(const std::string& /*command*/,
2275 const Engines::ContainerParameters& /*params*/,
2276 const std::string& /*name*/,
2277 SALOME_ContainerManager::actual_launch_machine_t & /*vect_machine*/)