Salome HOME
Fixed time unit for parameter MAXWALLTIME in batch managers PBS and Local (minutes...
[tools/libbatch.git] / src / Local / Batch_BatchManager_Local.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 * BatchManager_Local.cxx :
24 *
25 * Auteur : Ivan DUTKA-MALEN - EDF R&D
26 * Mail   : mailto:ivan.dutka-malen@der.edf.fr
27 * Date   : Thu Nov  6 10:17:22 2003
28 * Projet : Salome 2
29 *
30 * Refactored by Renaud Barate (EDF R&D) in September 2009 to use
31 * CommunicationProtocol classes and merge Local_SH, Local_RSH and Local_SSH batch
32 * managers.
33 */
34
35 #include <iostream>
36 #include <fstream>
37 #include <sstream>
38 #include <cstdlib>
39 #include <limits.h>
40
41 #include <sys/types.h>
42 #ifdef WIN32
43 #include <direct.h>
44 #else
45 #include <sys/wait.h>
46 #include <unistd.h>
47 #endif
48 #include <ctime>
49 #include <pthread.h>
50 #include <signal.h>
51 #include <errno.h>
52 #include <string.h>
53 #include "Batch_IOMutex.hxx"
54 #include "Batch_BatchManager_Local.hxx"
55 #include "Batch_RunTimeException.hxx"
56
57 using namespace std;
58
59 namespace Batch {
60
61
62   // Constructeur
63   BatchManager_Local::BatchManager_Local(const FactBatchManager * parent, const char * host,
64                                          CommunicationProtocolType protocolType)
65     : BatchManager(parent, host), _connect(0),
66       _protocol(CommunicationProtocol::getInstance(protocolType)),
67       _idCounter(0)
68   {
69     pthread_mutex_init(&_threads_mutex, NULL);
70     pthread_cond_init(&_threadSyncCondition, NULL);
71   }
72
73   // Destructeur
74   BatchManager_Local::~BatchManager_Local()
75   {
76     for (map<Id, Child>::iterator iter = _threads.begin() ; iter != _threads.end() ; iter++) {
77       pthread_mutex_lock(&_threads_mutex);
78       string state = iter->second.param[STATE];
79       if (state != FINISHED && state != FAILED) {
80         UNDER_LOCK( cout << "Warning: Job " << iter->first <<
81                             " is not finished, it will now be canceled." << endl );
82         pthread_cancel(iter->second.thread_id);
83         pthread_cond_wait(&_threadSyncCondition, &_threads_mutex);
84       }
85       pthread_mutex_unlock(&_threads_mutex);
86     }
87     pthread_mutex_destroy(&_threads_mutex);
88     pthread_cond_destroy(&_threadSyncCondition);
89   }
90
91   const CommunicationProtocol & BatchManager_Local::getProtocol() const
92   {
93     return _protocol;
94   }
95
96   // Methode pour le controle des jobs : soumet un job au gestionnaire
97   const JobId BatchManager_Local::submitJob(const Job & job)
98   {
99     Job_Local jobLocal = job;
100     Id id = _idCounter++;
101     ThreadAdapter * p_ta = new ThreadAdapter(*this, job, id);
102
103     // Les attributs du thread a sa creation
104     pthread_attr_t thread_attr;
105     pthread_attr_init(&thread_attr);
106     pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
107
108     // Creation du thread qui va executer la commande systeme qu'on lui passe
109     pthread_t thread_id;
110     pthread_mutex_lock(&_threads_mutex);
111     int rc = pthread_create(&thread_id,
112       &thread_attr,
113       &ThreadAdapter::run,
114       static_cast<void *>(p_ta));
115
116     // Liberation des zones memoire maintenant inutiles occupees par les attributs du thread
117     pthread_attr_destroy(&thread_attr);
118
119     if (rc != 0) {
120       pthread_mutex_unlock(&_threads_mutex);
121       throw RunTimeException("Can't create new thread in BatchManager_Local");
122     }
123
124     pthread_cond_wait(&_threadSyncCondition, &_threads_mutex);
125     pthread_mutex_unlock(&_threads_mutex);
126
127     ostringstream id_sst;
128     id_sst << id;
129     return JobId(this, id_sst.str());
130   }
131
132   // Methode pour le controle des jobs : retire un job du gestionnaire
133   void BatchManager_Local::deleteJob(const JobId & jobid)
134   {
135     Id id;
136
137     istringstream iss(jobid.getReference());
138     iss >> id;
139
140     // On retrouve le thread_id du thread
141     pthread_t thread_id;
142
143     // @@@ --------> SECTION CRITIQUE <-------- @@@
144     pthread_mutex_lock(&_threads_mutex);
145     bool idFound = (_threads.find(id) != _threads.end());
146     if (idFound) {
147       string state = _threads[id].param[STATE];
148       if (state != FINISHED && state != FAILED) {
149         pthread_cancel(_threads[id].thread_id);
150         pthread_cond_wait(&_threadSyncCondition, &_threads_mutex);
151       } else {
152         cout << "Cannot delete job " << jobid.getReference() <<
153                 ". Job is already finished." << endl;
154       }
155     }
156     pthread_mutex_unlock(&_threads_mutex);
157     // @@@ --------> SECTION CRITIQUE <-------- @@@
158
159     if (!idFound)
160       throw RunTimeException(string("Job with id ") + jobid.getReference() + " does not exist");
161   }
162
163   // Methode pour le controle des jobs : suspend un job en file d'attente
164   void BatchManager_Local::holdJob(const JobId & jobid)
165   {
166     Id id;
167     istringstream iss(jobid.getReference());
168     iss >> id;
169
170     UNDER_LOCK( cout << "BatchManager is sending HOLD command to the thread " << id << endl );
171
172     // On introduit une commande dans la queue du thread
173     // @@@ --------> SECTION CRITIQUE <-------- @@@
174     pthread_mutex_lock(&_threads_mutex);
175     if (_threads.find(id) != _threads.end())
176       _threads[id].command_queue.push(HOLD);
177     pthread_mutex_unlock(&_threads_mutex);
178     // @@@ --------> SECTION CRITIQUE <-------- @@@
179   }
180
181   // Methode pour le controle des jobs : relache un job suspendu
182   void BatchManager_Local::releaseJob(const JobId & jobid)
183   {
184     Id id;
185     istringstream iss(jobid.getReference());
186     iss >> id;
187
188     UNDER_LOCK( cout << "BatchManager is sending RELEASE command to the thread " << id << endl );
189
190     // On introduit une commande dans la queue du thread
191     // @@@ --------> SECTION CRITIQUE <-------- @@@
192     pthread_mutex_lock(&_threads_mutex);
193     if (_threads.find(id) != _threads.end())
194       _threads[id].command_queue.push(RELEASE);
195     pthread_mutex_unlock(&_threads_mutex);
196     // @@@ --------> SECTION CRITIQUE <-------- @@@
197   }
198
199
200   // Methode pour le controle des jobs : modifie un job en file d'attente
201   void BatchManager_Local::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
202   {
203   }
204
205   // Methode pour le controle des jobs : modifie un job en file d'attente
206   void BatchManager_Local::alterJob(const JobId & jobid, const Parametre & param)
207   {
208     alterJob(jobid, param, Environnement());
209   }
210
211   // Methode pour le controle des jobs : modifie un job en file d'attente
212   void BatchManager_Local::alterJob(const JobId & jobid, const Environnement & env)
213   {
214     alterJob(jobid, Parametre(), env);
215   }
216
217
218
219   // Methode pour le controle des jobs : renvoie l'etat du job
220   JobInfo BatchManager_Local::queryJob(const JobId & jobid)
221   {
222     Id id;
223     istringstream iss(jobid.getReference());
224     iss >> id;
225
226     Parametre param;
227     Environnement env;
228
229     //UNDER_LOCK( cout << "JobInfo BatchManager_Local::queryJob(const JobId & jobid) : AVANT section critique" << endl );
230     // @@@ --------> SECTION CRITIQUE <-------- @@@
231     pthread_mutex_lock(&_threads_mutex);
232     std::map<Id, Child >::iterator pos = _threads.find(id);
233     bool found = (pos != _threads.end());
234     if (found) {
235       param = pos->second.param;
236       env   = pos->second.env;
237     }
238     pthread_mutex_unlock(&_threads_mutex);
239     // @@@ --------> SECTION CRITIQUE <-------- @@@
240     //UNDER_LOCK( cout << "JobInfo BatchManager_Local::queryJob(const JobId & jobid) : APRES section critique" << endl );
241
242     if (!found) throw InvalidArgumentException("Invalid JobId argument for queryJob");
243
244     JobInfo_Local ji(param, env);
245     return ji;
246   }
247
248
249
250   // Methode pour le controle des jobs : teste si un job est present en machine
251   bool BatchManager_Local::isRunning(const JobId & jobid)
252   {
253     Id id;
254     istringstream iss(jobid.getReference());
255     iss >> id;
256
257     //UNDER_LOCK( cout << "JobInfo BatchManager_Local::queryJob(const JobId & jobid) : AVANT section critique" << endl );
258     // @@@ --------> SECTION CRITIQUE <-------- @@@
259     pthread_mutex_lock(&_threads_mutex);
260     bool running = (_threads[id].param[STATE].str() == RUNNING);
261     pthread_mutex_unlock(&_threads_mutex);
262     // @@@ --------> SECTION CRITIQUE <-------- @@@
263     //UNDER_LOCK( cout << "JobInfo BatchManager_Local::queryJob(const JobId & jobid) : APRES section critique" << endl );
264
265     return running;
266   }
267
268
269   vector<string> BatchManager_Local::exec_command(const Parametre & param) const
270   {
271     ostringstream exec_sub_cmd;
272
273 #ifdef WIN32
274     char drive[_MAX_DRIVE];
275     _splitpath(string(param[WORKDIR]).c_str(), drive, NULL, NULL, NULL);
276     if (strlen(drive) > 0) exec_sub_cmd << drive << " && ";
277 #endif
278
279     exec_sub_cmd << "cd " << param[WORKDIR] << " && " << param[EXECUTABLE];
280
281     if (param.find(ARGUMENTS) != param.end()) {
282       Versatile V = param[ARGUMENTS];
283       for(Versatile::const_iterator it=V.begin(); it!=V.end(); it++) {
284         StringType argt = * static_cast<StringType *>(*it);
285         string     arg  = argt;
286         exec_sub_cmd << " " << arg;
287       }
288     }
289
290     if (param.find(INFILE) != param.end()) {
291       Versatile V = param[INFILE];
292       for(Versatile::const_iterator it=V.begin(); it!=V.end(); it++) {
293         Couple cpl = * static_cast<CoupleType*>(*it);
294         string remote = cpl.getRemote();
295         if (remote == "stdin")
296         exec_sub_cmd << " <stdin";
297       }
298     }
299
300     if (param.find(OUTFILE) != param.end()) {
301       Versatile V = param[OUTFILE];
302       for(Versatile::const_iterator it=V.begin(); it!=V.end(); it++) {
303         Couple cpl = * static_cast<CoupleType*>(*it);
304         string remote = cpl.getRemote();
305         if (remote == "stdout") exec_sub_cmd << " 1>stdout";
306         if (remote == "stderr") exec_sub_cmd << " 2>stderr";
307       }
308     }
309
310     string user;
311     Parametre::const_iterator it = param.find(USER);
312     if (it != param.end()) {
313       user = string(it->second);
314     }
315
316     return _protocol.getExecCommandArgs(exec_sub_cmd.str(), param[EXECUTIONHOST], user);
317   }
318
319
320
321   // Constructeur de la classe ThreadAdapter
322   BatchManager_Local::ThreadAdapter::ThreadAdapter(BatchManager_Local & bm, const Job_Local & job, Id id) :
323   _bm(bm), _job(job), _id(id)
324   {
325     // Nothing to do
326   }
327
328
329
330   // Methode d'execution du thread
331   void * BatchManager_Local::ThreadAdapter::run(void * arg)
332   {
333     ThreadAdapter * p_ta = static_cast<ThreadAdapter *>(arg);
334
335 #ifndef WIN32
336     // On bloque tous les signaux pour ce thread
337     sigset_t setmask;
338     sigfillset(&setmask);
339     pthread_sigmask(SIG_BLOCK, &setmask, NULL);
340 #endif
341
342     // On autorise la terminaison differee du thread
343     // (ces valeurs sont les valeurs par defaut mais on les force par precaution)
344     pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,  NULL);
345     pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
346
347     // On enregistre la fonction de suppression du fils en cas d'arret du thread
348     // Cette fontion sera automatiquement appelee lorsqu'une demande d'annulation
349     // sera prise en compte par pthread_testcancel()
350     Process child;
351     pthread_cleanup_push(BatchManager_Local::delete_on_exit, arg);
352     pthread_cleanup_push(BatchManager_Local::setFailedOnCancel, arg);
353     pthread_cleanup_push(BatchManager_Local::kill_child_on_exit, static_cast<void *> (&child));
354
355
356     // Le code retour cumule (ORed) de tous les appels
357     // Nul en cas de reussite de l'ensemble des operations
358     int rc = 0;
359
360     // Cette table contient la liste des fichiers a detruire a la fin du processus
361     std::vector<string> files_to_delete;
362
363
364
365     // On copie les fichiers d'entree pour le fils
366     const Parametre param   = p_ta->_job.getParametre();
367     Parametre::const_iterator it;
368
369     // On initialise la variable workdir a la valeur du Current Working Directory
370     char * cwd =
371 #ifdef WIN32
372       _getcwd(NULL, 0);
373 #else
374       new char [PATH_MAX];
375     getcwd(cwd, PATH_MAX);
376 #endif
377     string workdir = cwd;
378     delete [] cwd;
379
380     if ( (it = param.find(WORKDIR)) != param.end() ) {
381       workdir = static_cast<string>( (*it).second );
382     }
383
384     string executionhost = string(param[EXECUTIONHOST]);
385     string user;
386     if ( (it = param.find(USER)) != param.end() ) {
387       user = string(it->second);
388     }
389
390     if ( (it = param.find(INFILE)) != param.end() ) {
391       Versatile V = (*it).second;
392       Versatile::iterator Vit;
393
394       for(Vit=V.begin(); Vit!=V.end(); Vit++) {
395         CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
396         Couple cp       = cpt;
397         string local    = cp.getLocal();
398         string remote   = cp.getRemote();
399
400         std::cerr << workdir << std::endl;
401         std::cerr << remote << std::endl;
402
403         int status = p_ta->getBatchManager().getProtocol().copyFile(local, "", "",
404                                                                     workdir + "/" + remote,
405                                                                     executionhost, user);
406         if (status) {
407           // Echec de la copie
408           rc |= 1;
409         } else {
410           // On enregistre le fichier comme etant a detruire
411           files_to_delete.push_back(workdir + "/" + remote);
412         }
413
414       }
415     }
416
417
418
419
420     // On forke/exec un nouveau process pour pouvoir controler le fils
421     // (plus finement qu'avec un appel system)
422     // int rc = system(commande.c_str());
423     //char *const parmList[] = {"/usr/bin/ssh", "localhost", "-l", "aribes", "sleep 10 && echo end", NULL};
424     //execv("/usr/bin/ssh", parmList);
425 #ifdef WIN32
426     child = p_ta->launchWin32ChildProcess();
427     p_ta->pere(child);
428 #else
429     child = fork();
430     if (child < 0) { // erreur
431       UNDER_LOCK( cerr << "Fork impossible (rc=" << child << ")" << endl );
432
433     } else if (child > 0) { // pere
434       p_ta->pere(child);
435
436     } else { // fils
437       p_ta->fils();
438     }
439 #endif
440
441
442     // On copie les fichiers de sortie du fils
443     if ( (it = param.find(OUTFILE)) != param.end() ) {
444       Versatile V = (*it).second;
445       Versatile::iterator Vit;
446
447       for(Vit=V.begin(); Vit!=V.end(); Vit++) {
448         CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
449         Couple cp       = cpt;
450         string local    = cp.getLocal();
451         string remote   = cp.getRemote();
452
453         int status = p_ta->getBatchManager().getProtocol().copyFile(workdir + "/" + remote,
454                                                                     executionhost, user,
455                                                                     local, "", "");
456         if (status) {
457           // Echec de la copie
458           rc |= 1;
459         } else {
460           // On enregistre le fichier comme etant a detruire
461           files_to_delete.push_back(workdir + "/" + remote);
462         }
463
464       }
465     }
466
467     // On efface les fichiers d'entree et de sortie du fils si les copies precedentes ont reussi
468     // ou si la creation du fils n'a pu avoir lieu
469     if ( (rc == 0) || (child < 0) ) {
470       std::vector<string>::const_iterator it;
471       for(it=files_to_delete.begin(); it!=files_to_delete.end(); it++) {
472         p_ta->getBatchManager().getProtocol().removeFile(*it, executionhost, user);
473 /*        string remove_cmd = p_ta->getBatchManager().remove_command(user, executionhost, *it);
474         UNDER_LOCK( cout << "Removing : " << remove_cmd << endl );
475 #ifdef WIN32
476         remove_cmd = string("\"") + remove_cmd + string("\"");
477 #endif
478         system(remove_cmd.c_str());*/
479       }
480     }
481
482     pthread_mutex_lock(&p_ta->_bm._threads_mutex);
483
484     // Set the job state to FINISHED or FAILED
485     p_ta->_bm._threads[p_ta->_id].param[STATE] = (p_ta->_bm._threads[p_ta->_id].hasFailed) ? FAILED : FINISHED;
486
487     // On retire la fonction de nettoyage de la memoire
488     pthread_cleanup_pop(0);
489
490     // On retire la fonction de suppression du fils
491     pthread_cleanup_pop(0);
492
493     // remove setFailedOnCancel function from cancel stack
494     pthread_cleanup_pop(0);
495
496     pthread_mutex_unlock(&p_ta->_bm._threads_mutex);
497
498     // On invoque la fonction de nettoyage de la memoire
499     delete_on_exit(arg);
500
501     UNDER_LOCK( cout << "Father is leaving" << endl );
502     pthread_exit(NULL);
503     return NULL;
504   }
505
506
507
508
509   void BatchManager_Local::ThreadAdapter::pere(Process child)
510   {
511     time_t child_starttime = time(NULL);
512
513     // On enregistre le fils dans la table des threads
514     pthread_t thread_id = pthread_self();
515
516     Parametre param   = _job.getParametre();
517     Environnement env = _job.getEnvironnement();
518
519     ostringstream id_sst;
520     id_sst << _id;
521     param[ID]         = id_sst.str();
522     param[STATE]      = Batch::RUNNING;
523 #ifndef WIN32
524     param[PID]        = child;
525 #endif
526
527     _bm._threads[_id].thread_id = thread_id;
528 #ifndef WIN32
529     _bm._threads[_id].pid       = child;
530 #endif
531     _bm._threads[_id].hasFailed = false;
532     _bm._threads[_id].param     = param;
533     _bm._threads[_id].env       = env;
534     _bm._threads[_id].command_queue.push(NOP);
535
536     // Unlock the master thread. From here, all shared variables must be protected
537     // from concurrent access
538     pthread_cond_signal(&_bm._threadSyncCondition);
539
540
541     // on boucle en attendant que le fils ait termine
542     while (1) {
543 #ifdef WIN32
544       DWORD exitCode;
545       BOOL res = GetExitCodeProcess(child, &exitCode);
546       if (exitCode != STILL_ACTIVE) {
547         UNDER_LOCK( cout << "Father sees his child is DONE: exit code = " << exitCode << endl );
548         break;
549       }
550 #else
551       int child_rc = 0;
552       pid_t child_wait_rc = waitpid(child, &child_rc, WNOHANG /* | WUNTRACED */);
553       if (child_wait_rc > 0) {
554          UNDER_LOCK( cout << "Status is: " << WIFEXITED( child_rc) << endl);
555          UNDER_LOCK( cout << "Status is: " << WEXITSTATUS( child_rc) << endl);
556          UNDER_LOCK( cout << "Status is: " << WIFSIGNALED( child_rc) << endl);
557          UNDER_LOCK( cout << "Status is: " << WTERMSIG( child_rc) << endl);
558          UNDER_LOCK( cout << "Status is: " << WCOREDUMP( child_rc) << endl);
559          UNDER_LOCK( cout << "Status is: " << WIFSTOPPED( child_rc) << endl);
560          UNDER_LOCK( cout << "Status is: " << WSTOPSIG( child_rc) << endl);
561 #ifdef WIFCONTINUED
562          UNDER_LOCK( cout << "Status is: " << WIFCONTINUED( child_rc) << endl); // not compilable on sarge
563 #endif
564         if (WIFSTOPPED(child_rc)) {
565           // NOTA : pour rentrer dans cette section, il faut que le flag WUNTRACED
566           // soit positionne dans l'appel a waitpid ci-dessus. Ce flag est couramment
567           // desactive car s'il est possible de detecter l'arret d'un process, il est
568           // plus difficile de detecter sa reprise.
569
570           // Le fils est simplement stoppe
571           // @@@ --------> SECTION CRITIQUE <-------- @@@
572           pthread_mutex_lock(&_bm._threads_mutex);
573           _bm._threads[_id].param[STATE] = Batch::PAUSED;
574           pthread_mutex_unlock(&_bm._threads_mutex);
575           // @@@ --------> SECTION CRITIQUE <-------- @@@
576           UNDER_LOCK( cout << "Father sees his child is STOPPED : " << child_wait_rc << endl );
577
578         }
579         else {
580           // Le fils est termine, on sort de la boucle et du if englobant
581           UNDER_LOCK( cout << "Father sees his child is DONE : " << child_wait_rc << " (child_rc=" << (WIFEXITED(child_rc) ? WEXITSTATUS(child_rc) : -1) << ")" << endl );
582           break;
583         }
584       }
585       else if (child_wait_rc == -1) {
586         // Le fils a disparu ...
587         // @@@ --------> SECTION CRITIQUE <-------- @@@
588         pthread_mutex_lock(&_bm._threads_mutex);
589         _bm._threads[_id].hasFailed = true;
590         pthread_mutex_unlock(&_bm._threads_mutex);
591         // @@@ --------> SECTION CRITIQUE <-------- @@@
592         UNDER_LOCK( cout << "Father sees his child is DEAD : " << child_wait_rc << " (Reason : " << strerror(errno) << ")" << endl );
593         break;
594       }
595 #endif
596
597       // On teste si le thread doit etre detruit
598       pthread_testcancel();
599
600
601
602       // On regarde si le fils n'a pas depasse son temps (wallclock time)
603       time_t child_currenttime = time(NULL);
604       long child_elapsedtime_minutes = (child_currenttime - child_starttime) / 60L;
605       if (param.find(MAXWALLTIME) != param.end()) {
606         long maxwalltime = param[MAXWALLTIME];
607         //        cout << "child_starttime          = " << child_starttime        << endl
608         //             << "child_currenttime        = " << child_currenttime      << endl
609         //             << "child_elapsedtime        = " << child_elapsedtime      << endl
610         //             << "maxwalltime              = " << maxwalltime            << endl
611         //             << "int(maxwalltime * 1.1)   = " << int(maxwalltime * 1.1) << endl;
612         if (child_elapsedtime_minutes > long((float)maxwalltime * 1.1) ) { // On se donne 10% de marge avant le KILL
613           UNDER_LOCK( cout << "Father is sending KILL command to the thread " << _id << endl );
614           // On introduit une commande dans la queue du thread
615           // @@@ --------> SECTION CRITIQUE <-------- @@@
616           pthread_mutex_lock(&_bm._threads_mutex);
617           if (_bm._threads.find(_id) != _bm._threads.end())
618             _bm._threads[_id].command_queue.push(KILL);
619           pthread_mutex_unlock(&_bm._threads_mutex);
620           // @@@ --------> SECTION CRITIQUE <-------- @@@
621
622
623         } else if (child_elapsedtime_minutes > maxwalltime ) {
624           UNDER_LOCK( cout << "Father is sending TERM command to the thread " << _id << endl );
625           // On introduit une commande dans la queue du thread
626           // @@@ --------> SECTION CRITIQUE <-------- @@@
627           pthread_mutex_lock(&_bm._threads_mutex);
628           if (_bm._threads.find(_id) != _bm._threads.end())
629             _bm._threads[_id].command_queue.push(TERM);
630           pthread_mutex_unlock(&_bm._threads_mutex);
631           // @@@ --------> SECTION CRITIQUE <-------- @@@
632         }
633       }
634
635
636
637       // On regarde s'il y a quelque chose a faire dans la queue de commande
638       // @@@ --------> SECTION CRITIQUE <-------- @@@
639       pthread_mutex_lock(&_bm._threads_mutex);
640       if (_bm._threads.find(_id) != _bm._threads.end()) {
641         while (_bm._threads[_id].command_queue.size() > 0) {
642           Commande cmd = _bm._threads[_id].command_queue.front();
643           _bm._threads[_id].command_queue.pop();
644
645           switch (cmd) {
646     case NOP:
647       UNDER_LOCK( cout << "Father does nothing to his child" << endl );
648       break;
649 #ifndef WIN32
650     case HOLD:
651       UNDER_LOCK( cout << "Father is sending SIGSTOP signal to his child" << endl );
652       kill(child, SIGSTOP);
653       break;
654
655     case RELEASE:
656       UNDER_LOCK( cout << "Father is sending SIGCONT signal to his child" << endl );
657       kill(child, SIGCONT);
658       break;
659
660     case TERM:
661       UNDER_LOCK( cout << "Father is sending SIGTERM signal to his child" << endl );
662       kill(child, SIGTERM);
663       break;
664
665     case KILL:
666       UNDER_LOCK( cout << "Father is sending SIGKILL signal to his child" << endl );
667       kill(child, SIGKILL);
668       break;
669 #endif
670     case ALTER:
671       break;
672
673     default:
674       break;
675           }
676         }
677
678       }
679       pthread_mutex_unlock(&_bm._threads_mutex);
680       // @@@ --------> SECTION CRITIQUE <-------- @@@
681
682       // On fait une petite pause pour ne pas surcharger inutilement le processeur
683 #ifdef WIN32
684       Sleep(1000);
685 #else
686       sleep(1);
687 #endif
688
689     }
690
691   }
692
693
694
695 #ifndef WIN32
696
697   void BatchManager_Local::ThreadAdapter::fils()
698   {
699     Parametre param = _job.getParametre();
700     Parametre::iterator it;
701
702       //char *const parmList[] = {"/usr/bin/ssh", "localhost", "-l", "aribes", "sleep 1 && echo end", NULL};
703       //int result = execv("/usr/bin/ssh", parmList);
704       //UNDER_LOCK( cout << "*** debug_command = " << result << endl );
705       //UNDER_LOCK( cout << "*** debug_command = " << strerror(errno) << endl );
706     try {
707
708       // EXECUTABLE is MANDATORY, if missing, we exit with failure notification
709       vector<string> command;
710       if (param.find(EXECUTABLE) != param.end()) {
711         command = _bm.exec_command(param);
712       } else exit(1);
713
714       // Build the argument array argv from the command
715       char ** argv = new char * [command.size() + 1];
716       string comstr;
717       for (string::size_type i=0 ; i<command.size() ; i++) {
718         argv[i] = new char[command[i].size() + 1];
719         strncpy(argv[i], command[i].c_str(), command[i].size() + 1);
720         if (i>0) comstr += " # ";
721         comstr += command[i];
722       }
723
724       argv[command.size()] = NULL;
725
726       UNDER_LOCK( cout << "*** debug_command = " << comstr << endl );
727       UNDER_LOCK( cout << "*** debug_command = " << argv[0] << endl );
728
729       // Create the environment for the new process. Note (RB): Here we change the environment for
730       // the process launched in local. It would seem more logical to set the environment for the
731       // remote process.
732       Environnement env = _job.getEnvironnement();
733
734       char ** envp = NULL;
735       if(env.size() > 0) {
736         envp = new char * [env.size() + 1]; // 1 pour le NULL terminal
737         int i = 0;
738         for(Environnement::const_iterator it=env.begin(); it!=env.end(); it++, i++) {
739           const string  & key   = (*it).first;
740           const string  & value = (*it).second;
741           ostringstream oss;
742           oss << key << "=" << value;
743           envp[i]         = new char [oss.str().size() + 1];
744           strncpy(envp[i], oss.str().c_str(), oss.str().size() + 1);
745         }
746
747         // assert (i == env.size())
748         envp[i] = NULL;
749       }
750
751       //char *const parmList[] = {"/usr/bin/ssh", "localhost", "-l", "aribes", "sleep 1 && echo end", NULL};
752       //int result = execv("/usr/bin/ssh", parmList);
753       //UNDER_LOCK( cout << "*** debug_command = " << result << endl );
754       //UNDER_LOCK( cout << "*** debug_command = " << strerror(errno) << endl );
755
756
757
758       // On positionne les limites systeme imposees au fils
759       if (param.find(MAXCPUTIME) != param.end()) {
760         int maxcputime = param[MAXCPUTIME];
761         struct rlimit limit;
762         limit.rlim_cur = maxcputime;
763         limit.rlim_max = int(maxcputime * 1.1);
764         setrlimit(RLIMIT_CPU, &limit);
765       }
766
767       if (param.find(MAXDISKSIZE) != param.end()) {
768         int maxdisksize = param[MAXDISKSIZE];
769         struct rlimit limit;
770         limit.rlim_cur = maxdisksize * 1024;
771         limit.rlim_max = int(maxdisksize * 1.1) * 1024;
772         setrlimit(RLIMIT_FSIZE, &limit);
773       }
774
775       if (param.find(MAXRAMSIZE) != param.end()) {
776         int maxramsize = param[MAXRAMSIZE];
777         struct rlimit limit;
778         limit.rlim_cur = maxramsize * 1024 * 1024;
779         limit.rlim_max = int(maxramsize * 1.1) * 1024 * 1024;
780         setrlimit(RLIMIT_AS, &limit);
781       }
782
783
784       //char *const parmList[] = {"/usr/bin/ssh", "localhost", "-l", "aribes", "sleep 1 && echo end", NULL};
785       //int result = execv("/usr/bin/ssh", parmList);
786       //UNDER_LOCK( cout << "*** debug_command = " << result << endl );
787       //UNDER_LOCK( cout << "*** debug_command = " << strerror(errno) << endl );
788
789       // On cree une session pour le fils de facon a ce qu'il ne soit pas
790       // detruit lorsque le shell se termine (le shell ouvre une session et
791       // tue tous les process appartenant a la session en quittant)
792       setsid();
793
794
795       // On ferme les descripteurs de fichiers standards
796       //close(STDIN_FILENO);
797       //close(STDOUT_FILENO);
798       //close(STDERR_FILENO);
799
800
801       // On execute la commande du fils
802       int result = execve(argv[0], argv, envp);
803       UNDER_LOCK( cout << "*** debug_command = " << strerror(errno) << endl );
804       // No need to deallocate since nothing happens after a successful exec
805
806       // Normalement on ne devrait jamais arriver ici
807       ofstream file_err("error.log");
808       UNDER_LOCK( file_err << "Echec de l'appel a execve" << endl );
809
810     } catch (GenericException & e) {
811
812       std::cerr << "Caught exception : " << e.type << " : " << e.message << std::endl;
813     }
814
815     exit(99);
816   }
817
818 #else
819
820   BatchManager_Local::Process BatchManager_Local::ThreadAdapter::launchWin32ChildProcess()
821   {
822     Parametre param = _job.getParametre();
823     Parametre::iterator it;
824     PROCESS_INFORMATION pi;
825
826     try {
827
828       // EXECUTABLE is MANDATORY, if missing, we throw an exception
829       vector<string> exec_command;
830       if (param.find(EXECUTABLE) != param.end()) {
831         exec_command = _bm.exec_command(param);
832       } else {
833         throw RunTimeException("Parameter \"EXECUTABLE\" is mandatory for local batch submission");
834       }
835
836       // Build the command string from the command argument vector
837       string comstr;
838       for (unsigned int i=0 ; i<exec_command.size() ; i++) {
839         if (i>0) comstr += " ";
840         comstr += exec_command[i];
841       }
842
843       UNDER_LOCK( cout << "*** debug_command = " << comstr << endl );
844
845       // Create the environment for the new process. Note (RB): Here we change the environment for
846       // the process launched in local. It would seem more logical to set the environment for the
847       // remote process.
848       // Note that if no environment is specified, we reuse the current environment.
849       Environnement env = _job.getEnvironnement();
850       char * chNewEnv = NULL;
851
852       if(env.size() > 0) {
853         chNewEnv = new char[4096];
854         LPTSTR lpszCurrentVariable = chNewEnv;
855         for(Environnement::const_iterator it=env.begin() ; it!=env.end() ; it++) {
856           const string  & key   = (*it).first;
857           const string  & value = (*it).second;
858           string envvar = key + "=" + value;
859           envvar.copy(lpszCurrentVariable, envvar.size());
860           lpszCurrentVariable[envvar.size()] = '\0';
861           lpszCurrentVariable += lstrlen(lpszCurrentVariable) + 1;
862         }
863         // Terminate the block with a NULL byte.
864         *lpszCurrentVariable = '\0';
865       }
866
867
868       STARTUPINFO si;
869       ZeroMemory( &si, sizeof(si) );
870       si.cb = sizeof(si);
871       ZeroMemory( &pi, sizeof(pi) );
872
873       // Copy the command to a non-const buffer
874       char * buffer = strdup(comstr.c_str());
875
876       // launch the new process
877       BOOL res = CreateProcess(NULL, buffer, NULL, NULL, FALSE,
878                                CREATE_NO_WINDOW, chNewEnv, NULL, &si, &pi);
879
880       if (buffer) free(buffer);
881       if (!res) throw RunTimeException("Error while creating new process");
882
883       CloseHandle(pi.hThread);
884
885     } catch (GenericException & e) {
886
887       std::cerr << "Caught exception : " << e.type << " : " << e.message << std::endl;
888     }
889
890     return pi.hProcess;
891   }
892
893 #endif
894
895
896   void BatchManager_Local::kill_child_on_exit(void * p_pid)
897   {
898 #ifndef WIN32
899     //TODO: porting of following functionality
900     pid_t child = * static_cast<pid_t *>(p_pid);
901
902     // On tue le fils
903     kill(child, SIGTERM);
904
905     // Nota : on pourrait aussi faire a la suite un kill(child, SIGKILL)
906     // mais cette option n'est pas implementee pour le moment, car il est
907     // preferable de laisser le process fils se terminer normalement et seul.
908 #endif
909   }
910
911   void BatchManager_Local::delete_on_exit(void * arg)
912   {
913     ThreadAdapter * p_ta = static_cast<ThreadAdapter *>(arg);
914     delete p_ta;
915   }
916
917   void BatchManager_Local::setFailedOnCancel(void * arg)
918   {
919     ThreadAdapter * p_ta = static_cast<ThreadAdapter *>(arg);
920     pthread_mutex_lock(&p_ta->getBatchManager()._threads_mutex);
921     p_ta->getBatchManager()._threads[p_ta->getId()].param[STATE] = FAILED;
922     pthread_mutex_unlock(&p_ta->getBatchManager()._threads_mutex);
923
924     // Unlock the master thread. From here, the batch manager instance should not be used.
925     pthread_cond_signal(&p_ta->getBatchManager()._threadSyncCondition);
926   }
927
928 }