Salome HOME
Update copyrights
[modules/smesh.git] / src / Tools / padder / meshjob / impl / MeshJobManager_i.cxx
1 // Copyright (C) 2011-2019  EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 // Authors : Guillaume Boulant (EDF) - 01/03/2011
21
22 #ifdef WIN32
23 #include <winsock2.h>
24 #include <windows.h> 
25 #else
26 #include <sys/time.h>
27 #endif
28
29 #include "MeshJobManager_i.hxx"
30
31 #include <SALOMEconfig.h>
32 #include CORBA_SERVER_HEADER(SALOME_Exception)
33
34
35 #include "Basics_Utils.hxx"         // For standard logging
36 #undef LOG
37 #include "SALOME_KernelServices.hxx"   // For CORBA logging
38 #undef LOG
39
40 #define LOG STDLOG
41
42 //
43 // ====================================================================
44 // General purpose helper functions (to put elsewhere at least)
45 // ====================================================================
46 //
47
48 /*!
49  * This function must be used to associate a datetime tag to a job
50  */
51
52 #ifndef WIN32
53 static long timetag() {
54   timeval tv;
55   gettimeofday(&tv,0);
56   long tag = tv.tv_usec + tv.tv_sec*1000000;
57   return tag;
58 }
59 #endif
60
61 /*!
62  * This function returns true if the string text starts with the string
63  * token.
64  */
65 static bool myStartsWith(const std::string& text,const std::string& token){     
66   if(text.length() < token.length())
67     return false;
68   return (text.compare(0, token.length(), token) == 0);
69 }
70
71 /*!
72  * This function returns true if the file exists on the local file
73  * system.
74  */
75 #include <iostream>
76 #include <fstream>
77 static bool fexists(const char *filename)
78 {
79   std::ifstream ifile(filename);
80   if ((bool)ifile && ifile.good()) {
81     return true;
82   }
83   return false;
84 }
85
86 //
87 // ====================================================================
88 // Constructor/Destructor
89 // ====================================================================
90 //
91 MeshJobManager_i::MeshJobManager_i(CORBA::ORB_ptr orb,
92                                    PortableServer::POA_ptr poa,
93                                    PortableServer::ObjectId * contId,
94                                    const char *instanceName,
95                                    const char *interfaceName)
96   : Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
97 {
98   LOG("Activating MESHJOB::MeshJobManager object");
99   _thisObj = this ;
100   _id = _poa->activate_object(_thisObj);
101
102   _salomeLauncher   = KERNEL::getSalomeLauncher();
103   if(CORBA::is_nil(_salomeLauncher)){
104     LOG("The SALOME launcher can't be reached ==> STOP");
105     throw KERNEL::createSalomeException("SALOME launcher can't be reached");
106   }
107
108   _resourcesManager = KERNEL::getResourcesManager();
109   if(CORBA::is_nil(_resourcesManager)){
110     LOG("The SALOME resource manager can't be reached ==> STOP");
111     throw KERNEL::createSalomeException("The SALOME resource manager can't be reached");
112   }
113
114   _lastErrorMessage = "";
115 }
116
117 MeshJobManager_i::~MeshJobManager_i() {
118   LOG("MeshJobManager_i::~MeshJobManager_i()");
119 }
120
121 //
122 // ====================================================================
123 // Helper functions to deals with the local and remote file systems
124 // ====================================================================
125 //
126 #include <fstream>     // to get the file streams
127 #ifdef WIN32
128 #include <stdlib.h>    // to get _splitpath
129 #include <direct.h>    // to get _mkdir
130 #else
131 #include <unistd.h>    // to get basename
132 #include <libgen.h>    // to get basename - as per posix
133 #include <sys/stat.h>  // to get mkdir
134 #include <sys/types.h> // to get mkdir options
135 #endif
136
137 #include <stdlib.h>    // to get system and getenv
138
139 static std::string OUTPUTFILE("output.med");
140 static std::string DATAFILE("data.txt");
141 static std::string SCRIPTFILE("padder.sh");
142 static std::string SEPARATOR(" ");
143
144 #ifdef WIN32
145 static std::string USER(getenv("USERNAME"));
146 #else
147 static std::string USER(getenv("USER"));
148 #endif
149
150 static std::string LOCAL_INPUTDIR("/tmp/spadder.local.inputdir."+USER);
151 static std::string LOCAL_RESULTDIR("/tmp/spadder.local.resultdir."+USER);
152 static std::string REMOTE_WORKDIR("/tmp/spadder.remote.workdir."+USER);
153
154 /*!
155  * This function creates the padder text input file containing the
156  * input data (list of filenames and groupnames) and returns the path
157  * of the created file. This function is the one that knows the format
158  * of the padder input file. If the input file format changes, then
159  * this function (and only this one) should be updated. The file
160  * format is the following ([] means that the variable is optional):
161  *
162  * [<concreteMeshFile>   <concreteGroupName>]
163  * nbSteelBarMeshes <N>
164  * <steelBarMeshFile_1>   <steelBarGroupName_1>
165  * <steelBarMeshFile_2>   <steelBarGroupName_2>
166  * ...
167  * <steelBarMeshFile_N>   <steelBarGroupName_N>
168  * <outputMedFile>
169  */
170 const char * MeshJobManager_i::_writeDataFile(std::vector<MESHJOB::MeshJobFile> listConcreteMesh,
171                                               std::vector<MESHJOB::MeshJobFile> listSteelBarMesh,
172                                               const MESHJOB::MeshJobParameterList & meshJobParameterList) {
173 #ifdef WIN32
174   _mkdir(LOCAL_INPUTDIR.c_str());
175 #else
176   mkdir(LOCAL_INPUTDIR.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
177 #endif
178
179   // Make it static so that it's allocated once (constant name)
180   static std::string * dataFilename = new std::string(LOCAL_INPUTDIR+"/"+DATAFILE);
181   std::ofstream dataFile(dataFilename->c_str());
182
183   // Note that we use here the basename of the files because the files
184   // are supposed to be copied in the REMOTE_WORKDIR for execution.
185   std::string line;
186
187   // We first specify the concrete mesh data (filename and groupname)
188   if ( listConcreteMesh.size() > 0 ) {
189 #ifdef WIN32
190     char fname[ _MAX_FNAME ];
191     _splitpath( listConcreteMesh[0].file_name, NULL, NULL, fname, NULL );
192     char* bname = &fname[0];
193 #else
194     char* bname = basename(listConcreteMesh[0].file_name);
195 #endif
196     line = std::string(bname) + " " + std::string(listConcreteMesh[0].group_name);
197     dataFile << line.c_str() << std::endl;
198   }
199   // Then, we can specify the steelbar mesh data, starting by the
200   // number of meshes
201   int nbSteelBarMeshes=listSteelBarMesh.size();
202   line = std::string("nbSteelBarMeshes") + SEPARATOR + ToString(nbSteelBarMeshes);
203   dataFile << line.c_str() << std::endl;
204   for (int i=0; i<nbSteelBarMeshes; i++) {
205 #ifdef WIN32
206         char fname[ _MAX_FNAME ];
207         _splitpath( listSteelBarMesh[i].file_name, NULL, NULL, fname, NULL );
208         char* bname = &fname[0];
209 #else
210         char* bname = basename(listSteelBarMesh[i].file_name);
211 #endif
212     line = std::string(bname) + " " + std::string(listSteelBarMesh[i].group_name);
213     dataFile << line.c_str() << std::endl;
214   }
215   
216   // We conclude the list of files with the name of the output file
217   line = OUTPUTFILE;
218   dataFile << line.c_str() << std::endl;
219
220   // We put the numerical parameters at the end of the data file
221   for(CORBA::ULong i=0; i<meshJobParameterList.length(); i++) {
222     MESHJOB::MeshJobParameter param = meshJobParameterList[i];
223     line = std::string(param.name) + " " + std::string(param.value);
224     dataFile << line.c_str() << std::endl;
225   }
226
227   dataFile.close();
228   return dataFilename->c_str();  
229 }
230
231 /*!
232  * This function creates a shell script that runs padder with the
233  * specified data file, and returns the path of the created script
234  * file. The config id is used to retrieve the path to the binary file
235  * and other required files.
236  */
237 const char* MeshJobManager_i::_writeScriptFile(const char * dataFileName, const char * configId) {
238 #ifdef WIN32
239   _mkdir(LOCAL_INPUTDIR.c_str());
240 #else
241   mkdir(LOCAL_INPUTDIR.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
242 #endif
243
244   // Make it static so that it's allocated once (constant name)
245   static std::string * scriptFilename = new std::string(LOCAL_INPUTDIR+"/"+SCRIPTFILE);
246
247   char * binpath = _configMap[configId].binpath;
248   char * envpath = _configMap[configId].envpath;
249
250 #ifdef WIN32
251         char fname[ _MAX_FNAME ];
252         _splitpath( dataFileName, NULL, NULL, fname, NULL );
253         const char* bname = &fname[0];
254 #else
255         const char* bname = basename(const_cast<char *>(dataFileName));
256 #endif
257
258
259   std::ofstream script(scriptFilename->c_str());
260   script << "#!/bin/sh"                                   << std::endl;
261   script << "here=$(dirname $0)"                          << std::endl;
262   script << ". " << envpath                               << std::endl;
263   script << binpath << " $here/" << bname                 << std::endl;
264   // Note that we use the basename of the datafile because all data
265   // files are supposed to have been copied in the REMOTE_WORKDIR.
266   script.close();
267   return scriptFilename->c_str();
268 }
269
270 //
271 // ====================================================================
272 // Functions to initialize and supervise the mesh computation job
273 // ====================================================================
274 //
275 bool MeshJobManager_i::configure(const char *configId,
276                                  const MESHJOB::ConfigParameter & configParameter)
277 {
278   beginService("MeshJobManager_i::configure");
279   
280   _configMap[configId] = configParameter;
281
282   LOG("Adding configuration for " << configId);
283   LOG("- binpath = " << _configMap[configId].binpath);
284   LOG("- envpath = " << _configMap[configId].envpath);
285
286   endService("MeshJobManager_i::configure");
287   return true;
288 }
289
290 long MeshJobManager_i::JOBID_UNDEFINED = -1;
291
292 /*! Initialize a smesh computation job and return the job identifier */
293 CORBA::Long MeshJobManager_i::initialize(const MESHJOB::MeshJobFileList & meshJobFileList,
294                                          const MESHJOB::MeshJobParameterList & meshJobParameterList,
295                                          const char * configId)
296 {
297   beginService("MeshJobManager_i::initialize");
298   //
299   // We first analyse the CORBA sequence to store data in C++ vectors
300   //
301   std::vector<MESHJOB::MeshJobFile> listConcreteMesh;
302   std::vector<MESHJOB::MeshJobFile> listSteelBarMesh;
303   for(CORBA::ULong i=0; i<meshJobFileList.length(); i++) {
304     MESHJOB::MeshJobFile currentMesh = meshJobFileList[i];
305     switch ( currentMesh.file_type ) {
306     case MESHJOB::MED_CONCRETE:
307       listConcreteMesh.push_back(currentMesh);
308       break;
309     case MESHJOB::MED_STEELBAR:
310       listSteelBarMesh.push_back(currentMesh);
311       break;
312     default:
313       _lastErrorMessage =
314         std::string("The type of the file ")+
315         std::string(currentMesh.file_name)+
316         std::string(" is not recognized");
317       LOG(_lastErrorMessage);
318       return JOBID_UNDEFINED;
319     }
320   }
321   
322   // It is not possible to specify more than one concrete
323   // file. Converselly, it is possible to specify no concrete file.
324   if ( listConcreteMesh.size() > 1 ) {
325     // Not consistent with the specification
326     _lastErrorMessage = std::string("You specify more than one concrete mesh (not authorized)");
327     LOG(_lastErrorMessage);
328     return JOBID_UNDEFINED;
329   }
330   
331   LOG("Nb. concrete mesh = " << listConcreteMesh.size());
332   LOG("Nb. steelbar mesh = " << listSteelBarMesh.size());
333
334   // We initiate here a datetime to tag the files and folder
335   // associated to this job.
336 #ifdef WIN32
337   DWORD jobDatetimeTag = timeGetTime();
338 #else
339   long jobDatetimeTag = timetag();
340 #endif
341   // And a MESHJOB::MeshJobPaths structure to hold the directories
342   // where to find data
343   MESHJOB::MeshJobPaths * jobPaths = new MESHJOB::MeshJobPaths();
344   jobPaths->local_inputdir  = LOCAL_INPUTDIR.c_str();
345   jobPaths->local_resultdir = (LOCAL_RESULTDIR + "." + ToString(jobDatetimeTag)).c_str();
346   jobPaths->remote_workdir  = (REMOTE_WORKDIR + "." + ToString(jobDatetimeTag)).c_str();  
347
348   //
349   // Then, we have to create the padder input data file. This input
350   // data is a text file containing the list of file names and group
351   // names.
352   //
353   const char * dataFilename = this->_writeDataFile(listConcreteMesh, listSteelBarMesh, meshJobParameterList);
354   LOG("dataFilename = " << dataFilename);
355   const char * scriptFilename = this->_writeScriptFile(dataFilename, configId);
356   LOG("scriptFilename = " << scriptFilename);
357
358   //
359   // Then, the following instructions consists in preparing the job
360   // parameters to request the SALOME launcher for creating a new
361   // job.
362   //
363   Engines::JobParameters_var jobParameters = new Engines::JobParameters;
364   jobParameters->job_type = CORBA::string_dup("command");
365   // CAUTION: the job_file must be a single filename specifying a
366   // self-consistent script to be executed without any argument on the
367   // remote host.
368   jobParameters->job_file = CORBA::string_dup(scriptFilename);
369
370   //
371   // Specification of the working spaces:
372   //
373   // - local_directory: can be used to specify where to find the input
374   //   files on the local resource. It's optional if you specify the
375   //   absolute path name of input files.
376   //
377   // - result_directory: must be used to specify where to download the
378   //   output files on the local resources
379   //
380   // - work_directory: must be used to specify the remote directory
381   //   where to put all the stuff to run the job. Note that the job
382   //   will be executed from within this directory, i.e. a change
383   //   directory toward this working directory is done by the batch
384   //   system before running the specified job script.
385   //
386   jobParameters->local_directory  = CORBA::string_dup("");
387   jobParameters->result_directory = CORBA::string_dup(jobPaths->local_resultdir);
388   jobParameters->work_directory   = CORBA::string_dup(jobPaths->remote_workdir);
389
390   // We specify the input files that are required to execute the
391   // job_file. If basenames are specified, then the files are supposed
392   // to be located in local_directory.
393   int nbcmesh = listConcreteMesh.size();
394   int nbsmesh = listSteelBarMesh.size();
395   int nbFiles = nbsmesh+nbcmesh+1;
396   // The number of input file is: 
397   //   (nb. of steelbar meshfile)
398   // + (1 or 0 concrete meshfile)
399   // + (1 padder input file)
400   jobParameters->in_files.length(nbFiles);
401   for (int i=0; i<nbcmesh; i++) {
402     jobParameters->in_files[i] = CORBA::string_dup(listConcreteMesh[i].file_name);
403   }
404   for (int i=0; i<nbsmesh; i++) {
405     jobParameters->in_files[nbcmesh+i] = CORBA::string_dup(listSteelBarMesh[i].file_name);
406   }
407   jobParameters->in_files[nbcmesh+nbsmesh] = CORBA::string_dup(dataFilename);
408   // Note that all these input files will be copied in the
409   // REMOTE_WORKDIR on the remote host. At this step, they should
410   // all exist, so we can check their presence on the local
411   // filesystem.
412   for (int i=0; i<nbFiles; i++) {
413     if ( fexists(jobParameters->in_files[i]) != true ) {
414       _lastErrorMessage = std::string("The input file ") + std::string(jobParameters->in_files[i]);
415       _lastErrorMessage+= std::string(" does not exists. Can't initialize the job");
416       LOG(_lastErrorMessage);
417       return JOBID_UNDEFINED;      
418     }
419   }
420
421   // Then, we have to specify the existence of an output filename. The
422   // path is supposed to be a path on the remote resource, i.e. where
423   // the job is executed.
424   jobParameters->out_files.length(1);
425   std::string outputfile_name = std::string(jobPaths->remote_workdir)+"/"+OUTPUTFILE;
426   jobParameters->out_files[0] = CORBA::string_dup(outputfile_name.c_str());
427
428   // CAUTION: the maximum duration has to be set with a format like "hh:mm"
429   //jobParameters->maximum_duration = CORBA::string_dup("01:00");
430   jobParameters->queue = CORBA::string_dup("");
431
432   // Setting resource and additional properties (if needed)
433   // The resource parameters can be initiated from scratch, for
434   // example by specifying the values in hard coding:
435   // >>>
436   //jobParameters->resource_required.name = CORBA::string_dup("localhost");
437   //jobParameters->resource_required.hostname = CORBA::string_dup("localhost");
438   //jobParameters->resource_required.mem_mb = 1024 * 10;
439   //jobParameters->resource_required.nb_proc = 1;
440   // <<<
441   // But it's better to initiate these parameters from a resource
442   // definition known by the resource manager. This ensures that the
443   // resource will be available:
444   //const char * resourceName = "localhost";
445   //const char * resourceName = "boulant@claui2p1";
446   //const char * resourceName = "nepal@nepal";
447   const char * resourceName = _configMap[configId].resname;
448   
449   Engines::ResourceDefinition * resourceDefinition;
450   try {
451     resourceDefinition = _resourcesManager->GetResourceDefinition(resourceName);
452   }
453   catch (const CORBA::SystemException& ex) {
454     _lastErrorMessage = std::string("We can not access the resource ") + std::string(resourceName);
455     _lastErrorMessage+= std::string("(check the file CatalogResource.xml)");
456     LOG(_lastErrorMessage);
457     return JOBID_UNDEFINED;
458   }
459   // CAUTION: This resource should have been defined in the
460   // CatalogResource.xml associated to the SALOME application.
461   //
462   // Then, the values can be used to initiate the resource parameters
463   // of the job:
464   jobParameters->resource_required.name     = CORBA::string_dup(resourceDefinition->name.in());
465   // CAUTION: the additional two following parameters MUST be
466   // specified explicitly, because they are not provided by the
467   // resource definition:
468   jobParameters->resource_required.mem_mb   = resourceDefinition->mem_mb;
469   jobParameters->resource_required.nb_proc  = resourceDefinition->nb_proc_per_node;
470   // CAUTION: the parameter mem_mb specifies the maximum memory value
471   // that could be allocated for executing the job. This takes into
472   // account not only the data that could be loaded by the batch
473   // process but also the linked dynamic library.
474   //
475   // A possible problem, for example in the case where you use the ssh
476   // emulation of a batch system, is to get an error message as below
477   // when libBatch try to run the ssh command:
478   //
479   // ## /usr/bin/ssh: error while loading shared libraries: libcrypto.so.0.9.8: failed
480   // ## to map segment from shared object: Cannot allocate memory
481   //
482   // In this example, the mem_mb was set to 1MB, value that is not
483   // sufficient to load the dynamic libraries linked to the ssh
484   // executable (libcrypto.so in the error message).
485   //
486   // So, even in the case of a simple test shell script, you should
487   // set this value at least to a standard threshold as 500MB
488   int jobId = JOBID_UNDEFINED;
489   try {
490     jobId = _salomeLauncher->createJob(jobParameters);
491     // We register the datetime tag of this job
492     _jobDateTimeMap[jobId]=jobDatetimeTag;
493     _jobPathsMap[jobId] = jobPaths;
494   }
495   catch (const SALOME::SALOME_Exception & ex) {
496     LOG("SALOME Exception at initialization step !" <<ex.details.text.in());
497     _lastErrorMessage = ex.details.text.in();
498     return JOBID_UNDEFINED;
499   }
500   catch (const CORBA::SystemException& ex) {
501     LOG("Receive SALOME System Exception: "<<ex);
502     LOG("Check SALOME servers...");
503     _lastErrorMessage = "Check the SALOME servers (or try to restart SALOME)";
504     return JOBID_UNDEFINED;
505   }
506   
507   endService("MeshJobManager_i::initialize");
508   return jobId;
509 }
510
511 /*! Submit the job execution and return true if submission is OK */
512 bool MeshJobManager_i::start(CORBA::Long jobId) {
513   beginService("MeshJobManager_i::start");
514
515   try {
516     _salomeLauncher->launchJob(jobId);
517   }
518   catch (const SALOME::SALOME_Exception & ex) {
519     LOG("SALOME Exception in launchjob !" <<ex.details.text.in());
520     _lastErrorMessage = ex.details.text.in();
521     return false;
522   }
523   catch (const CORBA::SystemException& ex) {
524     LOG("Receive SALOME System Exception: "<<ex);
525     LOG("Check SALOME servers...");
526     _lastErrorMessage = "Check the SALOME servers (or try to restart SALOME)";
527     return false;
528   }
529
530   endService("MeshJobManager_i::initialize");
531   return true;
532 }
533
534 /*! Request the launch manager for the state of the specified job */
535 char* MeshJobManager_i::getState(CORBA::Long jobId) {
536   beginService("MeshJobManager_i::getState");
537
538   std::string state;
539   try
540   {
541     state = _salomeLauncher->getJobState(jobId);
542   }
543   catch (const SALOME::SALOME_Exception & ex)
544   {
545     LOG("SALOME Exception in getJobState !");
546     _lastErrorMessage = ex.details.text.in();
547     state = ex.details.text;
548   }
549   catch (const CORBA::SystemException& ex)
550   {
551     LOG("Receive SALOME System Exception: " << ex);
552     state="SALOME System Exception - see logs";
553   }
554   LOG("jobId="<<ToString(jobId)<<" state="<<state);
555   endService("MeshJobManager_i::getState");
556   return CORBA::string_dup(state.c_str());
557 }
558
559 MESHJOB::MeshJobPaths * MeshJobManager_i::getPaths(CORBA::Long jobId) {
560
561   MESHJOB::MeshJobPaths * jobPaths = _jobPathsMap[jobId];
562   if ( jobPaths == NULL ) {
563     LOG("You request the working paths for an undefined job (jobId="<<ToString(jobId)<<")");
564     return NULL; // Maybe raise an exception?
565   }
566   return jobPaths;
567 }
568
569
570 MESHJOB::MeshJobResults * MeshJobManager_i::finalize(CORBA::Long jobId) {
571   beginService("MeshJobManager_i::getResults");
572   MESHJOB::MeshJobResults * result = new MESHJOB::MeshJobResults();
573
574   MESHJOB::MeshJobPaths * jobPaths = this->getPaths(jobId);
575   std::string local_resultdir(jobPaths->local_resultdir);
576   result->results_dirname = local_resultdir.c_str();  
577   try
578   {
579     _salomeLauncher->getJobResults(jobId, local_resultdir.c_str());
580  
581     // __BUG__: to prevent from a bug of the MED driver (SALOME
582     // 5.1.5), we change the basename of the output file to force the
583     // complete reloading of data by the med driver.
584     long jobDatetimeTag = _jobDateTimeMap[jobId];
585     std::string outputFileName = "output"+ToString(jobDatetimeTag)+".med";
586     rename((local_resultdir+"/"+OUTPUTFILE).c_str(), (local_resultdir+"/"+outputFileName).c_str());
587
588     result->outputmesh_filename = outputFileName.c_str();
589     
590     if ( fexists( (local_resultdir+"/"+outputFileName).c_str()  ) != true ) {
591       _lastErrorMessage = std::string("The result file ")+
592         std::string((local_resultdir+"/"+outputFileName).c_str())+
593         std::string(" has not been created.");
594       result->status = false;
595     }
596     else {
597       result->status = true;
598     }
599  }
600   catch (const SALOME::SALOME_Exception & ex)
601   {
602     _lastErrorMessage = ex.details.text.in();
603     LOG(_lastErrorMessage);
604     result->status = false;
605   }
606   catch (const CORBA::SystemException& ex)
607   {
608     _lastErrorMessage = "The SALOME launcher can not retrieve the result data";
609     LOG(_lastErrorMessage);
610     result->status = false;
611   }
612   endService("MeshJobManager_i::getResults");
613   return result;
614 }
615
616
617 /*! Clean all data associated to this job and remove the job from the launch manager */
618 bool MeshJobManager_i::clean(CORBA::Long jobId) {
619   beginService("MeshJobManager_i::clean");
620   
621   // __GBO__ WORK IN PROGRESS: we just clean the temporary local
622   // directories. The remote working directories are tag with the
623   // execution datetime and the we prevent the task from conflict
624   // with files of another task.
625   MESHJOB::MeshJobPaths * jobPaths = this->getPaths(jobId);
626   if ( jobPaths == NULL ) return false;
627
628   // WARN: !!!!!
629   // For safety reason (and prevent from bug that could erase the
630   // filesystem), we cancel the operation in the case where the
631   // directories to delete are not in the /tmp folder.
632   std::string shell_command("rm -rf ");
633   std::string inputdir(jobPaths->local_inputdir);
634   std::string resultdir(jobPaths->local_resultdir);
635   if ( !myStartsWith(inputdir,"/tmp/") )  {
636     LOG("WRN: The directory "<<inputdir<<" is not in /tmp. NO DELETE is done");
637   } else {
638     shell_command+=inputdir+" ";
639   }
640   if ( !myStartsWith(resultdir,"/tmp/"))  {
641     LOG("WRN: The directory "<<resultdir<<" is not in /tmp. NO DELETE is done");
642   } else {
643     shell_command+=resultdir;
644   }
645
646   LOG("DBG: clean shell command = "<<shell_command);
647
648   bool cleanOk = false;
649   int error = system(shell_command.c_str());
650   if (error == 0) cleanOk = true;
651
652   endService("MeshJobManager_i::clean");
653   return cleanOk;
654 }
655
656
657 std::vector<std::string> * MeshJobManager_i::_getResourceNames() {
658
659   //
660   // These part is just to control the available resources
661   //
662   Engines::ResourceParameters params;
663   KERNEL::getLifeCycleCORBA()->preSet(params);
664
665   Engines::ResourceList * resourceList = _resourcesManager->GetFittingResources(params);
666   Engines::ResourceDefinition * resourceDefinition = NULL;
667   LOG("### resource list:");
668   std::vector<std::string>* resourceNames = new std::vector<std::string>();
669   if (resourceList) {
670     for ( size_t i = 0; i < resourceList->length(); i++) {
671       const char* aResourceName = (*resourceList)[i];
672       resourceNames->push_back(std::string(aResourceName));
673       LOG("resource["<<i<<"] = "<<aResourceName);
674       resourceDefinition = _resourcesManager->GetResourceDefinition(aResourceName);
675       LOG("protocol["<<i<<"] = "<<resourceDefinition->protocol);
676     }
677   }
678
679   // Note: a ResourceDefinition is used to create a batch configuration
680   // in the Launcher. This operation is done at Launcher startup from
681   // the configuration file CatalogResources.xml provided by the
682   // SALOME application.
683   // In the code instructions, you just have to choose a resource
684   // configuration by its name and then define the ResourceParameters
685   // that specify additional properties for a specific job submission
686   // (use the attribute resource_required of the JobParameters).
687
688   return resourceNames;
689 }
690
691 char* MeshJobManager_i::getLastErrorMessage() {
692   beginService("MeshJobManager_i::getState");
693   endService("MeshJobManager_i::getState");
694   return CORBA::string_dup(_lastErrorMessage.c_str());
695 }
696
697 //
698 // ==========================================================================
699 // Factory services
700 // ==========================================================================
701 //
702 extern "C"
703 {
704   MESHJOBMANAGERENGINE_EXPORT
705   PortableServer::ObjectId * MeshJobManagerEngine_factory( CORBA::ORB_ptr orb,
706                                                            PortableServer::POA_ptr poa,
707                                                            PortableServer::ObjectId * contId,
708                                                            const char *instanceName,
709                                                            const char *interfaceName)
710   {
711     LOG("PortableServer::ObjectId * MeshJobManagerEngine_factory()");
712     MeshJobManager_i * myEngine = new MeshJobManager_i(orb, poa, contId, instanceName, interfaceName);
713     return myEngine->getId() ;
714   }
715 }