Salome HOME
Merge from V6_main_20120808 08Aug12
[modules/yacs.git] / src / Launcher / Launcher.cxx
1 // Copyright (C) 2007-2012  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
23 #ifdef WITH_LIBBATCH
24 #include <Batch/Batch_Date.hxx>
25 #include <Batch/Batch_BatchManagerCatalog.hxx>
26 #include <Batch/Batch_FactBatchManager_eClient.hxx>
27 #include <Batch/Batch_BatchManager_eClient.hxx>
28 #endif
29
30 #include "Basics_Utils.hxx"
31 #include "Basics_DirUtils.hxx"
32 #include "SALOME_Launcher_Handler.hxx"
33 #include "Launcher.hxx"
34 #include "Launcher_Job_Command.hxx"
35 #include <iostream>
36 #include <sstream>
37 #include <sys/stat.h>
38 #include <time.h>
39
40 //=============================================================================
41 /*! 
42  *  Constructor
43  *  \param orb
44  *  Define a CORBA single thread policy for the server, which avoid to deal
45  *  with non thread-safe usage like Change_Directory in SALOME naming service
46  */
47 //=============================================================================
48 Launcher_cpp::Launcher_cpp()
49 {
50   LAUNCHER_MESSAGE("Launcher_cpp constructor");
51   _job_cpt = 0;
52   _job_cpt_mutex = new pthread_mutex_t();
53   pthread_mutex_init(_job_cpt_mutex, NULL);
54 }
55
56 //=============================================================================
57 /*! 
58  * destructor
59  */
60 //=============================================================================
61 Launcher_cpp::~Launcher_cpp()
62 {
63   LAUNCHER_MESSAGE("Launcher_cpp destructor");
64 #ifdef WITH_LIBBATCH
65   std::map<int, Launcher::Job *>::const_iterator it_job;
66   for(it_job = _launcher_job_map.begin(); it_job != _launcher_job_map.end(); it_job++)
67     delete it_job->second;
68   std::map <int, Batch::BatchManager_eClient * >::const_iterator it1;
69   for(it1=_batchmap.begin();it1!=_batchmap.end();it1++)
70     delete it1->second;
71 #endif
72
73   pthread_mutex_destroy(_job_cpt_mutex);
74   delete _job_cpt_mutex;
75 }
76
77 #ifdef WITH_LIBBATCH
78
79 //=============================================================================
80 /*!
81  * Add a job into the launcher - check resource and choose one 
82  */ 
83 //=============================================================================
84 void 
85 Launcher_cpp::createJob(Launcher::Job * new_job)
86 {
87   LAUNCHER_MESSAGE("Creating a new job");
88   // Add job to the jobs map
89   pthread_mutex_lock(_job_cpt_mutex);
90   new_job->setNumber(_job_cpt);
91   _job_cpt++;
92   pthread_mutex_unlock(_job_cpt_mutex);
93   std::map<int, Launcher::Job *>::const_iterator it_job = _launcher_job_map.find(new_job->getNumber());
94   if (it_job == _launcher_job_map.end())
95     _launcher_job_map[new_job->getNumber()] = new_job;
96   else
97   {
98     LAUNCHER_INFOS("A job as already the same id: " << new_job->getNumber());
99     delete new_job;
100     throw LauncherException("A job as already the same id - job is not created !");
101   }
102   LAUNCHER_MESSAGE("New Job created");
103 }
104
105 //=============================================================================
106 /*!
107  * Launch a job 
108  */ 
109 //=============================================================================
110 void 
111 Launcher_cpp::launchJob(int job_id)
112 {
113   LAUNCHER_MESSAGE("Launch a job");
114
115   // Check if job exist
116   std::map<int, Launcher::Job *>::const_iterator it_job = _launcher_job_map.find(job_id);
117   if (it_job == _launcher_job_map.end())
118   {
119     LAUNCHER_INFOS("Cannot find the job, is it created ? job number: " << job_id);
120     throw LauncherException("Cannot find the job, is it created ?");
121   }
122
123   Launcher::Job * job = it_job->second;
124
125   // Check job state (cannot launch a job already launched...)
126   if (job->getState() != "CREATED")
127   {
128     LAUNCHER_INFOS("Bad state of the job: " << job->getState());
129     throw LauncherException("Bad state of the job: " + job->getState());
130   }
131
132   // Third step search batch manager for the job into the map -> instanciate one if does not exist
133 #ifdef WITH_LIBBATCH
134   std::map<int, Batch::BatchManager_eClient *>::const_iterator it = _batchmap.find(job_id);
135   if(it == _batchmap.end())
136   {
137     createBatchManagerForJob(job);
138   }
139 #endif
140
141   try {
142     Batch::JobId batch_manager_job_id = _batchmap[job_id]->submitJob(*(job->getBatchJob()));
143     job->setBatchManagerJobId(batch_manager_job_id);
144     job->setState("QUEUED");
145   }
146   catch(const Batch::EmulationException &ex)
147   {
148     LAUNCHER_INFOS("Job is not launched, exception in submitJob: " << ex.message);
149     throw LauncherException(ex.message.c_str());
150   }
151   LAUNCHER_MESSAGE("Job launched");
152 }
153
154 //=============================================================================
155 /*!
156  * Get job state
157  */ 
158 //=============================================================================
159 const char *
160 Launcher_cpp::getJobState(int job_id)
161 {
162   LAUNCHER_MESSAGE("Get job state");
163
164   // Check if job exist
165   std::map<int, Launcher::Job *>::const_iterator it_job = _launcher_job_map.find(job_id);
166   if (it_job == _launcher_job_map.end())
167   {
168     LAUNCHER_INFOS("Cannot find the job, is it created ? job number: " << job_id);
169     throw LauncherException("Cannot find the job, is it created ?");
170   }
171
172   Launcher::Job * job = it_job->second;
173
174   std::string state;
175   try
176   {
177     state = job->updateJobState();
178   }
179   catch(const Batch::EmulationException &ex)
180   {
181     LAUNCHER_INFOS("getJobState failed, exception: " << ex.message);
182     throw LauncherException(ex.message.c_str());
183   }
184   catch(const Batch::RunTimeException &ex)
185   {
186     LAUNCHER_INFOS("getJobState failed, exception: " << ex.message);
187     throw LauncherException(ex.message.c_str());
188   }
189
190   return state.c_str();
191 }
192
193 //=============================================================================
194 /*!
195  * Get Job result - the result directory could be changed
196  */ 
197 //=============================================================================
198 void
199 Launcher_cpp::getJobResults(int job_id, std::string directory)
200 {
201   LAUNCHER_MESSAGE("Get Job results");
202
203   // Check if job exist
204   std::map<int, Launcher::Job *>::const_iterator it_job = _launcher_job_map.find(job_id);
205   if (it_job == _launcher_job_map.end())
206   {
207     LAUNCHER_INFOS("Cannot find the job, is it created ? job number: " << job_id);
208     throw LauncherException("Cannot find the job, is it created ?");
209   }
210
211   Launcher::Job * job = it_job->second;
212   std::string resource_name = job->getResourceDefinition().Name;
213   try 
214   {
215     if (directory != "")
216       _batchmap[job_id]->importOutputFiles(*(job->getBatchJob()), directory);
217     else
218       _batchmap[job_id]->importOutputFiles(*(job->getBatchJob()), job->getResultDirectory());
219   }
220   catch(const Batch::EmulationException &ex)
221   {
222     LAUNCHER_INFOS("getJobResult is maybe incomplete, exception: " << ex.message);
223     throw LauncherException(ex.message.c_str());
224   }
225   LAUNCHER_MESSAGE("getJobResult ended");
226 }
227
228 //=============================================================================
229 /*!
230  * Get Job dump state - the result directory could be changed
231  */ 
232 //=============================================================================
233 bool
234 Launcher_cpp::getJobDumpState(int job_id, std::string directory)
235 {
236   bool rtn;
237   LAUNCHER_MESSAGE("Get Job dump state");
238
239   // Check if job exist
240   std::map<int, Launcher::Job *>::const_iterator it_job = _launcher_job_map.find(job_id);
241   if (it_job == _launcher_job_map.end())
242   {
243     LAUNCHER_INFOS("Cannot find the job, is it created ? job number: " << job_id);
244     throw LauncherException("Cannot find the job, is it created ?");
245   }
246
247   Launcher::Job * job = it_job->second;
248   std::string resource_name = job->getResourceDefinition().Name;
249   try 
250   {
251     if (directory != "")
252       rtn = _batchmap[job_id]->importDumpStateFile(*(job->getBatchJob()), directory);
253     else
254       rtn = _batchmap[job_id]->importDumpStateFile(*(job->getBatchJob()), job->getResultDirectory());
255   }
256   catch(const Batch::EmulationException &ex)
257   {
258     LAUNCHER_INFOS("getJobResult is maybe incomplete, exception: " << ex.message);
259     throw LauncherException(ex.message.c_str());
260   }
261   LAUNCHER_MESSAGE("getJobResult ended");
262   return rtn;
263 }
264
265 //=============================================================================
266 /*!
267  * Remove the job - into the Launcher and its batch manager
268  */ 
269 //=============================================================================
270 void
271 Launcher_cpp::removeJob(int job_id)
272 {
273   LAUNCHER_MESSAGE("Remove Job");
274
275   // Check if job exist
276   std::map<int, Launcher::Job *>::iterator it_job = _launcher_job_map.find(job_id);
277   if (it_job == _launcher_job_map.end())
278   {
279     LAUNCHER_INFOS("Cannot find the job, is it created ? job number: " << job_id);
280     throw LauncherException("Cannot find the job, is it created ?");
281   }
282
283   it_job->second->removeJob();
284   delete it_job->second;
285   _launcher_job_map.erase(it_job);
286 }
287
288 //=============================================================================
289 /*!
290  * stop the job
291  */ 
292 //=============================================================================
293 void
294 Launcher_cpp::stopJob(int job_id)
295 {
296   LAUNCHER_MESSAGE("Stop Job");
297
298   // Check if job exist
299   std::map<int, Launcher::Job *>::iterator it_job = _launcher_job_map.find(job_id);
300   if (it_job == _launcher_job_map.end())
301   {
302     LAUNCHER_INFOS("Cannot find the job, is it created ? job number: " << job_id);
303     throw LauncherException("Cannot find the job, is it created ?");
304   }
305
306   it_job->second->stopJob();
307 }
308
309 //=============================================================================
310 /*! 
311  *  create a launcher job based on a file
312  *  \param xmlExecuteFile     : to define the execution on the batch cluster
313  */
314 //=============================================================================
315 long 
316 Launcher_cpp::createJobWithFile(const std::string xmlExecuteFile, 
317                                 const std::string clusterName)
318 {
319   LAUNCHER_MESSAGE("Begin of Launcher_cpp::createJobWithFile");
320
321   // Parsing xml file
322   ParserLauncherType job_params = ParseXmlFile(xmlExecuteFile);
323
324   // Creating a new job
325   Launcher::Job_Command * new_job = new Launcher::Job_Command();
326
327   std::string cmdFile = Kernel_Utils::GetTmpFileName();  
328 #ifndef WIN32
329   cmdFile += ".sh";
330 #else
331   cmdFile += ".bat";
332 #endif
333   std::ofstream os;
334   os.open(cmdFile.c_str(), std::ofstream::out );
335   os << "#! /bin/sh" << std::endl;
336   os << job_params.Command;
337   os.close();
338
339   new_job->setJobFile(cmdFile);
340   new_job->setLocalDirectory(job_params.RefDirectory);
341   new_job->setWorkDirectory(job_params.MachinesList[clusterName].WorkDirectory);
342   new_job->setEnvFile(job_params.MachinesList[clusterName].EnvFile);
343
344   for(int i=0; i < job_params.InputFile.size(); i++)
345     new_job->add_in_file(job_params.InputFile[i]);
346   for(int i=0; i < job_params.OutputFile.size();i++)
347     new_job->add_out_file(job_params.OutputFile[i]);
348
349   resourceParams p;
350   p.hostname = clusterName;
351   p.name = "";
352   p.OS = "";
353   p.nb_proc = job_params.NbOfProcesses;
354   p.nb_node = 0;
355   p.nb_proc_per_node = 0;
356   p.cpu_clock = 0;
357   p.mem_mb = 0;
358   new_job->setResourceRequiredParams(p);
359
360   createJob(new_job);
361   return new_job->getNumber();
362 }
363
364 //=============================================================================
365 /*!
366  *  Factory to instanciate the good batch manager for choosen cluster.
367  */ 
368 //=============================================================================
369 Batch::BatchManager_eClient *
370 Launcher_cpp::FactoryBatchManager(ParserResourcesType& params)
371 {
372   std::string mpi;
373   Batch::CommunicationProtocolType protocol;
374   Batch::FactBatchManager_eClient* fact;
375
376   int nb_proc_per_node = params.DataForSort._nbOfProcPerNode;
377   std::string hostname = params.HostName;
378
379   switch(params.Protocol)
380   {
381     case rsh:
382       protocol = Batch::RSH;
383       break;
384     case ssh:
385       protocol = Batch::SSH;
386       break;
387     default:
388       throw LauncherException("Unknown protocol for this resource");
389       break;
390   }
391
392   switch(params.mpi)
393   {
394     case lam:
395       mpi = "lam";
396       break;
397     case mpich1:
398       mpi = "mpich1";
399       break;
400     case mpich2:
401       mpi = "mpich2";
402       break;
403     case openmpi:
404       mpi = "openmpi";
405       break;
406     case slurmmpi:
407       mpi = "slurmmpi";
408       break;
409     case prun:
410       mpi = "prun";
411       break;
412     default:
413       mpi = "nompi";
414   }
415
416   const char * bmType;
417   switch( params.Batch )
418   {
419     case pbs:
420       bmType = "ePBS";
421       break;
422     case lsf:
423       bmType = "eLSF";
424       break;
425     case sge:
426       bmType = "eSGE";
427       break;
428     case ccc:
429       bmType = "eCCC";
430       break;
431     case slurm:
432       bmType = "eSLURM";
433       break;
434     case ssh_batch:
435       bmType = "eSSH";
436       break;
437     case ll:
438       bmType = "eLL";
439       break;
440     case vishnu:
441       bmType = "eVISHNU";
442       break;
443     default:
444       LAUNCHER_MESSAGE("Bad batch description of the resource: Batch = " << params.Batch);
445       throw LauncherException("No batchmanager for that cluster - Bad batch description of the resource");
446   }
447   Batch::BatchManagerCatalog & cata = Batch::BatchManagerCatalog::getInstance();
448   fact = dynamic_cast<Batch::FactBatchManager_eClient*>(cata(bmType));
449   if (fact == NULL) {
450     LAUNCHER_MESSAGE("Cannot find batch manager factory for " << bmType << ". Check your version of libBatch.");
451     throw LauncherException("Cannot find batch manager factory");
452   }
453   LAUNCHER_MESSAGE("Instanciation of batch manager of type: " << bmType);
454   Batch::BatchManager_eClient * batch_client = (*fact)(hostname.c_str(), params.UserName.c_str(),
455                                                        protocol, mpi.c_str(), nb_proc_per_node);
456   return batch_client;
457 }
458
459 //----------------------------------------------------------
460 // Without LIBBATCH - Launcher_cpp do nothing...
461 //----------------------------------------------------------
462 #else
463
464 void 
465 Launcher_cpp::createJob(Launcher::Job * new_job)
466 {
467   LAUNCHER_INFOS("Launcher compiled without LIBBATCH - cannot create a job !!!");
468   delete new_job;
469   throw LauncherException("Method Launcher_cpp::createJob is not available "
470                           "(libBatch was not present at compilation time)");
471 }
472
473 void 
474 Launcher_cpp::launchJob(int job_id)
475 {
476   LAUNCHER_INFOS("Launcher compiled without LIBBATCH - cannot launch a job !!!");
477   throw LauncherException("Method Launcher_cpp::launchJob is not available "
478                           "(libBatch was not present at compilation time)");
479 }
480
481 const char *
482 Launcher_cpp::getJobState(int job_id)
483 {
484   LAUNCHER_INFOS("Launcher compiled without LIBBATCH - cannot get job state!!!");
485   throw LauncherException("Method Launcher_cpp::getJobState is not available "
486                           "(libBatch was not present at compilation time)");
487 }
488
489 void
490 Launcher_cpp::getJobResults(int job_id, std::string directory)
491 {
492   LAUNCHER_INFOS("Launcher compiled without LIBBATCH - cannot get job results!!!");
493   throw LauncherException("Method Launcher_cpp::getJobResults is not available "
494                           "(libBatch was not present at compilation time)");
495 }
496
497 bool
498 Launcher_cpp::getJobDumpState(int job_id, std::string directory)
499 {
500   LAUNCHER_INFOS("Launcher compiled without LIBBATCH - cannot get job dump state!!!");
501   throw LauncherException("Method Launcher_cpp::getJobDumpState is not available "
502                           "(libBatch was not present at compilation time)");
503 }
504
505 void
506 Launcher_cpp::removeJob(int job_id)
507 {
508   LAUNCHER_INFOS("Launcher compiled without LIBBATCH - cannot remove job!!!");
509   throw LauncherException("Method Launcher_cpp::removeJob is not available "
510                           "(libBatch was not present at compilation time)");
511 }
512
513 void
514 Launcher_cpp::stopJob(int job_id)
515 {
516   throw LauncherException("Method Launcher_cpp::stopJob is not available "
517                           "(libBatch was not present at compilation time)");
518 }
519
520 long 
521 Launcher_cpp::createJobWithFile( const std::string xmlExecuteFile, std::string clusterName)
522 {
523   throw LauncherException("Method Launcher_cpp::createJobWithFile is not available "
524                           "(libBatch was not present at compilation time)");
525   return 0;
526 }
527
528 #endif
529
530 ParserLauncherType 
531 Launcher_cpp::ParseXmlFile(std::string xmlExecuteFile)
532 {
533   ParserLauncherType job_params;
534   SALOME_Launcher_Handler * handler = new SALOME_Launcher_Handler(job_params);
535
536   const char* aFilePath = xmlExecuteFile.c_str();
537   FILE* aFile = fopen(aFilePath, "r");
538   if (aFile != NULL)
539   {
540     xmlDocPtr aDoc = xmlReadFile(aFilePath, NULL, 0);
541     if (aDoc != NULL)
542       handler->ProcessXmlDocument(aDoc);
543     else
544     {
545       std::string message = "ResourcesManager_cpp: could not parse file: " + xmlExecuteFile;
546       LAUNCHER_MESSAGE(message);
547       delete handler;
548       throw LauncherException(message);
549     }
550     // Free the document
551     xmlFreeDoc(aDoc);
552     fclose(aFile);
553   }
554   else
555   {
556     std::string message = "ResourcesManager_cpp: file is not readable: " + xmlExecuteFile;
557     LAUNCHER_MESSAGE(message);
558     delete handler;
559     throw LauncherException(message);
560   }
561
562   // Return
563   delete handler;
564   return job_params;
565 }
566
567 std::map<int, Launcher::Job *>
568 Launcher_cpp::getJobs()
569 {
570   return _launcher_job_map;
571 }
572
573 void 
574 Launcher_cpp::createBatchManagerForJob(Launcher::Job * job)
575 {
576   int job_id = job->getNumber();
577
578   // Select a ressource for the job
579   std::vector<std::string> ResourceList;
580   resourceParams params = job->getResourceRequiredParams();
581   try
582   {
583     ResourceList = _ResManager->GetFittingResources(params);
584   }
585   catch(const ResourcesException &ex)
586   {
587     throw LauncherException(ex.msg.c_str());
588   }
589   if (ResourceList.size() == 0)
590   {
591     LAUNCHER_INFOS("No adequate resource found for the job, number " << job->getNumber());
592     job->setState("ERROR");
593     throw LauncherException("No resource found the job");
594   }
595
596   // Configure the job with the resource selected - the first of the list
597   ParserResourcesType resource_definition = _ResManager->GetResourcesDescr(ResourceList[0]);
598
599   // Set resource definition to the job
600   // The job will check if the definitions needed
601   try
602   {
603     job->setResourceDefinition(resource_definition);
604   }
605   catch(const LauncherException &ex)
606   {
607     LAUNCHER_INFOS("Error in the definition of the resource, mess: " << ex.msg);
608     job->setState("ERROR");
609     throw ex;
610   }
611
612   // Step 2: We can now add a Factory if the resource is correctly define
613 #ifdef WITH_LIBBATCH
614   std::map<int, Batch::BatchManager_eClient *>::const_iterator it = _batchmap.find(job_id);
615   if(it == _batchmap.end())
616   {
617     try
618     {
619       // Warning cannot write on one line like this, because map object is constructed before
620       // the method is called...
621       //_batchmap[job_id] = FactoryBatchManager(resource_definition);
622       Batch::BatchManager_eClient * batch_client = FactoryBatchManager(resource_definition);
623       _batchmap[job_id] = batch_client;
624     }
625     catch(const LauncherException &ex)
626     {
627       LAUNCHER_INFOS("Error during creation of the batch manager of the job, mess: " << ex.msg);
628       throw ex;
629     }
630     catch(const Batch::EmulationException &ex)
631     {
632       LAUNCHER_INFOS("Error during creation of the batch manager of the job, mess: " << ex.message);
633       throw LauncherException(ex.message);
634     }
635     catch(const Batch::InvalidArgumentException &ex)
636     {
637       LAUNCHER_INFOS("Error during creation of the batch manager of the job, mess: " << ex.message);
638       throw LauncherException(ex.message);
639     }
640   }
641 #endif
642 }
643
644 void 
645 Launcher_cpp::addJobDirectlyToMap(Launcher::Job * new_job, const std::string job_reference)
646 {
647   // Step 0: Calculated job_id
648   pthread_mutex_lock(_job_cpt_mutex);
649   int job_id = _job_cpt;
650   _job_cpt++;
651   new_job->setNumber(job_id);
652   pthread_mutex_unlock(_job_cpt_mutex);
653
654   // Step 1: check if resource is already in the map
655   createBatchManagerForJob(new_job);
656
657   // Step 2: add the job to the batch manager
658 #ifdef WITH_LIBBATCH
659   try
660   {
661     Batch::JobId batch_manager_job_id = _batchmap[job_id]->addJob(*(new_job->getBatchJob()),
662                                                                   job_reference);
663     new_job->setBatchManagerJobId(batch_manager_job_id);
664   }
665   catch(const Batch::EmulationException &ex)
666   {
667     LAUNCHER_INFOS("Job cannot be added, exception in addJob: " << ex.message);
668     throw LauncherException(ex.message.c_str());
669   }
670
671   // Step 3: add job to launcher map
672   std::map<int, Launcher::Job *>::const_iterator it_job = _launcher_job_map.find(new_job->getNumber());
673   if (it_job == _launcher_job_map.end())
674     _launcher_job_map[new_job->getNumber()] = new_job;
675   else
676   {
677     LAUNCHER_INFOS("A job as already the same id: " << new_job->getNumber());
678     delete new_job;
679     throw LauncherException("A job as already the same id - job is not created !");
680   }
681   LAUNCHER_MESSAGE("New job added");
682 #endif
683 }