Salome HOME
433c30b1480433bdf8a403a6bcae3a02d43d7334
[modules/kernel.git] / src / Launcher / SALOME_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 #include "SALOME_Launcher.hxx"
24 #include "BatchTest.hxx"
25 #include "OpUtil.hxx"
26 #include "SALOME_ContainerManager.hxx"
27 #include "Utils_CorbaException.hxx"
28
29
30 #include "Launcher_Job_Command.hxx"
31 #include "Launcher_Job_YACSFile.hxx"
32 #include "Launcher_Job_PythonSALOME.hxx"
33
34 #ifdef WIN32
35 # include <process.h>
36 #else
37 # include <unistd.h>
38 #endif
39 #include <sys/types.h>
40 #include <vector>
41
42 #include <libxml/parser.h>
43 #include <stdio.h>
44 #include <sstream>
45
46 const char *SALOME_Launcher::_LauncherNameInNS = "/SalomeLauncher";
47
48 //=============================================================================
49 /*! 
50  *  Constructor
51  *  \param orb
52  */
53 //=============================================================================
54 SALOME_Launcher::SALOME_Launcher(CORBA::ORB_ptr orb, PortableServer::POA_var poa) : _l()
55 {
56   MESSAGE("SALOME_Launcher constructor");
57   _NS = new SALOME_NamingService(orb);
58   _ResManager = new SALOME_ResourcesManager(orb,poa,_NS);
59   _l.SetResourcesManager(_ResManager->GetImpl());
60   _ContManager = new SALOME_ContainerManager(orb,poa,_ResManager,_NS);
61   _ResManager->_remove_ref();
62   _ContManager->_remove_ref();
63
64   _orb = CORBA::ORB::_duplicate(orb) ;
65   _poa = PortableServer::POA::_duplicate(poa) ;
66   PortableServer::ObjectId_var id = _poa->activate_object(this);
67   CORBA::Object_var obj = _poa->id_to_reference(id);
68   Engines::SalomeLauncher_var refContMan = Engines::SalomeLauncher::_narrow(obj);
69
70   _NS->Register(refContMan,_LauncherNameInNS);
71   MESSAGE("SALOME_Launcher constructor end");
72 }
73
74 //=============================================================================
75 /*! 
76  * destructor
77  */
78 //=============================================================================
79 SALOME_Launcher::~SALOME_Launcher()
80 {
81   MESSAGE("SALOME_Launcher destructor");
82   delete _NS;
83   MESSAGE("SALOME_Launcher destructor end");
84 }
85
86
87 CORBA::Long 
88 SALOME_Launcher::createJob(const Engines::JobParameters & job_parameters)
89 {
90   std::string job_type = job_parameters.job_type.in();
91
92   if (job_type != "command" && job_type != "yacs_file" && job_type != "python_salome")
93   {
94     std::string message("SALOME_Launcher::createJob: bad job type: ");
95     message += job_type;
96     THROW_SALOME_CORBA_EXCEPTION(message.c_str(), SALOME::INTERNAL_ERROR);
97   }
98
99   Launcher::Job * new_job; // It is Launcher_cpp that is going to destroy it
100
101   if (job_type == "command")
102     new_job = new Launcher::Job_Command();
103   else if (job_type == "yacs_file")
104     new_job = new Launcher::Job_YACSFile();
105   else if (job_type == "python_salome")
106     new_job = new Launcher::Job_PythonSALOME();
107
108   // Name
109   new_job->setJobName(job_parameters.job_name.in());
110
111   // Directories
112   std::string work_directory = job_parameters.work_directory.in();
113   std::string local_directory = job_parameters.local_directory.in();
114   std::string result_directory = job_parameters.result_directory.in();
115   new_job->setWorkDirectory(work_directory);
116   new_job->setLocalDirectory(local_directory);
117   new_job->setResultDirectory(result_directory);
118
119   // Job File
120   std::string job_file = job_parameters.job_file.in();
121   try
122   {
123     new_job->setJobFile(job_file);
124   }
125   catch(const LauncherException &ex)
126   {
127     INFOS(ex.msg.c_str());
128     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::INTERNAL_ERROR);
129   }
130
131   // Files
132   std::string env_file = job_parameters.env_file.in();
133   new_job->setEnvFile(env_file);
134   for (CORBA::ULong i = 0; i < job_parameters.in_files.length(); i++)
135     new_job->add_in_file(job_parameters.in_files[i].in());
136   for (CORBA::ULong i = 0; i < job_parameters.out_files.length(); i++)
137     new_job->add_out_file(job_parameters.out_files[i].in());
138
139   // Expected During Time
140   try
141   {
142     std::string maximum_duration = job_parameters.maximum_duration.in();
143     new_job->setMaximumDuration(maximum_duration);
144   }
145   catch(const LauncherException &ex){
146     INFOS(ex.msg.c_str());
147     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::INTERNAL_ERROR);
148   }
149
150   // Queue
151   std::string queue = job_parameters.queue.in();
152   new_job->setQueue(queue);
153
154   // Resources requirements
155   try
156   {
157     resourceParams p;
158     p.name = job_parameters.resource_required.name;
159     p.hostname = job_parameters.resource_required.hostname;
160     p.OS = job_parameters.resource_required.OS;
161     p.nb_proc = job_parameters.resource_required.nb_proc;
162     p.nb_node = job_parameters.resource_required.nb_node;
163     p.nb_proc_per_node = job_parameters.resource_required.nb_proc_per_node;
164     p.cpu_clock = job_parameters.resource_required.cpu_clock;
165     p.mem_mb = job_parameters.resource_required.mem_mb;
166     new_job->setResourceRequiredParams(p);
167   }
168   catch(const LauncherException &ex){
169     INFOS(ex.msg.c_str());
170     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::INTERNAL_ERROR);
171   }
172
173   // Adding specific parameters to the job
174   for (CORBA::ULong i = 0; i < job_parameters.specific_parameters.length(); i++)
175     new_job->addSpecificParameter(job_parameters.specific_parameters[i].name.in(),
176                                   job_parameters.specific_parameters[i].value.in());
177   try
178   {
179     new_job->checkSpecificParameters();
180   }
181   catch(const LauncherException &ex)
182   {
183     INFOS(ex.msg.c_str());
184     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::INTERNAL_ERROR);
185   }
186
187   try
188   {
189     _l.createJob(new_job);
190     std::ostringstream job_id;
191     job_id << new_job->getNumber();
192     notifyObservers("NEW_JOB", job_id.str());
193   }
194   catch(const LauncherException &ex)
195   {
196     INFOS(ex.msg.c_str());
197     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
198   }
199   return new_job->getNumber();
200 }
201
202 void 
203 SALOME_Launcher::launchJob(CORBA::Long job_id)
204 {
205   try
206   {
207     _l.launchJob(job_id);
208   }
209   catch(const LauncherException &ex)
210   {
211     INFOS(ex.msg.c_str());
212     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
213   }
214 }
215
216 char *
217 SALOME_Launcher::getJobState(CORBA::Long job_id)
218 {
219   std::string result;
220   try
221   {
222     result = _l.getJobState(job_id);
223   }
224   catch(const LauncherException &ex)
225   {
226     INFOS(ex.msg.c_str());
227     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
228   }
229   return CORBA::string_dup(result.c_str());
230 }
231
232 void
233 SALOME_Launcher::getJobResults(CORBA::Long job_id, const char * directory)
234 {
235   try
236   {
237     _l.getJobResults(job_id, directory);
238   }
239   catch(const LauncherException &ex)
240   {
241     INFOS(ex.msg.c_str());
242     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
243   }
244 }
245
246 CORBA::Boolean
247 SALOME_Launcher::getJobDumpState(CORBA::Long job_id, const char * directory)
248 {
249   CORBA::Boolean rtn = false;
250   try
251   {
252     rtn = _l.getJobDumpState(job_id, directory);
253   }
254   catch(const LauncherException &ex)
255   {
256     INFOS(ex.msg.c_str());
257     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
258   }
259   return rtn;
260 }
261
262 void 
263 SALOME_Launcher::removeJob(CORBA::Long job_id)
264 {
265   try
266   {
267     _l.removeJob(job_id);
268     std::ostringstream job_id_str;
269     job_id_str << job_id;
270     notifyObservers("REMOVE_JOB", job_id_str.str());
271   }
272   catch(const LauncherException &ex)
273   {
274     INFOS(ex.msg.c_str());
275     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
276   }
277 }
278
279 void 
280 SALOME_Launcher::stopJob(CORBA::Long job_id)
281 {
282   try
283   {
284     _l.stopJob(job_id);
285     std::ostringstream job_id_str;
286     job_id_str << job_id;
287     notifyObservers("UPDATE_JOB_STATE", job_id_str.str());
288   }
289   catch(const LauncherException &ex)
290   {
291     INFOS(ex.msg.c_str());
292     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::BAD_PARAM);
293   }
294 }
295
296 //=============================================================================
297 /*! CORBA Method:
298  *  Create a job in the launcher with a file
299  *  \param xmlExecuteFile     : .xml to parse that contains job description
300  *  \param clusterName        : machine choosed
301  */
302 //=============================================================================
303 CORBA::Long 
304 SALOME_Launcher::createJobWithFile(const char * xmlExecuteFile,
305                                    const char * clusterName)
306 {
307   CORBA::Long jobId;
308   try{
309     jobId = _l.createJobWithFile(xmlExecuteFile, clusterName);
310   }
311   catch(const LauncherException &ex){
312     INFOS(ex.msg.c_str());
313     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::INTERNAL_ERROR);
314   }
315
316   return jobId;
317 }
318
319 //=============================================================================
320 /*! CORBA Method:
321  *  the test batch configuration 
322  *  \param params             : The batch cluster
323  */
324 //=============================================================================
325 CORBA::Boolean 
326 SALOME_Launcher::testBatch(const Engines::ResourceParameters& params)
327 {
328   MESSAGE("BEGIN OF SALOME_Launcher::testBatch");
329   CORBA::Boolean rtn = false;
330   try
331   {
332     // find a cluster matching the structure params
333     Engines::ResourceList *aMachineList = _ResManager->GetFittingResources(params);
334     if (aMachineList->length() == 0)
335       throw SALOME_Exception("No resources have been found with your parameters");
336
337     const Engines::ResourceDefinition* p = _ResManager->GetResourceDefinition((*aMachineList)[0]);
338         std::string resource_name(p->name);
339     INFOS("Choose resource for test: " <<  resource_name);
340     
341     BatchTest t(*p);
342     if (t.test()) 
343     {
344       rtn = true;
345     }
346   }
347   catch(const LauncherException &ex){
348     INFOS(ex.msg.c_str());
349     THROW_SALOME_CORBA_EXCEPTION(ex.msg.c_str(),SALOME::INTERNAL_ERROR);
350   }
351   return rtn;
352 }
353
354 //=============================================================================
355 /*! CORBA method:
356  *  shutdown all the containers, then the ContainerManager servant
357  */
358 //=============================================================================
359 void SALOME_Launcher::Shutdown()
360 {
361   MESSAGE("Shutdown");
362   _NS->Destroy_Name(_LauncherNameInNS);
363   _ContManager->Shutdown();
364   _ResManager->Shutdown();
365   PortableServer::ObjectId_var oid = _poa->servant_to_id(this);
366   _poa->deactivate_object(oid);
367   if(!CORBA::is_nil(_orb))
368     _orb->shutdown(0);
369 }
370
371 //=============================================================================
372 /*! CORBA Method:
373  *  Returns the PID of the process
374  */
375 //=============================================================================
376 CORBA::Long SALOME_Launcher::getPID()
377 {
378   return 
379 #ifndef WIN32
380     (CORBA::Long)getpid();
381 #else
382     (CORBA::Long)_getpid();
383 #endif
384 }
385
386 //=============================================================================
387 /*! CORBA Method:
388  *  Returns current launcher jobs list
389  */
390 //=============================================================================
391 Engines::JobsList *
392 SALOME_Launcher::getJobsList()
393 {
394   Engines::JobsList_var jobs_list = new Engines::JobsList();
395   std::map<int, Launcher::Job *> cpp_jobs = _l.getJobs();
396   std::map<int, Launcher::Job *>::const_iterator it_job;
397   int list_id = 0;
398   for(it_job = cpp_jobs.begin(); it_job != cpp_jobs.end(); it_job++)
399   {
400     int number          = it_job->first;
401     try
402     {
403       // Prepare CORBA job description
404       Engines::JobDescription_var job_descr = new Engines::JobDescription();
405       Engines::JobParameters_var job_parameters = getJobParameters(number);
406       job_descr->job_id = number;
407       job_descr->job_parameters = job_parameters;
408
409       // Add job description to the sequence
410       jobs_list->length(list_id + 1);
411       jobs_list[list_id] = job_descr;
412       list_id++;
413     }
414     catch (...) {}
415   }
416   return jobs_list._retn();
417 }
418
419 //=============================================================================
420 /*! CORBA Method:
421  * Returns the job description
422  */
423 //=============================================================================
424 Engines::JobParameters *
425 SALOME_Launcher::getJobParameters(CORBA::Long job_id)
426 {
427   std::map<int, Launcher::Job *> cpp_jobs = _l.getJobs();
428   std::map<int, Launcher::Job *>::const_iterator it_job = cpp_jobs.find(job_id);
429   if (it_job == cpp_jobs.end())
430   {
431     INFOS("Cannot find the job, is it created ? job number: " << job_id);
432     THROW_SALOME_CORBA_EXCEPTION("Job does not exist", SALOME::INTERNAL_ERROR);
433   }
434
435   Launcher::Job * job = it_job->second;
436   Engines::JobParameters_var job_parameters = new Engines::JobParameters;
437   job_parameters->job_name         = CORBA::string_dup(job->getJobName().c_str());
438   job_parameters->job_type         = CORBA::string_dup(job->getJobType().c_str());
439   job_parameters->job_file         = CORBA::string_dup(job->getJobFile().c_str());
440   job_parameters->env_file         = CORBA::string_dup(job->getEnvFile().c_str());
441   job_parameters->work_directory   = CORBA::string_dup(job->getWorkDirectory().c_str());
442   job_parameters->local_directory  = CORBA::string_dup(job->getLocalDirectory().c_str());
443   job_parameters->result_directory = CORBA::string_dup(job->getResultDirectory().c_str());
444
445   int i = 0;
446   int j = 0;
447   std::list<std::string> in_files  = job->get_in_files();
448   std::list<std::string> out_files = job->get_out_files();
449   job_parameters->in_files.length(in_files.size());
450   for(std::list<std::string>::iterator it = in_files.begin(); it != in_files.end(); it++)
451   {
452     job_parameters->in_files[i] = CORBA::string_dup((*it).c_str());
453     i++;
454   }
455   job_parameters->out_files.length(out_files.size());
456   for(std::list<std::string>::iterator it = out_files.begin(); it != out_files.end(); it++)
457   {
458     job_parameters->out_files[j] = CORBA::string_dup((*it).c_str());
459     j++;
460   }
461
462   job_parameters->maximum_duration = CORBA::string_dup(job->getMaximumDuration().c_str());
463   job_parameters->queue            = CORBA::string_dup(job->getQueue().c_str());
464
465   resourceParams resource_params = job->getResourceRequiredParams();
466   job_parameters->resource_required.name             = CORBA::string_dup(resource_params.name.c_str());
467   job_parameters->resource_required.hostname         = CORBA::string_dup(resource_params.hostname.c_str());
468   job_parameters->resource_required.OS               = CORBA::string_dup(resource_params.OS.c_str());
469   job_parameters->resource_required.nb_proc          = resource_params.nb_proc;
470   job_parameters->resource_required.nb_node          = resource_params.nb_node;
471   job_parameters->resource_required.nb_proc_per_node = resource_params.nb_proc_per_node;
472   job_parameters->resource_required.cpu_clock        = resource_params.cpu_clock;
473   job_parameters->resource_required.mem_mb           = resource_params.mem_mb;
474
475   std::map<std::string, std::string> specific_parameters = job->getSpecificParameters();
476   if (!specific_parameters.empty())
477   {
478     job_parameters->specific_parameters.length(specific_parameters.size());
479     std::map<std::string, std::string>::const_iterator it_specific;
480     CORBA::ULong i = 0;
481     for (it_specific = specific_parameters.begin() ; it_specific != specific_parameters.end(); it_specific++)
482     {
483       Engines::Parameter_var new_param = new Engines::Parameter;
484       new_param->name  = CORBA::string_dup((it_specific->first).c_str());
485       new_param->value = CORBA::string_dup((it_specific->second).c_str());
486       job_parameters->specific_parameters[i] = new_param;
487       i++;
488     }
489   }
490
491   return job_parameters._retn();
492 }
493
494 //=============================================================================
495 /*! CORBA Method:
496  *  Loads jobs saved in jobs_file
497  */
498 //=============================================================================
499 void
500 SALOME_Launcher::loadJobs(const char* jobs_file)
501 {
502   // Step 1: check jobs_file read access
503   FILE* xml_file = fopen(jobs_file, "r");
504   if (xml_file == NULL)
505   {
506     std::string error = "Error opening jobs_file in SALOME_Launcher::loadJobs: " + std::string(jobs_file);
507     INFOS(error);
508     THROW_SALOME_CORBA_EXCEPTION(error.c_str(), SALOME::INTERNAL_ERROR);
509   }
510
511   // Step 2: read xml file
512   xmlDocPtr doc = xmlReadFile(jobs_file, NULL, 0);
513   if (doc == NULL)
514   {
515     std::string error = "Error in xmlReadFile in SALOME_Launcher::loadJobs, could not parse file: " + std::string(jobs_file);
516     INFOS(error);
517     fclose(xml_file);
518     THROW_SALOME_CORBA_EXCEPTION(error.c_str(), SALOME::INTERNAL_ERROR);
519   }
520
521   // Step 3: Find jobs
522   xmlNodePtr root_node = xmlDocGetRootElement(doc);
523   xmlNodePtr xmlCurrentNode = root_node->xmlChildrenNode;
524   if (!xmlStrcmp(root_node->name, xmlCharStrdup("jobs")))
525   {
526     while(xmlCurrentNode != NULL)
527     {
528       if (!xmlStrcmp(xmlCurrentNode->name, xmlCharStrdup("job")))
529       {
530         INFOS("A job is found");
531         Launcher::Job * new_job; // It is Launcher_cpp that is going to destroy it
532         xmlNodePtr job_node = xmlCurrentNode;
533
534         // Begin Job
535         if (!xmlHasProp(job_node, xmlCharStrdup("type"))  ||
536             !xmlHasProp(job_node, xmlCharStrdup("name")))
537         {
538           INFOS("A bad job is found, type or name not found");
539           break;
540         }
541         xmlChar* type = xmlGetProp(job_node, xmlCharStrdup("type"));
542         xmlChar* name = xmlGetProp(job_node, xmlCharStrdup("name"));
543         std::string job_type((const char*) type);
544         if (job_type == "command")
545           new_job = new Launcher::Job_Command();
546         else if (job_type == "yacs_file")
547           new_job = new Launcher::Job_YACSFile();
548         else if (job_type == "python_salome")
549           new_job = new Launcher::Job_PythonSALOME();
550         new_job->setJobName(std::string((const char *)name));
551         xmlFree(type);
552         xmlFree(name);
553
554         xmlNodePtr user_node = xmlFirstElementChild(job_node);
555         xmlNodePtr run_node = xmlNextElementSibling(user_node);
556         if (user_node == NULL || run_node == NULL)
557         {
558           INFOS("A bad job is found, user_part or run_part not found");
559           delete new_job;
560           break;
561         }
562         if (xmlStrcmp(user_node->name, xmlCharStrdup("user_part")) ||
563             xmlStrcmp(run_node->name, xmlCharStrdup("run_part")))
564         {
565           INFOS("A bad job is found, cannot get a correct user_part or run_part node");
566           delete new_job;
567           break;
568         }
569
570         // Add user part
571
572         // Get job_file env_file work_directory local_directory result_directory
573         xmlNodePtr job_file_node         = xmlFirstElementChild(user_node);
574         xmlNodePtr env_file_node         = xmlNextElementSibling(job_file_node);
575         xmlNodePtr work_directory_node   = xmlNextElementSibling(env_file_node);
576         xmlNodePtr local_directory_node  = xmlNextElementSibling(work_directory_node);
577         xmlNodePtr result_directory_node = xmlNextElementSibling(local_directory_node);
578         if (job_file_node         == NULL ||
579             env_file_node         == NULL ||
580             work_directory_node   == NULL ||
581             local_directory_node  == NULL ||
582             result_directory_node == NULL
583            )
584         {
585           INFOS("A bad job is found, some user_part are not found");
586           delete new_job;
587           break;
588         }
589         if (xmlStrcmp(job_file_node->name,         xmlCharStrdup("job_file"))         ||
590             xmlStrcmp(env_file_node->name,         xmlCharStrdup("env_file"))         ||
591             xmlStrcmp(work_directory_node->name,   xmlCharStrdup("work_directory"))   ||
592             xmlStrcmp(local_directory_node->name,  xmlCharStrdup("local_directory"))  ||
593             xmlStrcmp(result_directory_node->name, xmlCharStrdup("result_directory"))
594            )
595         {
596           INFOS("A bad job is found, some user part node are not in the rigth or does not have a correct name");
597           delete new_job;
598           break;
599         }
600         xmlChar* job_file         = xmlNodeGetContent(job_file_node);
601         try
602         {
603           new_job->setJobFile(std::string((const char *)job_file));
604         }
605         catch(const LauncherException &ex)
606         {
607           INFOS("Exception receice for job_file, cannot add the job" << ex.msg.c_str());
608           delete new_job;
609           xmlFree(job_file);
610           break;
611         }
612         xmlChar* env_file         = xmlNodeGetContent(env_file_node);
613         xmlChar* work_directory   = xmlNodeGetContent(work_directory_node);
614         xmlChar* local_directory  = xmlNodeGetContent(local_directory_node);
615         xmlChar* result_directory = xmlNodeGetContent(result_directory_node);
616         new_job->setEnvFile(std::string((const char *)env_file));
617         new_job->setWorkDirectory(std::string((const char *)work_directory));
618         new_job->setLocalDirectory(std::string((const char *)local_directory));
619         new_job->setResultDirectory(std::string((const char *)result_directory));
620         xmlFree(job_file);
621         xmlFree(env_file);
622         xmlFree(work_directory);
623         xmlFree(local_directory);
624         xmlFree(result_directory);
625
626         // Get in and out files
627         xmlNodePtr files_node = xmlNextElementSibling(result_directory_node);
628         if (files_node == NULL)
629         {
630           INFOS("A bad job is found, user_part files is not found");
631           delete new_job;
632           break;
633         }
634         if (xmlStrcmp(files_node->name, xmlCharStrdup("files")))
635         {
636           INFOS("A bad job is found, files node are not in the rigth place or does not have a correct name or does not exist");
637           delete new_job;
638           break;
639         }
640         xmlNodePtr file_node = xmlFirstElementChild(files_node);
641         while (file_node != NULL)
642         {
643           if (!xmlStrcmp(file_node->name, xmlCharStrdup("in_file")))
644           {
645             xmlChar* in_file = xmlNodeGetContent(file_node);
646             new_job->add_in_file(std::string((const char *)in_file));
647             xmlFree(in_file);
648           }
649           else if (!xmlStrcmp(file_node->name, xmlCharStrdup("out_file")))
650           {
651             xmlChar* out_file = xmlNodeGetContent(file_node);
652             new_job->add_out_file(std::string((const char *)out_file));
653             xmlFree(out_file);
654           }
655           file_node = xmlNextElementSibling(file_node);
656         }
657
658         // Get resource part
659         xmlNodePtr res_node = xmlNextElementSibling(files_node);
660         xmlNodePtr maximum_duration_node = xmlNextElementSibling(res_node);
661         xmlNodePtr queue_node = xmlNextElementSibling(maximum_duration_node);
662         if (res_node              == NULL ||
663             maximum_duration_node == NULL ||
664             queue_node            == NULL
665            )
666         {
667           INFOS("A bad job is found, some user_part are not found");
668           delete new_job;
669           break;
670         }
671         if (xmlStrcmp(res_node->name,              xmlCharStrdup("resource_params"))  ||
672             xmlStrcmp(maximum_duration_node->name, xmlCharStrdup("maximum_duration")) ||
673             xmlStrcmp(queue_node->name,            xmlCharStrdup("queue"))
674            )
675         {
676           INFOS("A bad job is found, some user part node are not in the rigth or does not have a correct name");
677           delete new_job;
678           break;
679         }
680         xmlChar* maximum_duration = xmlNodeGetContent(maximum_duration_node);
681         try
682         {
683           new_job->setMaximumDuration(std::string((const char *)maximum_duration));
684         }
685         catch(const LauncherException &ex)
686         {
687           INFOS("Exception receice for maximum_duration, cannot add the job" << ex.msg.c_str());
688           delete new_job;
689           xmlFree(maximum_duration);
690           break;
691         }
692         xmlChar* queue            = xmlNodeGetContent(queue_node);
693         new_job->setQueue(std::string((const char *)queue));
694         xmlFree(maximum_duration);
695         xmlFree(queue);
696
697         xmlNodePtr specific_node = xmlNextElementSibling(queue_node);
698         if (specific_node == NULL)
699         {
700           INFOS("A bad job is found, specific_parameters part is not found");
701           delete new_job;
702           break;
703         }
704         xmlNodePtr parameter_node = xmlFirstElementChild(specific_node);
705         while (parameter_node != NULL)
706         {
707           if (!xmlStrcmp(parameter_node->name, xmlCharStrdup("specific_parameter")))
708           {
709             xmlNodePtr name_node = xmlFirstElementChild(parameter_node);
710             xmlNodePtr value_node = xmlNextElementSibling(name_node);
711             if (name_node == NULL ||
712                 value_node == NULL)
713             {
714               INFOS("A bad job is found, specific_parameter parts are not found");
715               delete new_job;
716               break;
717             }
718             if (xmlStrcmp(name_node->name, xmlCharStrdup("name")) ||
719                 xmlStrcmp(value_node->name, xmlCharStrdup("value")))
720             {
721               INFOS("A bad job is found, specific_parameter bad parts are found");
722               delete new_job;
723               break;
724             }
725
726             xmlChar* name  = xmlNodeGetContent(name_node);
727             xmlChar* value = xmlNodeGetContent(value_node);
728             try
729             {
730               new_job->addSpecificParameter(std::string((const char*)name), std::string((const char*)value));
731               xmlFree(name);
732               xmlFree(value);
733             }
734             catch(const LauncherException &ex)
735             {
736               INFOS("Exception receice for a specific parameter, cannot add the job" << ex.msg.c_str());
737               delete new_job;
738               xmlFree(name);
739               xmlFree(value);
740               break;
741             }
742           }
743           else
744           {
745             INFOS("A bad job is found, specific_parameters part is bad, a node that is not a specific parameter is found");
746             delete new_job;
747             break;
748           }
749           parameter_node = xmlNextElementSibling(parameter_node);
750         }
751
752         xmlNodePtr res_name_node             = xmlFirstElementChild(res_node);
753         xmlNodePtr res_hostname_node         = xmlNextElementSibling(res_name_node);
754         xmlNodePtr res_os_node               = xmlNextElementSibling(res_hostname_node);
755         xmlNodePtr res_nb_proc_node          = xmlNextElementSibling(res_os_node);
756         xmlNodePtr res_nb_node_node          = xmlNextElementSibling(res_nb_proc_node);
757         xmlNodePtr res_nb_proc_per_node_node = xmlNextElementSibling(res_nb_node_node);
758         xmlNodePtr res_cpu_clock_node        = xmlNextElementSibling(res_nb_proc_per_node_node);
759         xmlNodePtr res_mem_mb_node           = xmlNextElementSibling(res_cpu_clock_node);
760         if (res_name_node             == NULL ||
761             res_hostname_node         == NULL ||
762             res_os_node               == NULL ||
763             res_nb_proc_node          == NULL ||
764             res_nb_node_node          == NULL ||
765             res_nb_proc_per_node_node == NULL ||
766             res_cpu_clock_node        == NULL ||
767             res_mem_mb_node           == NULL
768            )
769         {
770           INFOS("A bad job is found, some resource_params user_part are not found");
771           delete new_job;
772           break;
773         }
774         if (xmlStrcmp(res_name_node->name,             xmlCharStrdup("name"))             ||
775             xmlStrcmp(res_hostname_node->name,         xmlCharStrdup("hostname"))         ||
776             xmlStrcmp(res_os_node->name,               xmlCharStrdup("OS"))               ||
777             xmlStrcmp(res_nb_proc_node->name,          xmlCharStrdup("nb_proc"))          ||
778             xmlStrcmp(res_nb_node_node->name,          xmlCharStrdup("nb_node"))          ||
779             xmlStrcmp(res_nb_proc_per_node_node->name, xmlCharStrdup("nb_proc_per_node")) ||
780             xmlStrcmp(res_cpu_clock_node->name,        xmlCharStrdup("cpu_clock"))        ||
781             xmlStrcmp(res_mem_mb_node->name,           xmlCharStrdup("mem_mb"))
782            )
783         {
784           INFOS("A bad job is found, some resource_params user_part node are not in the rigth or does not have a correct name");
785           delete new_job;
786           break;
787         }
788         xmlChar* res_name     = xmlNodeGetContent(res_name_node);
789         xmlChar* res_hostname = xmlNodeGetContent(res_hostname_node);
790         xmlChar* res_os       = xmlNodeGetContent(res_os_node);
791         resourceParams p;
792         p.name     = std::string((const char*) res_name);
793         p.hostname = std::string((const char*) res_hostname);
794         p.OS       = std::string((const char*) res_os);
795         xmlFree(res_name);
796         xmlFree(res_hostname);
797         xmlFree(res_os);
798         xmlChar* res_nb_proc          = xmlNodeGetContent(res_nb_proc_node);
799         xmlChar* res_nb_node          = xmlNodeGetContent(res_nb_node_node);
800         xmlChar* res_nb_proc_per_node = xmlNodeGetContent(res_nb_proc_per_node_node);
801         xmlChar* res_cpu_clock        = xmlNodeGetContent(res_cpu_clock_node);
802         xmlChar* res_mem_mb           = xmlNodeGetContent(res_mem_mb_node);
803         bool import_value = true;
804         std::istringstream nb_proc_stream((const char *) res_nb_proc);
805         if (!(nb_proc_stream >> p.nb_proc))
806           import_value = false;
807         std::istringstream nb_node_stream((const char *) res_nb_node);
808         if (!(nb_node_stream >> p.nb_node))
809           import_value = false;
810         std::istringstream nb_proc_per_node_stream((const char *) res_nb_proc_per_node);
811         if (!(nb_proc_per_node_stream >> p.nb_proc_per_node))
812           import_value = false;
813         std::istringstream cpu_clock_stream((const char *) res_cpu_clock);
814         if (!(cpu_clock_stream >> p.cpu_clock))
815           import_value = false;
816         std::istringstream mem_mb_stream((const char *) res_mem_mb);
817         if (!(mem_mb_stream >> p.mem_mb))
818           import_value = false;
819         xmlFree(res_nb_proc);
820         xmlFree(res_nb_node);
821         xmlFree(res_nb_proc_per_node);
822         xmlFree(res_cpu_clock);
823         xmlFree(res_mem_mb);
824         if (!import_value)
825         {
826           INFOS("A bad job is found, some resource_params value are not correct");
827           delete new_job;
828           break;
829         }
830         try
831         {
832           new_job->setResourceRequiredParams(p);
833         }
834         catch(const LauncherException &ex)
835         {
836           INFOS("A bad job is found, an error when inserting resource_params:" << ex.msg.c_str());
837           delete new_job;
838           break;
839         }
840
841         // We finally get run part to figure out what to do
842         xmlNodePtr job_state_node             = xmlFirstElementChild(run_node);
843         xmlNodePtr resource_choosed_name_node = xmlNextElementSibling(job_state_node);
844         xmlNodePtr job_reference_node         = xmlNextElementSibling(resource_choosed_name_node);
845         if (job_state_node             == NULL ||
846             resource_choosed_name_node == NULL ||
847             job_reference_node         == NULL
848            )
849         {
850           INFOS("A bad job is found, some run_part are not found");
851           delete new_job;
852           break;
853         }
854         if (xmlStrcmp(job_state_node->name,             xmlCharStrdup("job_state"))             ||
855             xmlStrcmp(resource_choosed_name_node->name, xmlCharStrdup("resource_choosed_name")) ||
856             xmlStrcmp(job_reference_node->name,         xmlCharStrdup("job_reference"))
857            )
858         {
859           INFOS("A bad job is found, some run_part nodes are not in the rigth or does not have a correct name");
860           delete new_job;
861           break;
862         }
863         xmlChar* job_state_xml             = xmlNodeGetContent(job_state_node);
864         xmlChar* resource_choosed_name_xml = xmlNodeGetContent(resource_choosed_name_node);
865         xmlChar* job_reference_xml         = xmlNodeGetContent(job_reference_node);
866         std::string job_state((const char *) job_state_xml);
867         std::string resource_choosed_name((const char *) resource_choosed_name_xml);
868         std::string job_reference((const char *) job_reference_xml);
869         xmlFree(job_state_xml);
870         xmlFree(resource_choosed_name_xml);
871         xmlFree(job_reference_xml);
872
873         if (job_state == "CREATED")
874         {
875           // In this case, we ignore run_part informations
876           try
877           {
878             _l.createJob(new_job);
879             std::ostringstream job_id;
880             job_id << new_job->getNumber();
881             notifyObservers("NEW_JOB", job_id.str());
882           }
883           catch(const LauncherException &ex)
884           {
885             INFOS("Load failed: " << ex.msg.c_str());
886           }
887         }
888         else if (job_state == "QUEUED"     ||
889                  job_state == "RUNNING"    ||
890                  job_state == "IN_PROCESS" ||
891                  job_state == "PAUSED")
892         {
893           try
894           {
895             new_job->setState(job_state);
896             _l.addJobDirectlyToMap(new_job, job_reference);
897
898             // Step 4: We check that the BatchManager could resume
899             // the job
900 #ifdef WITH_LIBBATCH
901             if (new_job->getBatchManagerJobId().getReference() != job_reference)
902             {
903               INFOS("BatchManager type cannot resume a job - job state is set to ERROR");
904               new_job->setState("ERROR");
905             }
906 #endif
907             std::ostringstream job_id;
908             job_id << new_job->getNumber();
909             notifyObservers("NEW_JOB", job_id.str());
910           }
911           catch(const LauncherException &ex)
912           {
913             INFOS("Cannot load the job! Exception: " << ex.msg.c_str());
914             delete new_job;
915           }
916         }
917         else if (job_state == "FINISHED" ||
918                  job_state == "FAILED"   ||
919                  job_state == "ERROR")
920         {
921           try
922           {
923             // Step 2: We add run_part informations
924             new_job->setState(job_state);
925             _l.addJobDirectlyToMap(new_job, job_reference);
926             std::ostringstream job_id;
927             job_id << new_job->getNumber();
928             notifyObservers("NEW_JOB", job_id.str());
929           }
930           catch(const LauncherException &ex)
931           {
932             INFOS("Cannot load the job! Exception: " << ex.msg.c_str());
933             delete new_job;
934           }
935         }
936         else
937         {
938           INFOS("A bad job is found, state unknown " << job_state);
939           delete new_job;
940         }
941
942       }
943       xmlCurrentNode = xmlCurrentNode->next;
944     }
945   }
946   else
947   {
948     xmlFreeDoc(doc);
949     fclose(xml_file);
950     std::string error = "Error in xml file, could not find root_node named jobs: " + std::string(jobs_file);
951     INFOS(error);
952     THROW_SALOME_CORBA_EXCEPTION(error.c_str(), SALOME::INTERNAL_ERROR);
953   }
954
955   // Clean
956   xmlFreeDoc(doc);
957   fclose(xml_file);
958   notifyObservers("LOAD_JOBS", jobs_file);
959 }
960
961 //=============================================================================
962 /*! CORBA Method:
963  *  Save jobs of Launcher (in any steps) in file jobs_file
964  */
965 //=============================================================================
966 void
967 SALOME_Launcher::saveJobs(const char* jobs_file)
968 {
969
970   // Step 1: check jobs_file write access
971   FILE* xml_file = fopen(jobs_file, "w");
972   if (xml_file == NULL)
973   {
974     std::string error = "Error opening jobs_file in SALOME_Launcher::saveJobs: " + std::string(jobs_file);
975     INFOS(error);
976     THROW_SALOME_CORBA_EXCEPTION(error.c_str(), SALOME::INTERNAL_ERROR);
977   }
978
979   // Step 2: First lines
980   xmlKeepBlanksDefault(0);
981   xmlDocPtr doc = xmlNewDoc(xmlCharStrdup("1.0"));
982   xmlNodePtr root_node = xmlNewNode(NULL, xmlCharStrdup("jobs"));
983   xmlDocSetRootElement(doc, root_node);
984   xmlNodePtr doc_comment = xmlNewDocComment(doc, xmlCharStrdup("SALOME Launcher save jobs file"));
985   xmlAddPrevSibling(root_node, doc_comment);
986
987   // Step 3: For each job write it on the xml document
988   // We could put a mutex but are not foing to do that currently
989   std::map<int, Launcher::Job *> jobs_list = _l.getJobs();
990   std::map<int, Launcher::Job *>::const_iterator it_job;
991   for(it_job = jobs_list.begin(); it_job != jobs_list.end(); it_job++)
992   {
993     it_job->second->addToXmlDocument(root_node);
994   }
995
996   // Final step: write file
997   int isOk = xmlSaveFormatFile(jobs_file, doc, 1);
998   if (!isOk)
999   {
1000     std::string error = "Error during xml file saving in SALOME_Launcher::saveJobs: " + std::string(jobs_file);
1001     INFOS(error);
1002     xmlFreeDoc(doc);
1003     fclose(xml_file);
1004     THROW_SALOME_CORBA_EXCEPTION(error.c_str(), SALOME::INTERNAL_ERROR);
1005   }
1006
1007   // Clean
1008   xmlFreeDoc(doc);
1009   fclose(xml_file);
1010   MESSAGE("SALOME_Launcher::saveJobs : WRITING DONE!");
1011   notifyObservers("SAVE_JOBS", jobs_file);
1012 }
1013
1014 //=============================================================================
1015 /*! CORBA Method:
1016  *  Add a new observer to the launcher
1017  */
1018 //=============================================================================
1019 void
1020 SALOME_Launcher::addObserver(Engines::SalomeLauncherObserver_ptr observer)
1021 {
1022   bool new_observer = true;
1023   std::list<Engines::SalomeLauncherObserver_var>::iterator iter = _observers.begin();
1024   while(iter != _observers.end())
1025   {
1026     if (std::string(_orb->object_to_string(*iter)) ==
1027         std::string(_orb->object_to_string(observer)))
1028     {
1029       new_observer = false;
1030       break;
1031     }
1032     iter++;
1033   }
1034   if (new_observer)
1035     _observers.push_back(Engines::SalomeLauncherObserver::_duplicate(observer));
1036
1037   // We notify the new observer with all jobs that are currently in the Launcher
1038   std::map<int, Launcher::Job *> cpp_jobs = _l.getJobs();
1039   std::map<int, Launcher::Job *>::const_iterator it_job;
1040   for(it_job = cpp_jobs.begin(); it_job != cpp_jobs.end(); it_job++)
1041   {
1042     int number = it_job->first;
1043     std::ostringstream job_id;
1044     job_id << number;
1045     try
1046     {
1047       observer->notify("NEW_JOB", job_id.str().c_str());
1048     }
1049     catch (...) 
1050     {
1051        MESSAGE("Notify Observer, exception catch");
1052     }
1053
1054   }
1055 }
1056
1057 //=============================================================================
1058 /*! CORBA Method:
1059  *  Add a new observer to the launcher
1060  */
1061 //=============================================================================
1062 void
1063 SALOME_Launcher::removeObserver(Engines::SalomeLauncherObserver_ptr observer)
1064 {
1065   std::list<Engines::SalomeLauncherObserver_var>::iterator iter = _observers.begin();
1066   while(iter != _observers.end())
1067   {
1068     if (std::string(_orb->object_to_string(*iter)) ==
1069         std::string(_orb->object_to_string(observer)))
1070     {
1071       // Observer found
1072       iter =_observers.erase(iter++);
1073     }
1074     else
1075     {
1076       iter++;
1077     }
1078   }
1079 }
1080
1081 //=============================================================================
1082 /*! Internal Method:
1083  *  Notify observers on a new event
1084  */
1085 //=============================================================================
1086 void
1087 SALOME_Launcher::notifyObservers(const std::string & event_name,
1088                                  const std::string & event_data)
1089 {
1090   std::list<Engines::SalomeLauncherObserver_var>::iterator iter = _observers.begin();
1091   while(iter != _observers.end())
1092   {
1093     try
1094     {
1095       (*iter)->notify(CORBA::string_dup(event_name.c_str()),
1096                       CORBA::string_dup(event_data.c_str()));
1097     }
1098     catch (...) 
1099     {
1100        MESSAGE("Notify Observer, exception catch");
1101     }
1102     iter++;
1103   }
1104
1105 }