Salome HOME
Integration of 0019971: A patch for cmake compilation.
[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(unsigned 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(unsigned 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               continue;
380             }
381           SALOME_ModuleCatalog::ImplType impl=compoInfo->implementation_type();
382           container_exe=compoInfo->implementation_name();
383           if(impl==SALOME_ModuleCatalog::CEXE)
384             {
385               if(found)
386                 {
387                   INFOS("ContainerManager Error: you can't have 2 CEXE component in the same container" );
388                   return Engines::Container::_nil();
389                 }
390               found=1;
391             }
392         }
393     }
394   catch (ServiceUnreachable&)
395     {
396       INFOS("Caught exception: Naming Service Unreachable");
397       return Engines::Container::_nil();
398     }
399   catch (...)
400     {
401       INFOS("Caught unknown exception.");
402       return Engines::Container::_nil();
403     }
404
405   if(found)
406     return StartContainer(params,possibleComputers,policy,container_exe.in());
407   else
408     return StartContainer(params,possibleComputers,policy);
409 }
410
411 #ifdef WITH_PACO_PARALLEL
412 //=============================================================================
413 /*! CORBA Method:
414  *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
415  *  \param params            Machine Parameters required for the container
416  *  \param possibleComputers list of machines usable for find or start
417  *
418  *  \return CORBA container reference.
419  */
420 //=============================================================================
421 Engines::Container_ptr
422 SALOME_ContainerManager::
423 FindOrStartParallelContainer(const Engines::MachineParameters& params_const,
424                              const Engines::MachineList& possibleComputers)
425 {
426   CORBA::Object_var obj;
427   PaCO::InterfaceManager_var proxy;
428   Engines::Container_ptr ret = Engines::Container::_nil();
429   Engines::MachineParameters params(params_const);
430
431   // Step 1 : Try to find a suitable container
432   // Currently not as good as could be since
433   // we have to verified the number of nodes of the container
434   // if a user tell that.
435   ret = FindContainer(params, possibleComputers);
436
437   if(CORBA::is_nil(ret)) {
438     // Step 2 : Starting a new parallel container
439     INFOS("[FindOrStartParallelContainer] Starting a parallel container");
440
441     // Step 2.1 : Choose a computer
442     string theMachine = _ResManager->FindFirst(possibleComputers);
443     if(theMachine == "") {
444       INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
445       INFOS("[FindOrStartParallelContainer] No possible computer found");
446       INFOS("[FindOrStartParallelContainer] !!!!!!!!!!!!!!!!!!!!!!!!!!");
447     }
448     else {
449       INFOS("[FindOrStartParallelContainer] on machine : " << theMachine);
450       string command;
451       if(theMachine == GetHostname()) {
452         // Step 3 : starting parallel container proxy
453         params.hostname = CORBA::string_dup(theMachine.c_str());
454         Engines::MachineParameters params_proxy(params);
455         try {
456           command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerProxy", params_proxy, "xterm");
457         }
458         catch(const SALOME_Exception & ex){
459           MESSAGE(ex.what());
460           return Engines::Container::_nil();
461         }
462         // LaunchParallelContainer uses this value to know if it launches the proxy or the nodes
463         params_proxy.nb_component_nodes = 0;
464         obj = LaunchParallelContainer(command, params_proxy, _NS->ContainerName(params));
465         ret = Engines::Container::_narrow(obj);
466         proxy = PaCO::InterfaceManager::_narrow(obj);
467
468         // Step 4 : starting parallel container nodes
469         command = BuildCommandToLaunchLocalParallelContainer("SALOME_ParallelContainerNode", params, "xterm");
470         string name = _NS->ContainerName(params) + "Node";
471         LaunchParallelContainer(command, params, name);
472         // Step 5 : connecting nodes and the proxy to actually create a parallel container
473         try {
474           for (int i = 0; i < params.nb_component_nodes; i++) {
475
476             char buffer [5];
477 #ifndef WNT
478             snprintf(buffer,5,"%d",i);
479 #else
480             _snprintf(buffer,5,"%d",i);
481 #endif
482             string name_cont = name + string(buffer);
483
484             string theNodeMachine(CORBA::string_dup(params.hostname));
485             string containerNameInNS = _NS->BuildContainerNameForNS(name_cont.c_str(),theNodeMachine.c_str());
486             int count = TIME_OUT_TO_LAUNCH_CONT;
487             obj = _NS->Resolve(containerNameInNS.c_str());
488             while (CORBA::is_nil(obj) && count) {
489               INFOS("[FindOrStartParallelContainer] CONNECTION FAILED !!!!!!!!!!!!!!!!!!!!!!!!");
490 #ifndef WNT
491               sleep(1) ;
492 #else
493               Sleep(1000);
494 #endif
495               count-- ;
496               obj = _NS->Resolve(containerNameInNS.c_str());
497             }
498
499             PaCO::InterfaceParallel_var node = PaCO::InterfaceParallel::_narrow(obj);
500             MESSAGE("[FindOrStartParallelContainer] Deploying node : " << name);
501             node->deploy();
502           }
503           proxy->start();
504         }
505         catch(CORBA::SystemException& e)
506         {
507           INFOS("Caught CORBA::SystemException. : " << e);
508         }
509         catch(PortableServer::POA::ServantAlreadyActive&)
510         {
511           INFOS("Caught CORBA::ServantAlreadyActiveException");
512         }
513         catch(CORBA::Exception&)
514         {
515           INFOS("Caught CORBA::Exception.");
516         }
517         catch(std::exception& exc)
518         {
519           INFOS("Caught std::exception - "<<exc.what()); 
520         }
521         catch(...)
522         {
523           INFOS("Caught unknown exception.");
524         }
525         INFOS("[FindOrStartParallelContainer] node " << name << " deployed");
526       }
527       else {
528         INFOS("[FindOrStartParallelContainer] Currently parallel containers are launched only on the local host");
529       }
530     }
531 }
532 return ret;
533 }
534 #else
535 //=============================================================================
536 /*! CORBA Method:
537  *  Find or Start a suitable PaCO++ Parallel Container in a list of machines.
538  *  \param params            Machine Parameters required for the container
539  *  \param possibleComputers list of machines usable for find or start
540  *
541  *  \return CORBA container reference.
542  */
543 //=============================================================================
544 Engines::Container_ptr
545 SALOME_ContainerManager::
546 FindOrStartParallelContainer(const Engines::MachineParameters& params,
547                              const Engines::MachineList& possibleComputers)
548 {
549   Engines::Container_ptr ret = Engines::Container::_nil();
550   INFOS("[FindOrStartParallelContainer] is disabled !");
551   INFOS("[FindOrStartParallelContainer] recompile SALOME Kernel to enable parallel extension");
552   return ret;
553 }
554 #endif
555
556 //=============================================================================
557 /*! CORBA Method:
558  *  Give a suitable Container in a list of machines
559  *  \param params            Machine Parameters required for the container
560  *  \param possibleComputers list of machines usable for start
561  */
562 //=============================================================================
563
564 Engines::Container_ptr
565 SALOME_ContainerManager::
566 GiveContainer(const Engines::MachineParameters& params,
567                Engines::ResPolicy policy,
568                const Engines::CompoList& componentList)
569 {
570   char *valenv=getenv("SALOME_BATCH");
571   if(valenv)
572     if (strcmp(valenv,"1")==0)
573       {
574         if(_batchLaunchedContainers.empty())
575           fillBatchLaunchedContainers();
576
577         if (_batchLaunchedContainersIter == _batchLaunchedContainers.end())
578           _batchLaunchedContainersIter = _batchLaunchedContainers.begin();
579
580         Engines::Container_ptr rtn = Engines::Container::_duplicate(*_batchLaunchedContainersIter);
581         _batchLaunchedContainersIter++;
582         return rtn;
583       }
584   return StartContainer(params,policy,componentList);
585 }
586
587 //=============================================================================
588 /*! 
589  * 
590  */
591 //=============================================================================
592
593 Engines::Container_ptr
594 SALOME_ContainerManager::
595 FindContainer(const Engines::MachineParameters& params,
596               const char *theMachine)
597 {
598   string containerNameInNS(_NS->BuildContainerNameForNS(params,theMachine));
599   CORBA::Object_var obj = _NS->Resolve(containerNameInNS.c_str());
600   if( !CORBA::is_nil(obj) )
601     return Engines::Container::_narrow(obj);
602   else
603     return Engines::Container::_nil();
604 }
605
606 //=============================================================================
607 /*! 
608  * 
609  */
610 //=============================================================================
611
612 Engines::Container_ptr
613 SALOME_ContainerManager::
614 FindContainer(const Engines::MachineParameters& params,
615               const Engines::MachineList& possibleComputers)
616 {
617   MESSAGE("FindContainer "<<possibleComputers.length());
618   for(unsigned int i=0;i<possibleComputers.length();i++)
619     {
620       MESSAGE("FindContainer possible " << possibleComputers[i]);
621       Engines::Container_ptr cont = FindContainer(params,possibleComputers[i]);
622       if( !CORBA::is_nil(cont) )
623         return cont;
624     }
625   MESSAGE("FindContainer: not found");
626   return Engines::Container::_nil();
627 }
628
629 //=============================================================================
630 /*! This method launches the parallel container.
631  *  It will may be placed on the ressources manager.
632  *
633  * \param command to launch
634  * \param container's parameters
635  * \param name of the container
636  *
637  * \return CORBA container reference
638  */
639 //=============================================================================
640 CORBA::Object_ptr 
641 SALOME_ContainerManager::LaunchParallelContainer(const std::string& command, 
642                                                  const Engines::MachineParameters& params,
643                                                  const std::string& name)
644 {
645   CORBA::Object_ptr obj = CORBA::Object::_nil();
646   string containerNameInNS;
647   MESSAGE("[LaunchParallelContainer] : command to launch...");
648   MESSAGE(command);
649   if (params.nb_component_nodes == 0) {
650     INFOS("[LaunchParallelContainer] launching the proxy of the parallel container");
651     int status = system(command.c_str());
652     if (status == -1) {
653       INFOS("[LaunchParallelContainer] failed : system command status -1");
654     }
655     else if (status == 217) {
656       INFOS("[LaunchParallelContainer] failed : system command status 217");
657     }
658
659     int count = TIME_OUT_TO_LAUNCH_CONT;
660     string theMachine(CORBA::string_dup(params.hostname));
661     containerNameInNS = _NS->BuildContainerNameForNS((char*) name.c_str(),theMachine.c_str());
662
663     INFOS("[LaunchParallelContainer]  Waiting for Parallel Container proxy on " << theMachine);
664     while (CORBA::is_nil(obj) && count) {
665 #ifndef WNT
666       sleep(1) ;
667 #else
668       Sleep(1000);
669 #endif
670       count-- ;
671       obj = _NS->Resolve(containerNameInNS.c_str());
672     }
673   }
674   else {
675     INFOS("[LaunchParallelContainer] launching the nodes of the parallel container");
676     int status = system(command.c_str());
677     if (status == -1) {
678       INFOS("[LaunchParallelContainer] failed : system command status -1");
679     }
680     else if (status == 217) {
681       INFOS("[LaunchParallelContainer] failed : system command status 217");
682     }
683     // We are waiting all the nodes
684     for (int i = 0; i < params.nb_component_nodes; i++) {
685       obj = CORBA::Object::_nil();
686       int count = TIME_OUT_TO_LAUNCH_CONT;
687
688       // Name of the node
689       char buffer [5];
690 #ifndef WNT
691       snprintf(buffer,5,"%d",i);
692 #else
693       _snprintf(buffer,5,"%d",i);
694 #endif
695
696       string name_cont = name + string(buffer);
697
698       // I don't like this...
699       string theMachine(CORBA::string_dup(params.hostname));
700       containerNameInNS = _NS->BuildContainerNameForNS((char*) name_cont.c_str(),theMachine.c_str());
701       cerr << "[LaunchContainer]  Waiting for Parllel Container node " << containerNameInNS << " on " << theMachine << endl;
702       while (CORBA::is_nil(obj) && count) {
703 #ifndef WNT
704         sleep(1) ;
705 #else
706         Sleep(1000);
707 #endif
708         count-- ;
709         obj = _NS->Resolve(containerNameInNS.c_str());
710       }
711     }
712   }
713
714   if ( CORBA::is_nil(obj) ) {
715     INFOS("[LaunchParallelContainer] failed");
716   }
717   return obj;
718 }
719
720 //=============================================================================
721 /*! 
722  * Get Id for container: a parallel container registers in Naming Service
723  * on the machine where is process 0. ContainerManager does'nt know the name
724  * of this machine before the launch of the parallel container. So to get
725  * the IOR of the parallel container in Naming Service, ContainerManager
726  * gives a unique Id. The parallel container registers his name under
727  * /ContainerManager/Id directory in NamingService
728  */
729 //=============================================================================
730
731
732 long SALOME_ContainerManager::GetIdForContainer(void)
733 {
734   _id++;
735   return _id;
736 }
737
738 void SALOME_ContainerManager::fillBatchLaunchedContainers()
739 {
740   _batchLaunchedContainers.clear();
741   _NS->Change_Directory("/Containers");
742   vector<string> vec = _NS->list_directory_recurs();
743   for(vector<string>::iterator iter = vec.begin();iter!=vec.end();iter++){
744     CORBA::Object_var obj=_NS->Resolve((*iter).c_str());
745     Engines::Container_ptr cont=Engines::Container::_narrow(obj);
746     if(!CORBA::is_nil(cont)){
747       _batchLaunchedContainers.push_back(cont);
748     }
749   }
750   _batchLaunchedContainersIter=_batchLaunchedContainers.begin();
751 }
752
753 //=============================================================================
754 /*!
755  *  This is no longer valid (C++ container are also python containers)
756  */ 
757 //=============================================================================
758
759 bool isPythonContainer(const char* ContainerName)
760 {
761   bool ret = false;
762   int len = strlen(ContainerName);
763
764   if (len >= 2)
765     if (strcmp(ContainerName + len - 2, "Py") == 0)
766       ret = true;
767
768   return ret;
769 }
770
771 //=============================================================================
772 /*!
773  *  Builds the script to be launched
774  *
775  *  If SALOME Application not defined ($APPLI),
776  *  see BuildTempFileToLaunchRemoteContainer()
777  *
778  *  Else rely on distant configuration. Command is under the form (example):
779  *  ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
780  *                   SALOME_Container containerName &"
781
782  *  - where user is ommited if not specified in CatalogResources,
783  *  - where distant path is always relative to user@machine $HOME, and
784  *    equal to $APPLI if not specified in CatalogResources,
785  *  - where hostNS is the hostname of CORBA naming server (set by scripts to
786  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
787  *  - where portNS is the port used by CORBA naming server (set by scripts to
788  *    use to launch SALOME and servers in $APPLI: runAppli.sh, runRemote.sh)
789  *  - where workingdir is the requested working directory for the container.
790  *    If WORKINGDIR (and workingdir) is not present the working dir will be $HOME
791  */ 
792 //=============================================================================
793
794 string
795 SALOME_ContainerManager::BuildCommandToLaunchRemoteContainer
796 (const string& machine,
797  const Engines::MachineParameters& params, const long id,const std::string& container_exe)
798 {
799   string command;
800   int nbproc;
801   char idc[3*sizeof(long)];
802           
803   if ( ! _isAppliSalomeDefined )
804     command = BuildTempFileToLaunchRemoteContainer(machine, params);
805
806   else
807     {
808       const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
809
810       if (params.isMPI)
811         {
812           if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
813             nbproc = 1;
814           else if ( params.nb_node == 0 )
815             nbproc = params.nb_proc_per_node;
816           else if ( params.nb_proc_per_node == 0 )
817             nbproc = params.nb_node;
818           else
819             nbproc = params.nb_node * params.nb_proc_per_node;
820         }
821
822       // "ssh user@machine distantPath/runRemote.sh hostNS portNS WORKINGDIR workingdir \
823       //  SALOME_Container containerName &"
824
825       if (resInfo.Protocol == rsh)
826         command = "rsh ";
827       else if (resInfo.Protocol == ssh)
828         command = "ssh ";
829       else
830         throw SALOME_Exception("Unknown protocol");
831
832       if (resInfo.UserName != "")
833         {
834           command += resInfo.UserName;
835           command += "@";
836         }
837
838       command += machine;
839       command += " ";
840
841       if (resInfo.AppliPath != "")
842         command += resInfo.AppliPath; // path relative to user@machine $HOME
843       else
844         {
845           ASSERT(getenv("APPLI"));
846           command += getenv("APPLI"); // path relative to user@machine $HOME
847         }
848
849       command += "/runRemote.sh ";
850
851       ASSERT(getenv("NSHOST")); 
852       command += getenv("NSHOST"); // hostname of CORBA name server
853
854       command += " ";
855       ASSERT(getenv("NSPORT"));
856       command += getenv("NSPORT"); // port of CORBA name server
857
858       std::string wdir=params.workingdir.in();
859       if(wdir != "")
860         {
861           command += " WORKINGDIR ";
862           command += " '";
863           if(wdir == "$TEMPDIR")
864             wdir="\\$TEMPDIR";
865           command += wdir; // requested working directory
866           command += "'"; 
867         }
868
869       if(params.isMPI)
870         {
871           command += " mpirun -np ";
872           std::ostringstream o;
873           o << nbproc << " ";
874           command += o.str();
875 #ifdef WITHLAM
876           command += "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
877 #endif  
878           command += " SALOME_MPIContainer ";
879         }
880       else
881         command += " " +container_exe+ " ";
882
883       command += _NS->ContainerName(params);
884       command += " -id ";
885       sprintf(idc,"%ld",id);
886       command += idc;
887       command += " -";
888       AddOmninamesParams(command);
889
890       MESSAGE("command =" << command);
891     }
892
893   return command;
894 }
895
896 //=============================================================================
897 /*!
898  *  builds the command to be launched.
899  */ 
900 //=============================================================================
901
902 string
903 SALOME_ContainerManager::BuildCommandToLaunchLocalContainer
904 (const Engines::MachineParameters& params, const long id,const std::string& container_exe)
905 {
906   _TmpFileName = BuildTemporaryFileName();
907   string command;
908   int nbproc = 0;
909   //char idc[3*sizeof(long)];
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 #endif
937
938       if (isPythonContainer(params.container_name))
939         //command += "pyMPI SALOME_ContainerPy.py ";
940         command_file << "pyMPI SALOME_ContainerPy.py ";
941       else
942         //command += "SALOME_MPIContainer ";
943         command_file << "SALOME_MPIContainer ";
944     }
945
946   else
947     {
948       //command="";
949       std::string wdir=params.workingdir.in();
950       if(wdir != "")
951         {
952           // a working directory is requested
953           if(wdir == "$TEMPDIR")
954             {
955               // a new temporary directory is requested
956               string dir = OpUtil_Dir::GetTmpDir();
957 #ifdef WIN32
958               //command += "cd /d "+ dir +";";
959               command_file << "cd /d " << dir << endl;
960 #else
961               //command = "cd "+ dir +";";
962               command_file << "cd " << dir << ";";
963 #endif
964
965             }
966           else
967             {
968               // a permanent directory is requested use it or create it
969 #ifdef WIN32
970               //command="mkdir " + wdir;
971               command_file << "mkdir " + wdir << endl;
972               command_file << "cd /D " + wdir << endl;
973 #else
974               //command="mkdir -p " + wdir + " && cd " + wdir + ";";
975               command_file << "mkdir -p " << wdir << " && cd " << wdir + ";";
976 #endif
977             }
978         }
979       if (isPythonContainer(params.container_name))
980         //command += "SALOME_ContainerPy.py ";
981         command_file << "SALOME_ContainerPy.py ";
982       else
983         //command += container_exe + " ";
984         command_file << container_exe + " ";
985
986     }
987
988
989   /*command += _NS->ContainerName(params);
990   command += " -id ";
991   sprintf(idc,"%ld",id);
992   command += idc;
993   command += " -";  
994   AddOmninamesParams(command);*/
995
996   command_file << _NS->ContainerName(params);
997   command_file << " -id " << id << " -";
998   AddOmninamesParams(command_file);
999   command_file.close();
1000
1001 #ifndef WIN32
1002   chmod(_TmpFileName.c_str(), 0x1ED);
1003 #endif
1004   command = _TmpFileName;
1005
1006   MESSAGE("Command is file ... " << command);
1007   return command;
1008 }
1009
1010
1011 //=============================================================================
1012 /*!
1013  *  removes the generated temporary file in case of a remote launch.
1014  */ 
1015 //=============================================================================
1016
1017 void SALOME_ContainerManager::RmTmpFile()
1018 {
1019   if (_TmpFileName != "")
1020     {
1021 #ifndef WNT
1022       string command = "rm ";
1023 #else
1024       string command = "del /F ";
1025 #endif
1026       command += _TmpFileName;
1027       char *temp = strdup(command.c_str());
1028       int lgthTemp = strlen(temp);
1029       temp[lgthTemp - 3] = '*';
1030       temp[lgthTemp - 2] = '\0';
1031       system(temp);
1032       free(temp);
1033     }
1034 }
1035
1036 //=============================================================================
1037 /*!
1038  *   add to command all options relative to naming service.
1039  */ 
1040 //=============================================================================
1041
1042 void SALOME_ContainerManager::AddOmninamesParams(string& command) const
1043   {
1044     CORBA::String_var iorstr = _NS->getIORaddr();
1045     command += "ORBInitRef NameService=";
1046     command += iorstr;
1047   }
1048
1049
1050 //=============================================================================
1051 /*!
1052  *  add to command all options relative to naming service.
1053  */ 
1054 //=============================================================================
1055
1056 void SALOME_ContainerManager::AddOmninamesParams(ofstream& fileStream) const
1057   {
1058     CORBA::String_var iorstr = _NS->getIORaddr();
1059     fileStream << "ORBInitRef NameService=";
1060     fileStream << iorstr;
1061   }
1062
1063 //=============================================================================
1064 /*!
1065  *  generate a file name in /tmp directory
1066  */ 
1067 //=============================================================================
1068
1069 string SALOME_ContainerManager::BuildTemporaryFileName() const
1070   {
1071     //build more complex file name to support multiple salome session
1072     string aFileName = OpUtil_Dir::GetTmpFileName();
1073 #ifndef WIN32
1074     aFileName += ".sh";
1075 #else
1076     aFileName += ".bat";
1077 #endif
1078     return aFileName;
1079   }
1080
1081
1082 //=============================================================================
1083 /*!
1084  *  Builds in a temporary file the script to be launched.
1085  *  
1086  *  Used if SALOME Application ($APPLI) is not defined.
1087  *  The command is build with data from CatalogResources, in which every path
1088  *  used on remote computer must be defined.
1089  */ 
1090 //=============================================================================
1091
1092 string
1093 SALOME_ContainerManager::BuildTempFileToLaunchRemoteContainer
1094 (const string& machine,
1095  const Engines::MachineParameters& params) throw(SALOME_Exception)
1096 {
1097   int status;
1098
1099   _TmpFileName = BuildTemporaryFileName();
1100   ofstream tempOutputFile;
1101   tempOutputFile.open(_TmpFileName.c_str(), ofstream::out );
1102   const ParserResourcesType& resInfo = _ResManager->GetImpl()->GetResourcesList(machine);
1103   tempOutputFile << "#! /bin/sh" << endl;
1104
1105   // --- set env vars
1106
1107   tempOutputFile << "export SALOME_trace=local" << endl; // mkr : 27.11.2006 : PAL13967 - Distributed supervision graphs - Problem with "SALOME_trace"
1108   //tempOutputFile << "source " << resInfo.PreReqFilePath << endl;
1109
1110   // ! env vars
1111
1112   if (params.isMPI)
1113     {
1114       tempOutputFile << "mpirun -np ";
1115       int nbproc;
1116
1117       if ( (params.nb_node <= 0) && (params.nb_proc_per_node <= 0) )
1118         nbproc = 1;
1119       else if ( params.nb_node == 0 )
1120         nbproc = params.nb_proc_per_node;
1121       else if ( params.nb_proc_per_node == 0 )
1122         nbproc = params.nb_node;
1123       else
1124         nbproc = params.nb_node * params.nb_proc_per_node;
1125
1126       std::ostringstream o;
1127
1128       tempOutputFile << nbproc << " ";
1129 #ifdef WITHLAM
1130       tempOutputFile << "-x PATH,LD_LIBRARY_PATH,OMNIORB_CONFIG,SALOME_trace ";
1131 #endif
1132     }
1133
1134   tempOutputFile << getenv("KERNEL_ROOT_DIR") << "/bin/salome/";
1135
1136   if (params.isMPI)
1137     {
1138       if (isPythonContainer(params.container_name))
1139         tempOutputFile << "pyMPI SALOME_ContainerPy.py ";
1140       else
1141         tempOutputFile << "SALOME_MPIContainer ";
1142     }
1143
1144   else
1145     {
1146       if (isPythonContainer(params.container_name))
1147         tempOutputFile << "SALOME_ContainerPy.py ";
1148       else
1149         tempOutputFile << "SALOME_Container ";
1150     }
1151
1152   tempOutputFile << _NS->ContainerName(params) << " -";
1153   AddOmninamesParams(tempOutputFile);
1154   tempOutputFile << " &" << endl;
1155   tempOutputFile.flush();
1156   tempOutputFile.close();
1157 #ifndef WIN32
1158   chmod(_TmpFileName.c_str(), 0x1ED);
1159 #endif
1160
1161   // --- Build command
1162
1163   string command;
1164
1165   if (resInfo.Protocol == rsh)
1166     {
1167       command = "rsh ";
1168       string commandRcp = "rcp ";
1169       commandRcp += _TmpFileName;
1170       commandRcp += " ";
1171       commandRcp += machine;
1172       commandRcp += ":";
1173       commandRcp += _TmpFileName;
1174       status = system(commandRcp.c_str());
1175     }
1176
1177   else if (resInfo.Protocol == ssh)
1178     {
1179       command = "ssh ";
1180       string commandRcp = "scp ";
1181       commandRcp += _TmpFileName;
1182       commandRcp += " ";
1183       commandRcp += machine;
1184       commandRcp += ":";
1185       commandRcp += _TmpFileName;
1186       status = system(commandRcp.c_str());
1187     }
1188   else
1189     throw SALOME_Exception("Unknown protocol");
1190
1191   if(status)
1192     throw SALOME_Exception("Error of connection on remote host");    
1193
1194   command += machine;
1195   _CommandForRemAccess = command;
1196   command += " ";
1197   command += _TmpFileName;
1198
1199   SCRUTE(command);
1200
1201   return command;
1202
1203 }
1204
1205 //=============================================================================
1206 /*! Creates a command line that the container manager uses to launch
1207  * a parallel container.
1208  */ 
1209 //=============================================================================
1210 string 
1211 SALOME_ContainerManager::BuildCommandToLaunchLocalParallelContainer(const std::string& exe_name,
1212                                                                     const Engines::MachineParameters& params,
1213                                                                     const std::string& log)
1214 {
1215   // This method knows the differences between the proxy and the nodes.
1216   // nb_component_nodes is not used in the same way if it is a proxy or 
1217   // a node.
1218
1219   string command;
1220   string parallelLib(CORBA::string_dup(params.parallelLib));
1221   string hostname(CORBA::string_dup(params.hostname));
1222   int par = exe_name.find("Proxy");
1223   int nbproc = params.nb_component_nodes;
1224   char buffer [33];
1225   sprintf(buffer,"%d",nbproc);
1226
1227   Engines::MachineParameters_var rtn = new Engines::MachineParameters();
1228   rtn->container_name = params.container_name;
1229   rtn->hostname = params.hostname;
1230   rtn->OS = params.OS;
1231   rtn->mem_mb = params.mem_mb;
1232   rtn->cpu_clock = params.cpu_clock;
1233   rtn->nb_proc_per_node = params.nb_proc_per_node;
1234   rtn->nb_node = params.nb_node;
1235   rtn->isMPI = params.isMPI;
1236
1237   string real_exe_name  = exe_name + parallelLib;
1238
1239   if (parallelLib == "Dummy")
1240   {
1241     //command = "gdb --args ";
1242     //command = "valgrind --tool=memcheck --log-file=val_log ";
1243     //command += real_exe_name;
1244
1245     command = real_exe_name;
1246
1247     command += " " + _NS->ContainerName(rtn);
1248     command += " " + parallelLib;
1249     command += " " + hostname;
1250     command += " -";
1251     AddOmninamesParams(command);
1252   }
1253
1254   else if (parallelLib == "Mpi")
1255   {
1256     // Step 1 : check if MPI is started
1257     if (_MpiStarted == false)
1258     {
1259       startMPI();
1260     }
1261
1262     if (par < 0)
1263     {
1264       // Nodes case
1265
1266       command = "mpiexec -np " + string(buffer) + " ";
1267 //      command += "gdb --args ";
1268       command += real_exe_name;
1269       command += " " + _NS->ContainerName(rtn);
1270       command += " " + parallelLib;
1271       command += " " + hostname;
1272       command += " -";
1273       AddOmninamesParams(command);
1274     }
1275     else                                          
1276     {
1277       // Proxy case
1278       command = "mpiexec -np 1 ";
1279       command += real_exe_name;
1280       command += " " + _NS->ContainerName(rtn);
1281       command += " " + string(buffer);
1282       command += " " + parallelLib;
1283       command += " " + hostname;
1284       command += " -";
1285       AddOmninamesParams(command);
1286     }
1287   }
1288   else
1289   {
1290     std::string message("Unknown parallelLib" + parallelLib);
1291     throw SALOME_Exception(message.c_str());
1292   }
1293
1294   // log choice
1295   if (log == "default")
1296   {
1297     command += " > /tmp/";
1298     command += _NS->ContainerName(rtn);
1299     command += "_";
1300     command += GetHostname();
1301     command += "_";
1302     command += getenv( "USER" ) ;
1303     command += ".log 2>&1 &" ;
1304   }
1305   if (log == "xterm")
1306   {
1307     command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH;  " 
1308               + command + " \" &";
1309 //            + command + "; echo $LD_LIBRARY_PATH; cat \" &";
1310   }
1311   return command;
1312
1313 /*  if (log == "xterm")
1314   {
1315     command = "/usr/X11R6/bin/xterm -e \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; export PATH=$PATH; echo $LD_LIBRARY_PATH; echo $PATH; " + command + "; cat \" &";
1316   }
1317 */
1318 /*  command = "cd ; rm " + fichier_commande + "; touch " + \
1319              fichier_commande + "; echo \" export LD_LIBRARY_PATH=$LD_LIBRARY_PATH; " + \
1320              command + " >& /tmp/ribes_" + fichier_commande + " & \" > " + fichier_commande + ";";
1321   command += "ssh cn01 sh " + fichier_commande + " &";
1322   cerr << "La commande : " << command << endl;
1323 */
1324 }
1325
1326 void SALOME_ContainerManager::startMPI()
1327 {
1328   cerr << "----------------------------------------------" << endl;
1329   cerr << "----------------------------------------------" << endl;
1330   cerr << "----------------------------------------------" << endl;
1331   cerr << "-Only Lam on Localhost is currently supported-" << endl;
1332   cerr << "----------------------------------------------" << endl;
1333   cerr << "----------------------------------------------" << endl;
1334   cerr << "----------------------------------------------" << endl;
1335
1336   int status = system("lamboot");
1337   if (status == -1)
1338   {
1339     INFOS("lamboot failed : system command status -1");
1340   }
1341   else if (status == 217)
1342   {
1343     INFOS("lamboot failed : system command status 217");
1344   }
1345   else
1346   {
1347     _MpiStarted = true;
1348   }
1349 }
1350