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