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