]> SALOME platform Git repositories - modules/kernel.git/blob - src/Container/SALOME_ContainerManager.cxx
Salome HOME
CCAR:
[modules/kernel.git] / src / Container / SALOME_ContainerManager.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
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.
10 //
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.
15 //
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
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 #include "SALOME_ContainerManager.hxx"
23 #include "SALOME_NamingService.hxx"
24 #include "SALOME_ModuleCatalog.hh"
25 #include "Basics_Utils.hxx"
26 #include "Basics_DirUtils.hxx"
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #ifndef WIN32
30 #include <unistd.h>
31 #endif
32 #include <vector>
33 #include "Utils_CorbaException.hxx"
34 #include "Batch_Date.hxx"
35
36 #ifdef WITH_PACO_PARALLEL
37 #include "PaCO++.h"
38 #endif
39
40 #define TIME_OUT_TO_LAUNCH_CONT 61
41
42 using namespace std;
43
44 vector<Engines::Container_ptr> SALOME_ContainerManager::_batchLaunchedContainers;
45
46 vector<Engines::Container_ptr>::iterator SALOME_ContainerManager::_batchLaunchedContainersIter;
47
48 const char *SALOME_ContainerManager::_ContainerManagerNameInNS = 
49   "/ContainerManager";
50
51 //=============================================================================
52 /*! 
53  *  Constructor
54  *  \param orb
55  *  Define a CORBA single thread policy for the server, which avoid to deal
56  *  with non thread-safe usage like Change_Directory in SALOME naming service
57  */
58 //=============================================================================
59
60 SALOME_ContainerManager::SALOME_ContainerManager(CORBA::ORB_ptr orb, PortableServer::POA_var poa, SALOME_ResourcesManager *rm, SALOME_NamingService *ns)
61 {
62   MESSAGE("constructor");
63   _NS = ns;
64   _ResManager = rm;
65
66   PortableServer::POAManager_var pman = poa->the_POAManager();
67   _orb = CORBA::ORB::_duplicate(orb) ;
68   CORBA::PolicyList policies;
69   policies.length(1);
70   PortableServer::ThreadPolicy_var threadPol = 
71     poa->create_thread_policy(PortableServer::SINGLE_THREAD_MODEL);
72   policies[0] = PortableServer::ThreadPolicy::_duplicate(threadPol);
73
74   _poa = poa->create_POA("SThreadPOA",pman,policies);
75   threadPol->destroy();
76   PortableServer::ObjectId_var id = _poa->activate_object(this);
77   CORBA::Object_var obj = _poa->id_to_reference(id);
78   Engines::ContainerManager_var refContMan =
79     Engines::ContainerManager::_narrow(obj);
80
81   _NS->Register(refContMan,_ContainerManagerNameInNS);
82   _MpiStarted = false;
83   _isAppliSalomeDefined = (getenv("APPLI") != 0);
84   MESSAGE("constructor end");
85 }
86
87 //=============================================================================
88 /*! 
89  * destructor
90  */
91 //=============================================================================
92
93 SALOME_ContainerManager::~SALOME_ContainerManager()
94 {
95   MESSAGE("destructor");
96 }
97
98 //=============================================================================
99 /*! CORBA method:
100  *  shutdown all the containers, then the ContainerManager servant
101  */
102 //=============================================================================
103
104 void SALOME_ContainerManager::Shutdown()
105 {
106   MESSAGE("Shutdown");
107   ShutdownContainers();
108   _NS->Destroy_Name(_ContainerManagerNameInNS);
109   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
110   _poa->deactivate_object(oid);
111 }
112
113 //=============================================================================
114 /*! CORBA Method:
115  *  Loop on all the containers listed in naming service, ask shutdown on each
116  */
117 //=============================================================================
118
119 void SALOME_ContainerManager::ShutdownContainers()
120 {
121   MESSAGE("ShutdownContainers");
122   bool isOK;
123   isOK = _NS->Change_Directory("/Containers");
124   if( isOK ){
125     vector<string> vec = _NS->list_directory_recurs();
126     list<string> lstCont;
127     for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++)
128       {
129         SCRUTE((*iter));
130         CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
131         try
132           {
133             Engines::Container_var cont=Engines::Container::_narrow(obj);
134             if(!CORBA::is_nil(cont))
135               lstCont.push_back((*iter));
136           }
137         catch(const CORBA::Exception& e)
138           {
139             // ignore this entry and continue
140           }
141       }
142     MESSAGE("Container list: ");
143     for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
144       SCRUTE((*iter));
145     }
146     for(list<string>::iterator iter=lstCont.begin();iter!=lstCont.end();iter++){
147       SCRUTE((*iter));
148       CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
149       Engines::Container_var cont=Engines::Container::_narrow(obj);
150       if(!CORBA::is_nil(cont))
151         {
152           MESSAGE("ShutdownContainers: " << (*iter));
153           try
154             {
155               cont->Shutdown();
156             }
157           catch(CORBA::SystemException& e)
158             {
159               INFOS("CORBA::SystemException ignored : " << e);
160             }
161           catch(CORBA::Exception&)
162             {
163               INFOS("CORBA::Exception ignored.");
164             }
165           catch(...)
166             {
167               INFOS("Unknown exception ignored.");
168             }
169         }
170       else 
171         MESSAGE("ShutdownContainers: no container ref for " << (*iter));
172     }
173   }
174 }
175
176 //=============================================================================
177 //!  Find a suitable Container in a list of machines, or start one
178 /*! CORBA Method:
179  *  \param params            Machine Parameters required for the container
180  *  \param possibleComputers list of machines usable for find or start
181  */
182 //=============================================================================
183
184 Engines::Container_ptr
185 SALOME_ContainerManager::
186 FindOrStartContainer(const Engines::MachineParameters& params,
187                      const Engines::MachineList& possibleComputers)
188 {
189   Engines::Container_ptr ret = FindContainer(params,possibleComputers);
190   if(!CORBA::is_nil(ret))
191     return ret;
192   MESSAGE("Container doesn't exist try to launch it ...");
193
194   return StartContainer(params,possibleComputers,Engines::P_FIRST);
195
196 }
197
198 //=============================================================================
199 //! Start a suitable Container in a list of machines with constraints and a policy
200 /*! C++ Method:
201  * Constraints are given by a machine parameters struct
202  *  \param params            Machine Parameters required for the container
203  *  \param possibleComputers list of machines usable for start
204  *  \param policy        policy to use (first,cycl or best)
205  *  \param container_exe specific container executable (default=SALOME_Container)
206  */
207 //=============================================================================
208
209 Engines::Container_ptr
210 SALOME_ContainerManager::
211 StartContainer(const Engines::MachineParameters& params,
212                const Engines::MachineList& possibleComputers,
213                Engines::ResPolicy policy,const std::string& container_exe)
214 {
215 #ifdef WITH_PACO_PARALLEL
216   std::string parallelLib(params.parallelLib);
217   if (parallelLib != "")
218     return FindOrStartParallelContainer(params, possibleComputers);
219 #endif
220   string containerNameInNS;
221   Engines::Container_ptr ret = Engines::Container::_nil();
222
223   MESSAGE("SALOME_ContainerManager::StartContainer " << possibleComputers.length());
224
225   vector<string> lm;
226 // if mode is "get" keep only machines with existing containers 
227   if(std::string(params.mode.in())=="get")
228     {
229       for(unsigned int i=0;i<possibleComputers.length();i++)
230         {
231           Engines::Container_ptr cont = FindContainer(params,possibleComputers[i]);
232           try
233             {
234               if(!cont->_non_existent())
235                 lm.push_back(string(possibleComputers[i]));
236             }
237           catch(CORBA::Exception&)
238             {
239               // CORBA::Exception ignored.
240             }
241         }
242     }
243   else
244     {
245       for(unsigned int i=0;i<possibleComputers.length();i++)
246         lm.push_back(string(possibleComputers[i]));
247     }
248
249   string theMachine;
250   try
251     {
252       theMachine=_ResManager->GetImpl()->Find(params.policy.in(),lm);
253     }
254   catch( const SALOME_Exception &ex )
255     {
256       MESSAGE(ex.what());
257       return Engines::Container::_nil();
258     }
259
260   //If the machine name is localhost use the real name
261   if(theMachine == "localhost")
262     theMachine=Kernel_Utils::GetHostname();
263
264   //check if an entry exists in Naming service
265   //if params.mode == "start" or "" shutdown the existing container before launching a new one with that name
266   //if params.mode == "getorstart" or "get" use the existing container
267   containerNameInNS = _NS->BuildContainerNameForNS(params,theMachine.c_str());
268
269   SCRUTE(containerNameInNS);
270   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
271   if ( !CORBA::is_nil(obj) )
272     {
273       try
274         {
275           Engines::Container_var cont=Engines::Container::_narrow(obj);
276           if(!cont->_non_existent())
277             {
278               if(std::string(params.mode.in())=="getorstart"||std::string(params.mode.in())=="get")
279                 return cont._retn(); /* the container exists and params.mode is getorstart or get use it*/
280               else
281                 cont->Shutdown(); // shutdown the registered container if it exists
282             }
283         }
284       catch(CORBA::Exception&)
285         {
286           INFOS("CORBA::Exception ignored.");
287         }
288     }
289
290   //try to launch a new container
291   MESSAGE("try to launch it on " << theMachine);
292
293   string command;
294   if(theMachine==""){
295     MESSAGE("SALOME_ContainerManager::StartContainer : no possible computer");
296     return Engines::Container::_nil();
297   }
298   else if(theMachine==Kernel_Utils::GetHostname())
299     command = BuildCommandToLaunchLocalContainer(params,container_exe);
300   else
301     command = BuildCommandToLaunchRemoteContainer(theMachine,params,container_exe);
302
303   //redirect stdout and stderr in a file
304   string logFilename="/tmp/"+_NS->ContainerName(params)+"_"+ theMachine +"_"+getenv( "USER" )+".log" ;
305   command += " > " + logFilename + " 2>&1 &";
306
307   // launch container with a system call
308   int status=system(command.c_str());
309
310   if (status == -1){
311     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status -1)");
312     RmTmpFile(_TmpFileName); // command file can be removed here
313     return Engines::Container::_nil();
314   }
315   else if (status == 217){
316     MESSAGE("SALOME_ContainerManager::StartContainer rsh failed (system command status 217)");
317     RmTmpFile(_TmpFileName); // command file can be removed here
318     return Engines::Container::_nil();
319   }
320   else{
321     int count=TIME_OUT_TO_LAUNCH_CONT;
322     MESSAGE("count = "<<count);
323     while ( CORBA::is_nil(ret) && count ){
324 #ifndef WIN32
325       sleep( 1 ) ;
326 #else
327       Sleep(1000);
328 #endif
329       count-- ;
330       if ( count != 10 )
331         MESSAGE( count << ". Waiting for container on " << theMachine);
332
333       CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
334       ret=Engines::Container::_narrow(obj);
335     }
336     
337     if ( CORBA::is_nil(ret) )
338       {
339         MESSAGE("SALOME_ContainerManager::StartContainer rsh failed");
340       }
341     else
342       {
343         logFilename=":"+logFilename;
344         logFilename="@"+Kernel_Utils::GetHostname()+logFilename;
345         logFilename=getenv( "USER" )+logFilename;
346         ret->logfilename(logFilename.c_str());
347       }
348
349     RmTmpFile(_TmpFileName); // command file can be removed here
350     return ret;
351   }
352 }
353
354 //=============================================================================
355 //! Start a suitable Container for a list of components with constraints and a policy
356 /*! CORBA Method:
357  *  \param params            Machine Parameters required for the container
358  *  \param policy        policy to use (first,cycl or best)
359  *  \param componentList list of component to be loaded on this container
360  */
361 //=============================================================================
362
363 Engines::Container_ptr
364 SALOME_ContainerManager::
365 StartContainer(const Engines::MachineParameters& params,
366                Engines::ResPolicy policy,
367                const Engines::CompoList& componentList)
368 {
369   Engines::MachineList_var possibleComputers = _ResManager->GetFittingResources(params,componentList);
370
371   // Look into ModulCatalog if a specific container must be launched
372   CORBA::String_var container_exe;
373   int found=0;
374   try
375     {
376       CORBA::Object_var obj = _NS->Resolve("/Kernel/ModulCatalog");
377       SALOME_ModuleCatalog::ModuleCatalog_var Catalog = SALOME_ModuleCatalog::ModuleCatalog::_narrow(obj) ;
378       if (CORBA::is_nil (Catalog))
379         return Engines::Container::_nil();
380       // Loop through component list
381       for(unsigned int i=0;i<componentList.length();i++)
382         {
383           const char* compoi = componentList[i];
384           SALOME_ModuleCatalog::Acomponent_var compoInfo = Catalog->GetComponent(compoi);
385           if (CORBA::is_nil (compoInfo))
386             {
387               continue;
388             }
389           SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
390           container_exe=compoInfo->implementation_name();
391           if(impl==SALOME_ModuleCatalog::CEXE)
392             {
393               if(found)
394                 {
395                   INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
396                   return Engines::Container::_nil();
397                 }
398               found=1;
399             }
400         }
401     }
402   catch (ServiceUnreachable&)
403     {
404       INFOS("Caught exception: Naming Service Unreachable");
405       return Engines::Container::_nil();
406     }
407   catch (...)
408     {
409       INFOS("Caught unknown exception.");
410       return Engines::Container::_nil();
411     }
412
413   if(found)
414     return StartContainer(params,possibleComputers,policy,container_exe.in());
415   else
416     return StartContainer(params,possibleComputers,policy);
417 }
418
419 #ifdef WITH_PACO_PARALLEL
420 //=============================================================================
421 /*! CORBA Method:
422  *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
423  *  \param params            Machine Parameters required for the container
424  *  \param possibleComputers list of machines usable for find or start
425  *
426  *  \return CORBA container reference.
427  */
428 //=============================================================================
429 Engines::Container_ptr
430 SALOME_ContainerManager::
431 FindOrStartParallelContainer(const Engines::MachineParameters& params_const,
432                              const Engines::MachineList& possibleComputers)
433 {
434   CORBA::Object_var obj;
435   PaCO::InterfaceManager_var proxy;
436   Engines::Container_ptr ret = Engines::Container::_nil();
437   Engines::MachineParameters params(params_const);
438
439   // Step 1 : Try to find a suitable container
440   // Currently not as good as could be since
441   // we have to verified the number of nodes of the container
442   // if a user tell that.
443   ret = FindContainer(params, possibleComputers);
444
445   if(CORBA::is_nil(ret)) {
446     // Step 2 : Starting a new parallel container
447     INFOS("[FindOrStartParallelContainer] Starting a parallel container");
448
449     // Step 2.1 : Choose a computer
450     string theMachine = _ResManager->FindFirst(possibleComputers);
451     if(theMachine == "") {
452       INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
453       INFOS("[FindOrStartParallelContainer] No possible computer found");
454       INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
455     }
456     else {
457       INFOS("[FindOrStartParallelContainer] on machine : " << theMachine);
458       string command;
459       if(theMachine == Kernel_Utils::GetHostname()) {
460         // Step 3 : starting parallel container proxy
461         params.hostname = CORBA::string_dup(theMachine.c_str());
462         Engines::MachineParameters params_proxy(params);
463         try {
464           command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerProxy", params_proxy, "xterm");
465         }
466         catch(const SALOME_Exception & ex){
467           MESSAGE(ex.what());
468           return Engines::Container::_nil();
469         }
470         // LaunchParallelContainer uses this value to know if it launches the proxy or the nodes
471         params_proxy.nb_component_nodes = 0;
472         obj = LaunchParallelContainer(command, params_proxy, _NS->ContainerName(params));
473         ret = Engines::Container::_narrow(obj);
474         proxy = PaCO::InterfaceManager::_narrow(obj);
475
476         // Step 4 : starting parallel container nodes
477         command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerNode", params, "xterm");
478         string name = _NS->ContainerName(params) + "Node";
479         LaunchParallelContainer(command, params, name);
480         // Step 5 : connecting nodes and the proxy to actually create a parallel container
481         try {
482           for (int i = 0; i < params.nb_component_nodes; i++) {
483
484             char buffer [5];
485 #ifndef WIN32
486             snprintf(buffer,5,"%d",i);
487 #else
488             _snprintf(buffer,5,"%d",i);
489 #endif
490             string name_cont = name + string(buffer);
491
492             string theNodeMachine(CORBA::string_dup(params.hostname));
493             string containerNameInNS = _NS->BuildContainerNameForNS(name_cont.c_str(),theNodeMachine.c_str());
494             int count = TIME_OUT_TO_LAUNCH_CONT;
495             obj = _NS->Resolve(containerNameInNS.c_str());
496             while (CORBA::is_nil(obj) && count) {
497               INFOS("[FindOrStartParallelContainer] CONNECTION FAILED !!!!!!!!!!!!!!!!!!!!!!!!");
498 #ifndef WIN32
499               sleep(1) ;
500 #else
501               Sleep(1000);
502 #endif
503               count-- ;
504               obj = _NS->Resolve(containerNameInNS.c_str());
505             }
506
507             PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
508             MESSAGE("[FindOrStartParallelContainer] Deploying node : " << name);
509             node->deploy();
510           }
511           proxy->start();
512         }
513         catch(CORBA::SystemException& e)
514           {
515             INFOS("Caught CORBA::SystemException. : " << e);
516           }
517         catch(PortableServer::POA::ServantAlreadyActive&)
518           {
519             INFOS("Caught CORBA::ServantAlreadyActiveException");
520           }
521         catch(CORBA::Exception&)
522           {
523             INFOS("Caught CORBA::Exception.");
524           }
525         catch(std::exception& exc)
526           {
527             INFOS("Caught std::exception - "<<exc.what()); 
528           }
529         catch(...)
530           {
531             INFOS("Caught unknown exception.");
532           }
533         INFOS("[FindOrStartParallelContainer] node " << name << " deployed");
534       }
535       else {
536         INFOS("[FindOrStartParallelContainer] Currently parallel containers are launched only on the local host");
537       }
538     }
539   }
540   return ret;
541 }
542 #else
543 //=============================================================================
544 /*! CORBA Method:
545  *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
546  *  \param params            Machine Parameters required for the container
547  *  \param possibleComputers list of machines usable for find or start
548  *
549  *  \return CORBA container reference.
550  */
551 //=============================================================================
552 Engines::Container_ptr
553 SALOME_ContainerManager::
554 FindOrStartParallelContainer(const Engines::MachineParameters& params,
555                              const Engines::MachineList& possibleComputers)
556 {
557   Engines::Container_ptr ret = Engines::Container::_nil();
558   INFOS("[FindOrStartParallelContainer] is disabled !");
559   INFOS("[FindOrStartParallelContainer] recompile SALOME Kernel to enable parallel extension");
560   return ret;
561 }
562 #endif
563
564 //=============================================================================
565 //! Give a suitable Container for a list of components with constraints and a policy
566 /*! CORBA Method:
567  *  \param params            Machine Parameters required for the container
568  *  \param policy        policy to use (first,cycl or best)
569  *  \param componentList list of component to be loaded on this container
570  */
571 //=============================================================================
572
573 Engines::Container_ptr
574 SALOME_ContainerManager::
575 GiveContainer(const Engines::MachineParameters& params,
576               Engines::ResPolicy policy,
577               const Engines::CompoList& componentList)
578 {
579   char *valenv=getenv("SALOME_BATCH");
580   if(valenv)
581     if (strcmp(valenv,"1")==0)
582       {
583         if(_batchLaunchedContainers.empty())
584           fillBatchLaunchedContainers();
585
586         if (_batchLaunchedContainersIter == _batchLaunchedContainers.end())
587           _batchLaunchedContainersIter = _batchLaunchedContainers.begin();
588
589         Engines::Container_ptr rtn = Engines::Container::_duplicate(*_batchLaunchedContainersIter);
590         _batchLaunchedContainersIter++;
591         return rtn;
592       }
593   return StartContainer(params,policy,componentList);
594 }
595
596 //=============================================================================
597 /*! 
598  * 
599  */
600 //=============================================================================
601
602 Engines::Container_ptr
603 SALOME_ContainerManager::
604 FindContainer(const Engines::MachineParameters& params,
605               const char *theMachine)
606 {
607   string containerNameInNS(_NS->BuildContainerNameForNS(params,theMachine));
608   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
609   try
610     {
611       if(obj->_non_existent())
612         return Engines::Container::_nil();
613       else
614         return Engines::Container::_narrow(obj);
615     }
616   catch(const CORBA::Exception& e)
617     {
618       return Engines::Container::_nil();
619     }
620 }
621
622 //=============================================================================
623 /*! 
624  * 
625  */
626 //=============================================================================
627
628 Engines::Container_ptr
629 SALOME_ContainerManager::
630 FindContainer(const Engines::MachineParameters& params,
631               const Engines::MachineList& possibleComputers)
632 {
633   MESSAGE("FindContainer "<<possibleComputers.length());
634   for(unsigned int i=0;i<possibleComputers.length();i++)
635     {
636       MESSAGE("FindContainer possible " << possibleComputers[i]);
637       Engines::Container_ptr cont = FindContainer(params,possibleComputers[i]);
638       if( !CORBA::is_nil(cont) )
639         return cont;
640     }
641   MESSAGE("FindContainer: not found");
642   return Engines::Container::_nil();
643 }
644
645 //=============================================================================
646 /*! This method launches the parallel container.
647  *  It will may be placed on the ressources manager.
648  *
649  * \param command to launch
650  * \param container's parameters
651  * \param name of the container
652  *
653  * \return CORBA container reference
654  */
655 //=============================================================================
656 CORBA::Object_ptr 
657 SALOME_ContainerManager::LaunchParallelContainer(const std::string& command, 
658                                                  const Engines::MachineParameters& params,
659                                                  const std::string& name)
660 {
661   CORBA::Object_ptr obj = CORBA::Object::_nil();
662   string containerNameInNS;
663   MESSAGE("[LaunchParallelContainer] : command to launch...");
664   MESSAGE(command);
665   if (params.nb_component_nodes == 0) {
666     INFOS("[LaunchParallelContainer] launching the proxy of the parallel container");
667     int status = system(command.c_str());
668     if (status == -1) {
669       INFOS("[LaunchParallelContainer] failed : system command status -1");
670     }
671     else if (status == 217) {
672       INFOS("[LaunchParallelContainer] failed : system command status 217");
673     }
674
675     int count = TIME_OUT_TO_LAUNCH_CONT;
676     string theMachine(CORBA::string_dup(params.hostname));
677     containerNameInNS = _NS->BuildContainerNameForNS((char*) name.c_str(),theMachine.c_str());
678
679     INFOS("[LaunchParallelContainer]  Waiting for Parallel Container proxy on " << theMachine);
680     while (CORBA::is_nil(obj) && count) {
681 #ifndef WIN32
682       sleep(1) ;
683 #else
684       Sleep(1000);
685 #endif
686       count-- ;
687       obj = _NS->Resolve(containerNameInNS.c_str());
688     }
689   }
690   else {
691     INFOS("[LaunchParallelContainer] launching the nodes of the parallel container");
692     int status = system(command.c_str());
693     if (status == -1) {
694       INFOS("[LaunchParallelContainer] failed : system command status -1");
695     }
696     else if (status == 217) {
697       INFOS("[LaunchParallelContainer] failed : system command status 217");
698     }
699     // We are waiting all the nodes
700     for (int i = 0; i < params.nb_component_nodes; i++) {
701       obj = CORBA::Object::_nil();
702       int count = TIME_OUT_TO_LAUNCH_CONT;
703
704       // Name of the node
705       char buffer [5];
706 #ifndef WIN32
707       snprintf(buffer,5,"%d",i);
708 #else
709       _snprintf(buffer,5,"%d",i);
710 #endif
711
712       string name_cont = name + string(buffer);
713
714       // I don't like this...
715       string theMachine(CORBA::string_dup(params.hostname));
716       containerNameInNS = _NS->BuildContainerNameForNS((char*) name_cont.c_str(),theMachine.c_str());
717       cerr << "[LaunchContainer]  Waiting for Parllel Container node " << containerNameInNS << " on " << theMachine << endl;
718       while (CORBA::is_nil(obj) && count) {
719 #ifndef WIN32
720         sleep(1) ;
721 #else
722         Sleep(1000);
723 #endif
724         count-- ;
725         obj = _NS->Resolve(containerNameInNS.c_str());
726       }
727     }
728   }
729
730   if ( CORBA::is_nil(obj) ) {
731     INFOS("[LaunchParallelContainer] failed");
732   }
733   return obj;
734 }
735
736 void SALOME_ContainerManager::fillBatchLaunchedContainers()
737 {
738   _batchLaunchedContainers.clear();
739   _NS->Change_Directory("/Containers");
740   vector<string> vec = _NS->list_directory_recurs();
741   for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++){
742     CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
743     Engines::Container_ptr cont=Engines::Container::_narrow(obj);
744     if(!CORBA::is_nil(cont)){
745       _batchLaunchedContainers.push_back(cont);
746     }
747   }
748   _batchLaunchedContainersIter=_batchLaunchedContainers.begin();
749 }
750
751 //=============================================================================
752 /*!
753  *  This is no longer valid (C++ container are also python containers)
754  */ 
755 //=============================================================================
756
757 bool isPythonContainer(const char* ContainerName)
758 {
759   bool ret = false;
760   int len = strlen(ContainerName);
761
762   if (len >= 2)
763     if (strcmp(ContainerName + len - 2, "Py") == 0)
764       ret = true;
765
766   return ret;
767 }
768
769 //=============================================================================
770 /*!
771  *  Builds the script to be launched
772  *
773  *  If SALOME Application not defined ($APPLI),
774  *  see BuildTempFileToLaunchRemoteContainer()
775  *
776  *  Else rely on distant configuration. Command is under the form (example):
777  *  ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
778  *                   SALOME_Container containerName &"
779
780  *  - where user is ommited if not specified in CatalogResources,
781  *  - where distant path is always relative to user@machine $HOME, and
782  *    equal to $APPLI if not specified in CatalogResources,
783  *  - where hostNS is the hostname of CORBA naming server (set by scripts to
784  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
785  *  - where portNS is the port used by CORBA naming server (set by scripts to
786  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
787  *  - where workingdir is the requested working directory for the container.
788  *    If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
789  */ 
790 //=============================================================================
791
792 string
793 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer
794 (const string& machine,
795  const Engines::MachineParameters& params, const std::string& container_exe)
796 {
797   string command;
798   int nbproc;
799           
800   if ( ! _isAppliSalomeDefined )
801     command = BuildTempFileToLaunchRemoteContainer(machine, params);
802
803   else
804     {
805       const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
806
807       if (params.isMPI)
808         {
809           if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
810             nbproc = 1;
811           else if ( params.nb_node == 0 )
812             nbproc = params.nb_proc_per_node;
813           else if ( params.nb_proc_per_node == 0 )
814             nbproc = params.nb_node;
815           else
816             nbproc = params.nb_node * params.nb_proc_per_node;
817         }
818
819       // "ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
820         //  SALOME_Container containerName &"
821
822       if (resInfo.Protocol == rsh)
823         command = "rsh ";
824       else if (resInfo.Protocol == ssh)
825         command = "ssh ";
826       else
827         throw SALOME_Exception("Unknown protocol");
828
829       if (resInfo.UserName != "")
830         {
831           command += resInfo.UserName;
832           command += "@";
833         }
834
835       command += machine;
836       command += " ";
837
838       if (resInfo.AppliPath != "")
839         command += resInfo.AppliPath; // path relative to user@machine $HOME
840       else
841         {
842           ASSERT(getenv("APPLI"));
843           command += getenv("APPLI"); // path relative to user@machine $HOME
844         }
845
846       command += "/runRemote.sh ";
847
848       ASSERT(getenv("NSHOST")); 
849       command += getenv("NSHOST"); // hostname of CORBA name server
850
851       command += " ";
852       ASSERT(getenv("NSPORT"));
853       command += getenv("NSPORT"); // port of CORBA name server
854
855       std::string wdir=params.workingdir.in();
856       if(wdir != "")
857         {
858           command += " WORKINGDIR ";
859           command += " '";
860           if(wdir == "$TEMPDIR")
861             wdir="\\$TEMPDIR";
862           command += wdir; // requested working directory
863           command += "'"; 
864         }
865
866       if(params.isMPI)
867         {
868           command += " mpirun -np ";
869           std::ostringstream o;
870           o << nbproc << " ";
871           command += o.str();
872 #ifdef WITHLAM
873           command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
874 #elif defined(WITHOPENMPI)
875           if( getenv("OMPI_URI_FILE") == NULL )
876             command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
877           else{
878             command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
879             command += getenv("OMPI_URI_FILE");
880           }
881 #endif  
882           command += " SALOME_MPIContainer ";
883         }
884       else
885         command += " " +container_exe+ " ";
886
887       command += _NS->ContainerName(params);
888       command += " -";
889       AddOmninamesParams(command);
890
891       MESSAGE("command =" << command);
892     }
893
894   return command;
895 }
896
897 //=============================================================================
898 /*!
899  *  builds the command to be launched.
900  */ 
901 //=============================================================================
902
903 string
904 SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
905 (const Engines::MachineParameters& params, const std::string& container_exe)
906 {
907   _TmpFileName = BuildTemporaryFileName();
908   string command;
909   int nbproc = 0;
910
911   ofstream command_file( _TmpFileName.c_str() );
912
913   if (params.isMPI)
914     {
915       //command = "mpirun -np ";
916       command_file << "mpirun -np ";
917
918       if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
919         nbproc = 1;
920       else if ( params.nb_node == 0 )
921         nbproc = params.nb_proc_per_node;
922       else if ( params.nb_proc_per_node == 0 )
923         nbproc = params.nb_node;
924       else
925         nbproc = params.nb_node * params.nb_proc_per_node;
926
927       //std::ostringstream o;
928
929       //o << nbproc << " ";
930       command_file << nbproc << " ";
931
932       //command += o.str();
933 #ifdef WITHLAM
934       //command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
935       command_file << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
936 #elif defined(WITHOPENMPI)
937       //command += "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace ";
938       if( getenv("OMPI_URI_FILE") == NULL )
939         command_file << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
940       else
941         {
942           command_file << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
943           command_file << getenv("OMPI_URI_FILE");
944         }
945 #endif
946
947       if (isPythonContainer(params.container_name))
948         //command += "pyMPI SALOME_ContainerPy.py ";
949         command_file << " pyMPI SALOME_ContainerPy.py ";
950       else
951         //command += "SALOME_MPIContainer ";
952         command_file << " SALOME_MPIContainer ";
953     }
954
955   else
956     {
957       //command="";
958       std::string wdir=params.workingdir.in();
959       if(wdir != "")
960         {
961           // a working directory is requested
962           if(wdir == "$TEMPDIR")
963             {
964               // a new temporary directory is requested
965               string dir = Kernel_Utils::GetTmpDir();
966 #ifdef WIN32
967               //command += "cd /d "+ dir +";";
968               command_file << "cd /d " << dir << endl;
969 #else
970               //command = "cd "+ dir +";";
971               command_file << "cd " << dir << ";";
972 #endif
973
974             }
975           else
976             {
977               // a permanent directory is requested use it or create it
978 #ifdef WIN32
979               //command="mkdir " + wdir;
980               command_file << "mkdir " + wdir << endl;
981               command_file << "cd /D " + wdir << endl;
982 #else
983               //command="mkdir -p " + wdir + " && cd " + wdir + ";";
984               command_file << "mkdir -p " << wdir << " && cd " << wdir + ";";
985 #endif
986             }
987         }
988       if (isPythonContainer(params.container_name))
989         //command += "SALOME_ContainerPy.py ";
990         command_file << "SALOME_ContainerPy.py ";
991       else
992         //command += container_exe + " ";
993         command_file << container_exe + " ";
994
995     }
996
997   command_file << _NS->ContainerName(params);
998   command_file << " -";
999   AddOmninamesParams(command_file);
1000   command_file.close();
1001
1002 #ifndef WIN32
1003   chmod(_TmpFileName.c_str(), 0x1ED);
1004 #endif
1005   command = _TmpFileName;
1006
1007   MESSAGE("Command is file ... " << command);
1008   return command;
1009 }
1010
1011
1012 //=============================================================================
1013 /*!
1014  *  removes the generated temporary file in case of a remote launch.
1015  */ 
1016 //=============================================================================
1017
1018 void SALOME_ContainerManager::RmTmpFile(std::string& tmpFileName)
1019 {
1020   int lenght = tmpFileName.size();
1021   if ( lenght  > 0)
1022     {
1023 #ifdef WIN32
1024       string command = "del /F ";
1025 #else
1026       string command = "rm ";      
1027 #endif
1028       if ( lenght > 4 )
1029         command += tmpFileName.substr(0, lenght - 3 );
1030       else
1031         command += tmpFileName;
1032       command += '*';
1033       system(command.c_str());
1034       //if dir is empty - remove it
1035       string tmp_dir = Kernel_Utils::GetDirByPath( tmpFileName );
1036       if ( Kernel_Utils::IsEmptyDir( tmp_dir ) )
1037         {
1038 #ifdef WIN32
1039           command = "del /F " + tmp_dir;
1040 #else
1041           command = "rmdir " + tmp_dir;
1042 #endif
1043           system(command.c_str());
1044         }
1045     }
1046 }
1047
1048 //=============================================================================
1049 /*!
1050  *   add to command all options relative to naming service.
1051  */ 
1052 //=============================================================================
1053
1054 void SALOME_ContainerManager::AddOmninamesParams(string& command) const
1055 {
1056   CORBA::String_var iorstr = _NS->getIORaddr();
1057   command += "ORBInitRef NameService=";
1058   command += iorstr;
1059 }
1060
1061
1062 //=============================================================================
1063 /*!
1064  *  add to command all options relative to naming service.
1065  */ 
1066 //=============================================================================
1067
1068 void SALOME_ContainerManager::AddOmninamesParams(ofstream& fileStream) const
1069 {
1070   CORBA::String_var iorstr = _NS->getIORaddr();
1071   fileStream << "ORBInitRef NameService=";
1072   fileStream << iorstr;
1073 }
1074
1075 //=============================================================================
1076 /*!
1077  *  generate a file name in /tmp directory
1078  */ 
1079 //=============================================================================
1080
1081 string SALOME_ContainerManager::BuildTemporaryFileName() const
1082 {
1083   //build more complex file name to support multiple salome session
1084   string aFileName = Kernel_Utils::GetTmpFileName();
1085 #ifndef WIN32
1086   aFileName += ".sh";
1087 #else
1088   aFileName += ".bat";
1089 #endif
1090   return aFileName;
1091 }
1092
1093
1094 //=============================================================================
1095 /*!
1096  *  Builds in a temporary file the script to be launched.
1097  *  
1098  *  Used if SALOME Application ($APPLI) is not defined.
1099  *  The command is build with data from CatalogResources, in which every path
1100  *  used on remote computer must be defined.
1101  */ 
1102 //=============================================================================
1103
1104 string
1105 SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
1106 (const string& machine,
1107  const Engines::MachineParameters& params) throw(SALOME_Exception)
1108 {
1109   int status;
1110
1111   _TmpFileName = BuildTemporaryFileName();
1112   ofstream tempOutputFile;
1113   tempOutputFile.open(_TmpFileName.c_str(), ofstream::out );
1114   const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
1115   tempOutputFile << "#! /bin/sh" << endl;
1116
1117   // --- set env vars
1118
1119   tempOutputFile << "export SALOME_trace=local" << endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1120   //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1121
1122   // ! env vars
1123
1124   if (params.isMPI)
1125     {
1126       tempOutputFile << "mpirun -np ";
1127       int nbproc;
1128
1129       if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
1130         nbproc = 1;
1131       else if ( params.nb_node == 0 )
1132         nbproc = params.nb_proc_per_node;
1133       else if ( params.nb_proc_per_node == 0 )
1134         nbproc = params.nb_node;
1135       else
1136         nbproc = params.nb_node * params.nb_proc_per_node;
1137
1138       std::ostringstream o;
1139
1140       tempOutputFile << nbproc << " ";
1141 #ifdef WITHLAM
1142       tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1143 #elif defined(WITHOPENMPI)
1144       if( getenv("OMPI_URI_FILE") == NULL )
1145         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace";
1146       else{
1147         tempOutputFile << "-x PATH -x LD_LIBRARY_PATH -x OMNIORB_CONFIG -x SALOME_trace -ompi-server file:";
1148         tempOutputFile << getenv("OMPI_URI_FILE");
1149       }
1150 #endif
1151     }
1152
1153   tempOutputFile << getenv("KERNEL_ROOT_DIR") << "/bin/salome/";
1154
1155   if (params.isMPI)
1156     {
1157       if (isPythonContainer(params.container_name))
1158         tempOutputFile << " pyMPI SALOME_ContainerPy.py ";
1159       else
1160         tempOutputFile << " SALOME_MPIContainer ";
1161     }
1162
1163   else
1164     {
1165       if (isPythonContainer(params.container_name))
1166         tempOutputFile << "SALOME_ContainerPy.py ";
1167       else
1168         tempOutputFile << "SALOME_Container ";
1169     }
1170
1171   tempOutputFile << _NS->ContainerName(params) << " -";
1172   AddOmninamesParams(tempOutputFile);
1173   tempOutputFile << " &" << endl;
1174   tempOutputFile.flush();
1175   tempOutputFile.close();
1176 #ifndef WIN32
1177   chmod(_TmpFileName.c_str(), 0x1ED);
1178 #endif
1179
1180   // --- Build command
1181
1182   string command;
1183
1184   if (resInfo.Protocol == rsh)
1185     {
1186       command = "rsh ";
1187       string commandRcp = "rcp ";
1188       commandRcp += _TmpFileName;
1189       commandRcp += " ";
1190       commandRcp += machine;
1191       commandRcp += ":";
1192       commandRcp += _TmpFileName;
1193       status = system(commandRcp.c_str());
1194     }
1195
1196   else if (resInfo.Protocol == ssh)
1197     {
1198       command = "ssh ";
1199       string commandRcp = "scp ";
1200       commandRcp += _TmpFileName;
1201       commandRcp += " ";
1202       commandRcp += machine;
1203       commandRcp += ":";
1204       commandRcp += _TmpFileName;
1205       status = system(commandRcp.c_str());
1206     }
1207   else
1208     throw SALOME_Exception("Unknown protocol");
1209
1210   if(status)
1211     throw SALOME_Exception("Error of connection on remote host");    
1212
1213   command += machine;
1214   _CommandForRemAccess = command;
1215   command += " ";
1216   command += _TmpFileName;
1217
1218   SCRUTE(command);
1219
1220   return command;
1221
1222 }
1223
1224 //=============================================================================
1225 /*! Creates a command line that the container manager uses to launch
1226  * a parallel container.
1227  */ 
1228 //=============================================================================
1229 string 
1230 SALOME_ContainerManager::BuildCommandToLaunchLocalParallelContainer(const std::string& exe_name,
1231                                                                     const Engines::MachineParameters& params,
1232                                                                     const std::string& log)
1233 {
1234   // This method knows the differences between the proxy and the nodes.
1235   // nb_component_nodes is not used in the same way if it is a proxy or 
1236   // a node.
1237
1238   string command;
1239   string parallelLib(CORBA::string_dup(params.parallelLib));
1240   string hostname(CORBA::string_dup(params.hostname));
1241   int par = exe_name.find("Proxy");
1242   int nbproc = params.nb_component_nodes;
1243   char buffer [33];
1244   sprintf(buffer,"%d",nbproc);
1245
1246   Engines::MachineParameters_var rtn = new Engines::MachineParameters();
1247   rtn->container_name = params.container_name;
1248   rtn->hostname = params.hostname;
1249   rtn->OS = params.OS;
1250   rtn->mem_mb = params.mem_mb;
1251   rtn->cpu_clock = params.cpu_clock;
1252   rtn->nb_proc_per_node = params.nb_proc_per_node;
1253   rtn->nb_node = params.nb_node;
1254   rtn->isMPI = params.isMPI;
1255
1256   string real_exe_name  = exe_name + parallelLib;
1257
1258   if (parallelLib == "Dummy")
1259     {
1260       //command = "gdb --args ";
1261       //command = "valgrind --tool=memcheck --log-file=val_log ";
1262       //command += real_exe_name;
1263
1264       command = real_exe_name;
1265
1266       command += " " + _NS->ContainerName(rtn);
1267       command += " " + parallelLib;
1268       command += " " + hostname;
1269       command += " -";
1270       AddOmninamesParams(command);
1271     }
1272
1273   else if (parallelLib == "Mpi")
1274     {
1275       // Step 1 : check if MPI is started
1276       if (_MpiStarted == false)
1277         {
1278           startMPI();
1279         }
1280
1281       if (par < 0)
1282         {
1283           // Nodes case
1284
1285           command = "mpiexec -np " + string(buffer) + " ";
1286           //      command += "gdb --args ";
1287           command += real_exe_name;
1288           command += " " + _NS->ContainerName(rtn);
1289           command += " " + parallelLib;
1290           command += " " + hostname;
1291           command += " -";
1292           AddOmninamesParams(command);
1293         }
1294       else                                          
1295         {
1296           // Proxy case
1297           command = "mpiexec -np 1 ";
1298           command += real_exe_name;
1299           command += " " + _NS->ContainerName(rtn);
1300           command += " " + string(buffer);
1301           command += " " + parallelLib;
1302           command += " " + hostname;
1303           command += " -";
1304           AddOmninamesParams(command);
1305         }
1306     }
1307   else
1308     {
1309       std::string message("Unknown parallelLib" + parallelLib);
1310       throw SALOME_Exception(message.c_str());
1311     }
1312
1313   // log choice
1314   if (log == "default")
1315     {
1316       command += " > /tmp/";
1317       command += _NS->ContainerName(rtn);
1318       command += "_";
1319       command += Kernel_Utils::GetHostname();
1320       command += "_";
1321       command += getenv( "USER" ) ;
1322       command += ".log 2>&1 &" ;
1323     }
1324   if (log == "xterm")
1325     {
1326       command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;  " 
1327         + command + " \" &";
1328       //              + command + "; echo $LD_LIBRARY_PATH; cat \" &";
1329     }
1330   return command;
1331
1332   /*  if (log == "xterm")
1333       {
1334       command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH; echo $LD_LIBRARY_PATH; echo $PATH; " + command + "; cat \" &";
1335       }
1336   */
1337   /*  command = "cd ; rm " + fichier_commande + "; touch " + \
1338       fichier_commande + "; echo \" export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; " + \
1339       command + " >& /tmp/ribes_" + fichier_commande + " & \" > " + fichier_commande + ";";
1340       command += "ssh cn01 sh " + fichier_commande + " &";
1341       cerr << "La commande : " << command << endl;
1342   */
1343 }
1344
1345 void SALOME_ContainerManager::startMPI()
1346 {
1347   cerr << "----------------------------------------------" << endl;
1348   cerr << "----------------------------------------------" << endl;
1349   cerr << "----------------------------------------------" << endl;
1350   cerr << "-Only Lam on Localhost is currently supported-" << endl;
1351   cerr << "----------------------------------------------" << endl;
1352   cerr << "----------------------------------------------" << endl;
1353   cerr << "----------------------------------------------" << endl;
1354
1355   int status = system("lamboot");
1356   if (status == -1)
1357     {
1358       INFOS("lamboot failed : system command status -1");
1359     }
1360   else if (status == 217)
1361     {
1362       INFOS("lamboot failed : system command status 217");
1363     }
1364   else
1365     {
1366       _MpiStarted = true;
1367     }
1368 }
1369
1370 string SALOME_ContainerManager::GetMPIZeroNode(string machine)
1371 {
1372   int status;
1373   string zeronode;
1374   string cmd;
1375   string tmpFile = BuildTemporaryFileName();
1376
1377   cmd = "ssh " + machine + " mpirun -np 1 hostname > " + tmpFile;
1378
1379   status = system(cmd.c_str());
1380   if( status == 0 ){
1381     ifstream fp(tmpFile.c_str(),ios::in);
1382     fp >> zeronode;
1383   }
1384
1385   RmTmpFile(tmpFile);
1386
1387   return zeronode;
1388 }