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