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