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