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