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