Salome HOME
Merge branch V7_3_1_BR
[modules/kernel.git] / src / Launcher / Launcher_Job.cxx
1 // Copyright (C) 2009-2014  CEA/DEN, EDF R&D, OPEN CASCADE
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 // Author: AndrĂ© RIBES - EDF R&D
21 //
22 #include "Launcher_Job.hxx"
23 #include "Launcher.hxx"
24
25 #ifdef WITH_LIBBATCH
26 #include <libbatch/Constants.hxx>
27 #endif
28
29 using namespace std;
30
31 Launcher::Job::Job()
32 {
33   _number = -1;
34   _state = "CREATED";
35   _launch_date = getLaunchDate();
36
37   _env_file = "";
38   _job_name = "";
39   _job_file = "";
40   _job_file_name = "";
41   _job_file_name_complete = "";
42   _work_directory = "";
43   _local_directory = "";
44   _result_directory = "";
45   _maximum_duration = "";
46   _maximum_duration_in_second = -1;
47   _resource_required_params.name = "";
48   _resource_required_params.hostname = "";
49   _resource_required_params.OS = "";
50   _resource_required_params.nb_proc = -1;
51   _resource_required_params.nb_node = -1;
52   _resource_required_params.nb_proc_per_node = -1;
53   _resource_required_params.cpu_clock = -1;
54   _resource_required_params.mem_mb = -1;
55   _queue = "";
56   _job_type = "";
57   _exclusive = false;
58   _mem_per_cpu = 0;
59
60   // Parameters for COORM
61   _launcher_file = "";
62   _launcher_args = "";
63
64 #ifdef WITH_LIBBATCH
65   _batch_job = new Batch::Job();
66 #endif
67 }
68
69 Launcher::Job::~Job() 
70 {
71   LAUNCHER_MESSAGE("Deleting job number: " << _number);
72 #ifdef WITH_LIBBATCH
73   if (_batch_job)
74     delete _batch_job;
75 #endif
76 }
77
78 void
79 Launcher::Job::stopJob()
80 {
81   LAUNCHER_MESSAGE("Stop resquested for job number: " << _number);
82   setState("FAILED");
83 #ifdef WITH_LIBBATCH
84   if (_batch_job_id.getReference() != "undefined")
85   {
86     try 
87     {
88       _batch_job_id.deleteJob();
89     }
90     catch (const Batch::GenericException &ex)
91     {
92       LAUNCHER_INFOS("WARNING: exception when stopping the job: " << ex.message);
93     }
94   }
95 #endif
96 }
97
98
99 void
100 Launcher::Job::removeJob()
101 {
102   LAUNCHER_MESSAGE("Removing job number: " << _number);
103 #ifdef WITH_LIBBATCH
104   if (_batch_job_id.getReference() != "undefined")
105   {
106     try 
107     {
108       _batch_job_id.deleteJob();
109     }
110     catch (const Batch::GenericException &ex)
111     {
112       LAUNCHER_INFOS("WARNING: exception when removing the job: " << ex.message);
113     }
114   }
115 #endif
116 }
117
118 std::string
119 Launcher::Job::getJobType() const
120 {
121   return _job_type;
122 }
123
124 void
125 Launcher::Job::setJobName(const std::string & job_name)
126 {
127   _job_name = job_name;
128 }
129
130 std::string
131 Launcher::Job::getJobName() const
132 {
133   return _job_name;
134 }
135
136 void 
137 Launcher::Job::setState(const std::string & state)
138 {
139   // State of a Job: CREATED, QUEUED, RUNNING, FINISHED, FAILED
140   if (state != "CREATED" &&
141       state != "IN_PROCESS" &&
142       state != "QUEUED" &&
143       state != "RUNNING" &&
144       state != "PAUSED" &&
145       state != "FINISHED" &&
146       state != "FAILED" &&
147       state != "ERROR")
148   {
149     throw LauncherException("Bad state, this state does not exist: " + state);
150   }
151   _state = state;
152 }
153
154 std::string 
155 Launcher::Job::getState() const
156 {
157   return _state;
158 }
159
160 // Get names or ids of hosts assigned to the job
161 std::string
162 Launcher::Job::getAssignedHostnames()
163 {
164   return _assigned_hostnames;
165 }
166
167 void 
168 Launcher::Job::setNumber(const int & number)
169 {
170   if (_number != -1)
171     std::cerr << "Launcher::Job::setNumber -- Job number was already defined, before: " << _number << " now: " << number << std::endl;
172   _number = number;
173 }
174
175 int
176 Launcher::Job::getNumber()
177 {
178   return _number;
179 }
180
181 void 
182 Launcher::Job::setResourceDefinition(const ParserResourcesType & resource_definition)
183 {
184   // Check machine_definition
185   std::string user_name = "";
186   if (resource_definition.UserName == "")
187   {
188     user_name = getenv("USER");
189     if (user_name == "")
190     {
191       std::string mess = "You must define a user name: into your resource description or with env variable USER";
192       throw LauncherException(mess);
193     }
194   }
195   else
196     user_name = resource_definition.UserName;
197
198   _resource_definition = resource_definition;
199   _resource_definition.UserName = user_name;
200 }
201
202 ParserResourcesType 
203 Launcher::Job::getResourceDefinition() const
204 {
205   return _resource_definition;
206 }
207
208 void 
209 Launcher::Job::setJobFile(const std::string & job_file)
210 {
211   // Check job file
212   if (job_file == "")
213   {
214     std::string mess = "Empty Job File is forbidden !";
215     throw LauncherException(mess);
216   }
217
218   _job_file = job_file;
219   std::string::size_type p1 = _job_file.find_last_of("/");
220   std::string::size_type p2 = _job_file.find_last_of(".");
221   _job_file_name_complete = _job_file.substr(p1+1);
222   _job_file_name = _job_file.substr(p1+1,p2-p1-1);
223 }
224
225 std::string
226 Launcher::Job::getJobFile() const
227 {
228   return _job_file;
229 }
230 void 
231 Launcher::Job::setEnvFile(const std::string & env_file)
232 {
233   _env_file = env_file;
234 }
235
236 std::string
237 Launcher::Job::getEnvFile() const
238 {
239   return _env_file;
240 }
241
242 void 
243 Launcher::Job::setWorkDirectory(const std::string & work_directory)
244 {
245   _work_directory = work_directory;
246 }
247
248 void 
249 Launcher::Job::setLocalDirectory(const std::string & local_directory)
250 {
251   _local_directory = local_directory;
252 }
253
254 void 
255 Launcher::Job::setResultDirectory(const std::string & result_directory)
256 {
257   _result_directory = result_directory;
258 }
259
260 void 
261 Launcher::Job::add_in_file(const std::string & file)
262 {
263   std::list<std::string>::iterator it = std::find(_in_files.begin(), _in_files.end(), file);
264   if (it == _in_files.end())
265     _in_files.push_back(file);
266   else
267     std::cerr << "Launcher::Job::add_in_file -- Warning file was already entered in in_files: " << file << std::endl;
268 }
269
270 void 
271 Launcher::Job::add_out_file(const std::string & file)
272 {
273   std::list<std::string>::iterator it = std::find(_out_files.begin(), _out_files.end(), file);
274   if (it == _out_files.end())
275     _out_files.push_back(file);
276   else
277     std::cerr << "Launcher::Job::add_out_file -- Warning file was already entered in out_files: " << file << std::endl;
278 }
279
280 void 
281 Launcher::Job::setMaximumDuration(const std::string & maximum_duration)
282 {
283   checkMaximumDuration(maximum_duration);
284   _maximum_duration_in_second = convertMaximumDuration(maximum_duration);
285   _maximum_duration = maximum_duration;
286 }
287
288 // For COORM
289 void
290 Launcher::Job::setLauncherFile(const std::string & launcher_file)
291 {
292         _launcher_file = launcher_file;
293 }
294 void
295 Launcher::Job::setLauncherArgs(const std::string & launcher_args)
296 {
297         _launcher_args = launcher_args;
298 }
299
300 void 
301 Launcher::Job::setResourceRequiredParams(const resourceParams & resource_required_params)
302 {
303   checkResourceRequiredParams(resource_required_params);
304   _resource_required_params = resource_required_params;
305 }
306
307 void 
308 Launcher::Job::setQueue(const std::string & queue)
309 {
310   _queue = queue;
311 }
312
313 void
314 Launcher::Job::setExclusive(bool exclusive)
315 {
316   _exclusive = exclusive;
317 }
318
319 void
320 Launcher::Job::setExclusiveStr(const std::string & exclusiveStr)
321 {
322   if (exclusiveStr == "true")
323     _exclusive = true;
324   else if (exclusiveStr == "false")
325     _exclusive = false;
326   else
327     throw LauncherException(std::string("Invalid boolean value for exclusive: ") + exclusiveStr);
328 }
329
330 void
331 Launcher::Job::setMemPerCpu(unsigned long mem_per_cpu)
332 {
333   _mem_per_cpu = mem_per_cpu;
334 }
335
336 void
337 Launcher::Job::setReference(const std::string & reference)
338 {
339   _reference = reference;
340 }
341
342 std::string 
343 Launcher::Job::getWorkDirectory() const
344 {
345   return _work_directory;
346 }
347
348 std::string 
349 Launcher::Job::getLocalDirectory() const
350 {
351   return _local_directory;
352 }
353
354 std::string
355 Launcher::Job::getResultDirectory() const
356 {
357   return _result_directory;
358 }
359
360 const std::list<std::string> & 
361 Launcher::Job::get_in_files() const
362 {
363   return _in_files;
364 }
365
366 const std::list<std::string> & 
367 Launcher::Job::get_out_files() const
368 {
369   return _out_files;
370 }
371
372 std::string 
373 Launcher::Job::getMaximumDuration() const
374 {
375   return _maximum_duration;
376 }
377
378 // For COORM
379 std::string
380 Launcher::Job::getLauncherFile() const
381 {
382         return _launcher_file;
383 }
384 std::string
385 Launcher::Job::getLauncherArgs() const
386 {
387         return _launcher_args;
388 }
389
390 resourceParams 
391 Launcher::Job::getResourceRequiredParams() const
392 {
393   return _resource_required_params;
394 }
395
396 std::string 
397 Launcher::Job::getQueue() const
398 {
399   return _queue;
400 }
401
402 bool
403 Launcher::Job::getExclusive() const
404 {
405   return _exclusive;
406 }
407
408 std::string
409 Launcher::Job::getExclusiveStr() const
410 {
411   return _exclusive ? "true" : "false";
412 }
413
414 unsigned long
415 Launcher::Job::getMemPerCpu() const
416 {
417   return _mem_per_cpu;
418 }
419
420 std::string
421 Launcher::Job::getReference() const
422 {
423   return _reference;
424 }
425
426 void 
427 Launcher::Job::checkMaximumDuration(const std::string & maximum_duration)
428 {
429   std::string result("");
430   std::string edt_value = maximum_duration;
431   std::size_t pos = edt_value.find(":");
432
433   if (edt_value != "") {
434     if (pos == edt_value.npos) {
435       throw LauncherException("[Launcher::Job::checkMaximumDuration] Error on definition: " + edt_value);
436     }
437     std::string begin_edt_value = edt_value.substr(0, pos);
438     std::string mid_edt_value = edt_value.substr(pos, 1);
439     std::string end_edt_value = edt_value.substr(pos + 1, edt_value.npos);
440   
441     long value;
442     std::istringstream iss(begin_edt_value);
443     if (!(iss >> value)) {
444       result = "[Launcher::Job::checkExpectedDuration] Error on definition ! : " + edt_value;
445     }
446     else if (value < 0) {
447       result = "[Launcher::Job::checkExpectedDuration] Error on definition time is negative ! : " + value;
448     }
449     std::istringstream iss_2(end_edt_value);
450     if (!(iss_2 >> value)) {
451       result = "[Launcher::Job::checkExpectedDuration] Error on definition ! : " + edt_value;
452     }
453     else if (value < 0) {
454       result = "[Launcher::Job::checkExpectedDuration] Error on definition time is negative ! : " + value;
455     }
456     if (mid_edt_value != ":") {
457       result = "[Launcher::Job::checkExpectedDuration] Error on definition ! :" + edt_value;
458     }
459   }
460   if (result != "")
461     throw LauncherException(result);
462 }
463
464 void 
465 Launcher::Job::checkResourceRequiredParams(const resourceParams & resource_required_params)
466 {
467   // nb_proc has be to > 0
468   if (resource_required_params.nb_proc <= 0)
469   {
470     std::string message("[Launcher::Job::checkResourceRequiredParams] proc number is not > 0 ! ");
471     throw LauncherException(message);
472   }
473 }
474
475 long 
476 Launcher::Job::convertMaximumDuration(const std::string & edt)
477 {
478   long hh, mm, ret;
479
480   if( edt.size() == 0 )
481     return -1;
482
483   std::string::size_type pos = edt.find(":");
484   std::string h = edt.substr(0,pos);
485   std::string m = edt.substr(pos+1,edt.size()-pos+1);
486   std::istringstream issh(h);
487   issh >> hh;
488   std::istringstream issm(m);
489   issm >> mm;
490   ret = hh*60 + mm;
491   ret = ret * 60;
492
493   return ret;
494 }
495
496 std::string 
497 Launcher::Job::getLaunchDate() const
498 {
499   time_t rawtime;
500   time(&rawtime);
501   std::string launch_date = ctime(&rawtime);
502   int i = 0 ;
503   for (;i < launch_date.size(); i++) 
504     if (launch_date[i] == '/' ||
505         launch_date[i] == '-' ||
506         launch_date[i] == ':' ||
507         launch_date[i] == ' ') 
508       launch_date[i] = '_';
509   launch_date.erase(--launch_date.end()); // Last caracter is a \n
510
511   return launch_date;
512 }
513
514 std::string
515 Launcher::Job::updateJobState()
516 {
517
518   if (_state != "FINISHED" &&
519       _state != "ERROR"    &&
520       _state != "FAILED")
521   {
522 #ifdef WITH_LIBBATCH
523     if (_batch_job_id.getReference() != "undefined")
524     {
525       // A batch manager has been affected to the job
526       Batch::JobInfo job_info = _batch_job_id.queryJob();
527       Batch::Parametre par = job_info.getParametre();
528       _state = par[Batch::STATE].str();
529       _assigned_hostnames = (par.find(Batch::ASSIGNEDHOSTNAMES) == par.end())?
530                             "" : par[Batch::ASSIGNEDHOSTNAMES].str();
531       LAUNCHER_MESSAGE("State received is: " << par[Batch::STATE].str());
532     }
533 #endif
534   }
535   return _state;
536 }
537
538 #ifdef WITH_LIBBATCH
539 Batch::Job * 
540 Launcher::Job::getBatchJob()
541 {
542   update_job();
543   return _batch_job;
544 }
545
546 Batch::Parametre
547 Launcher::Job::common_job_params()
548 {
549   Batch::Parametre params;
550
551   params[Batch::NAME] = getJobName();
552   params[Batch::NBPROC] = _resource_required_params.nb_proc;
553   params[Batch::NBPROCPERNODE] = _resource_required_params.nb_proc_per_node;
554
555   // Memory in megabytes
556   if (_resource_required_params.mem_mb > 0)
557   {
558     params[Batch::MAXRAMSIZE] = _resource_required_params.mem_mb;
559   }
560   else if (_mem_per_cpu > 0)
561   {
562     params[Batch::MEMPERCPU] = (long)_mem_per_cpu;
563   }
564
565   // We define a default directory based on user time
566   if (_work_directory == "")
567   {
568     const size_t BUFSIZE = 32;
569     char date[BUFSIZE];
570     time_t curtime = time(NULL);
571     strftime(date, BUFSIZE, "%Y_%m_%d__%H_%M_%S", localtime(&curtime));
572     _work_directory = std::string("$HOME/Batch/workdir_");
573     _work_directory += date;
574   }
575   params[Batch::WORKDIR] = _work_directory;
576
577   // Parameters for COORM
578   params[Batch::LAUNCHER_FILE] = _launcher_file;
579   params[Batch::LAUNCHER_ARGS] = _launcher_args;
580
581   // If result_directory is not defined, we use HOME environnement
582   if (_result_directory == "")
583     _result_directory = getenv("HOME");
584
585   // _in_files
586   std::list<std::string> in_files(_in_files);
587   in_files.push_back(_job_file);
588   if (_env_file != "")
589           in_files.push_back(_env_file);
590   for(std::list<std::string>::iterator it = in_files.begin(); it != in_files.end(); it++)
591   {
592     std::string file = *it;
593
594     // local file -> If file is not an absolute path, we apply _local_directory
595     std::string local_file;
596     if (file.substr(0, 1) == std::string("/"))
597       local_file = file;
598     else
599 #ifndef WIN32
600       local_file = _local_directory + "/" + file;
601 #else
602           local_file = file;
603 #endif
604     
605     // remote file -> get only file name from in_files
606     size_t found = file.find_last_of("/");
607     std::string remote_file = _work_directory + "/" + file.substr(found+1);
608
609     params[Batch::INFILE] += Batch::Couple(local_file, remote_file);
610   }
611    
612   // _out_files
613   for(std::list<std::string>::iterator it = _out_files.begin(); it != _out_files.end(); it++)
614   {
615     std::string file = *it;
616
617     // local file 
618     size_t found = file.find_last_of("/");
619     std::string local_file = _result_directory +  "/" + file.substr(found+1);
620
621     // remote file -> If file is not an absolute path, we apply _work_directory
622     std::string remote_file;
623     if (file.substr(0, 1) == std::string("/"))
624       remote_file = file;
625     else
626       remote_file = _work_directory + "/" + file;
627
628     params[Batch::OUTFILE] += Batch::Couple(local_file, remote_file);
629   }
630
631   // Time
632   if (_maximum_duration_in_second != -1)
633     params[Batch::MAXWALLTIME] = _maximum_duration_in_second / 60;
634
635   // Queue
636   if (_queue != "")
637     params[Batch::QUEUE] = _queue;
638
639   // Exclusive
640   if (getExclusive())
641     params[Batch::EXCLUSIVE] = true;
642
643   // Specific parameters
644   std::map<std::string, std::string>::iterator it = _specific_parameters.find("LoalLevelerJobType");
645   if (it != _specific_parameters.end())
646     params["LL_JOBTYPE"] = it->second;
647   return params;
648 }
649
650 void 
651 Launcher::Job::setBatchManagerJobId(Batch::JobId batch_manager_job_id)
652 {
653   _batch_job_id = batch_manager_job_id;
654 }
655
656 Batch::JobId 
657 Launcher::Job::getBatchManagerJobId() const
658 {
659   return _batch_job_id;
660 }
661 #endif
662
663 void 
664 Launcher::Job::addSpecificParameter(const std::string & name,
665                                       const std::string & value)
666 {
667   _specific_parameters[name] = value;
668 }
669
670 const std::map<std::string, std::string> &
671 Launcher::Job::getSpecificParameters() const
672 {
673   return _specific_parameters;
674 }
675
676 void
677 Launcher::Job::checkSpecificParameters()
678 {
679 }