1 // Copyright (C) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 * BatchManager_Local.cxx :
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
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
41 #include <sys/types.h>
53 #include "Batch_IOMutex.hxx"
54 #include "Batch_BatchManager_Local.hxx"
55 #include "Batch_RunTimeException.hxx"
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)),
69 pthread_mutex_init(&_threads_mutex, NULL);
70 pthread_cond_init(&_threadSyncCondition, NULL);
74 BatchManager_Local::~BatchManager_Local()
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);
85 pthread_mutex_unlock(&_threads_mutex);
87 pthread_mutex_destroy(&_threads_mutex);
88 pthread_cond_destroy(&_threadSyncCondition);
91 const CommunicationProtocol & BatchManager_Local::getProtocol() const
96 // Methode pour le controle des jobs : soumet un job au gestionnaire
97 const JobId BatchManager_Local::submitJob(const Job & job)
99 Job_Local jobLocal = job;
100 Id id = _idCounter++;
101 ThreadAdapter * p_ta = new ThreadAdapter(*this, job, id);
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);
108 // Creation du thread qui va executer la commande systeme qu'on lui passe
110 pthread_mutex_lock(&_threads_mutex);
111 int rc = pthread_create(&thread_id,
114 static_cast<void *>(p_ta));
116 // Liberation des zones memoire maintenant inutiles occupees par les attributs du thread
117 pthread_attr_destroy(&thread_attr);
120 pthread_mutex_unlock(&_threads_mutex);
121 throw RunTimeException("Can't create new thread in BatchManager_Local");
124 pthread_cond_wait(&_threadSyncCondition, &_threads_mutex);
125 pthread_mutex_unlock(&_threads_mutex);
127 ostringstream id_sst;
129 return JobId(this, id_sst.str());
132 // Methode pour le controle des jobs : retire un job du gestionnaire
133 void BatchManager_Local::deleteJob(const JobId & jobid)
137 istringstream iss(jobid.getReference());
140 // @@@ --------> SECTION CRITIQUE <-------- @@@
141 pthread_mutex_lock(&_threads_mutex);
142 bool idFound = (_threads.find(id) != _threads.end());
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);
149 cout << "Cannot delete job " << jobid.getReference() <<
150 ". Job is already finished." << endl;
153 pthread_mutex_unlock(&_threads_mutex);
154 // @@@ --------> SECTION CRITIQUE <-------- @@@
157 throw RunTimeException(string("Job with id ") + jobid.getReference() + " does not exist");
160 // Methode pour le controle des jobs : suspend un job en file d'attente
161 void BatchManager_Local::holdJob(const JobId & jobid)
164 istringstream iss(jobid.getReference());
167 UNDER_LOCK( cout << "BatchManager is sending HOLD command to the thread " << id << endl );
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 <-------- @@@
178 // Methode pour le controle des jobs : relache un job suspendu
179 void BatchManager_Local::releaseJob(const JobId & jobid)
182 istringstream iss(jobid.getReference());
185 UNDER_LOCK( cout << "BatchManager is sending RELEASE command to the thread " << id << endl );
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 <-------- @@@
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)
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)
205 alterJob(jobid, param, Environnement());
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)
211 alterJob(jobid, Parametre(), env);
216 // Methode pour le controle des jobs : renvoie l'etat du job
217 JobInfo BatchManager_Local::queryJob(const JobId & jobid)
220 istringstream iss(jobid.getReference());
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());
232 param = pos->second.param;
233 env = pos->second.env;
235 pthread_mutex_unlock(&_threads_mutex);
236 // @@@ --------> SECTION CRITIQUE <-------- @@@
237 //UNDER_LOCK( cout << "JobInfo BatchManager_Local::queryJob(const JobId & jobid) : APRES section critique" << endl );
239 if (!found) throw InvalidArgumentException("Invalid JobId argument for queryJob");
241 JobInfo_Local ji(param, env);
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
250 BatchManager_Local::addJob(const Batch::Job & job, const std::string reference)
252 return JobId(this, "undefined");
255 // Methode pour le controle des jobs : teste si un job est present en machine
256 bool BatchManager_Local::isRunning(const JobId & jobid)
259 istringstream iss(jobid.getReference());
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 );
274 vector<string> BatchManager_Local::exec_command(const Parametre & param) const
276 ostringstream exec_sub_cmd;
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 << " && ";
284 exec_sub_cmd << "cd " << param[WORKDIR] << " && " << param[EXECUTABLE];
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);
291 exec_sub_cmd << " " << arg;
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";
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";
316 Parametre::const_iterator it = param.find(USER);
317 if (it != param.end()) {
318 user = string(it->second);
321 return _protocol.getExecCommandArgs(exec_sub_cmd.str(), param[EXECUTIONHOST], user);
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)
335 // Methode d'execution du thread
336 void * BatchManager_Local::ThreadAdapter::run(void * arg)
338 ThreadAdapter * p_ta = static_cast<ThreadAdapter *>(arg);
341 // On bloque tous les signaux pour ce thread
343 sigfillset(&setmask);
344 pthread_sigmask(SIG_BLOCK, &setmask, NULL);
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);
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()
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));
361 // Le code retour cumule (ORed) de tous les appels
362 // Nul en cas de reussite de l'ensemble des operations
365 // Cette table contient la liste des fichiers a detruire a la fin du processus
366 std::vector<string> files_to_delete;
370 // On copie les fichiers d'entree pour le fils
371 const Parametre param = p_ta->_job.getParametre();
372 Parametre::const_iterator it;
374 // On initialise la variable workdir a la valeur du Current Working Directory
380 getcwd(cwd, PATH_MAX);
382 string workdir = cwd;
385 if ( (it = param.find(WORKDIR)) != param.end() ) {
386 workdir = static_cast<string>( (*it).second );
389 string executionhost = string(param[EXECUTIONHOST]);
391 if ( (it = param.find(USER)) != param.end() ) {
392 user = string(it->second);
395 if ( (it = param.find(INFILE)) != param.end() ) {
396 Versatile V = (*it).second;
397 Versatile::iterator Vit;
399 for(Vit=V.begin(); Vit!=V.end(); Vit++) {
400 CoupleType cpt = *static_cast< CoupleType * >(*Vit);
402 string local = cp.getLocal();
403 string remote = cp.getRemote();
405 std::cerr << workdir << std::endl;
406 std::cerr << remote << std::endl;
408 int status = p_ta->getBatchManager().getProtocol().copyFile(local, "", "",
409 workdir + "/" + remote,
410 executionhost, user);
415 // On enregistre le fichier comme etant a detruire
416 files_to_delete.push_back(workdir + "/" + remote);
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);
431 child = p_ta->launchWin32ChildProcess();
435 if (child < 0) { // erreur
436 UNDER_LOCK( cerr << "Fork impossible (rc=" << child << ")" << endl );
438 } else if (child > 0) { // pere
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;
452 for(Vit=V.begin(); Vit!=V.end(); Vit++) {
453 CoupleType cpt = *static_cast< CoupleType * >(*Vit);
455 string local = cp.getLocal();
456 string remote = cp.getRemote();
458 int status = p_ta->getBatchManager().getProtocol().copyFile(workdir + "/" + remote,
465 // On enregistre le fichier comme etant a detruire
466 files_to_delete.push_back(workdir + "/" + remote);
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 );
481 remove_cmd = string("\"") + remove_cmd + string("\"");
483 system(remove_cmd.c_str());*/
487 pthread_mutex_lock(&p_ta->_bm._threads_mutex);
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;
492 // On retire la fonction de nettoyage de la memoire
493 pthread_cleanup_pop(0);
495 // On retire la fonction de suppression du fils
496 pthread_cleanup_pop(0);
498 // remove setFailedOnCancel function from cancel stack
499 pthread_cleanup_pop(0);
501 pthread_mutex_unlock(&p_ta->_bm._threads_mutex);
503 // On invoque la fonction de nettoyage de la memoire
506 UNDER_LOCK( cout << "Father is leaving" << endl );
514 void BatchManager_Local::ThreadAdapter::pere(Process child)
516 time_t child_starttime = time(NULL);
518 // On enregistre le fils dans la table des threads
519 pthread_t thread_id = pthread_self();
521 Parametre param = _job.getParametre();
522 Environnement env = _job.getEnvironnement();
524 ostringstream id_sst;
526 param[ID] = id_sst.str();
527 param[STATE] = Batch::RUNNING;
532 _bm._threads[_id].thread_id = thread_id;
534 _bm._threads[_id].pid = child;
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);
541 // Unlock the master thread. From here, all shared variables must be protected
542 // from concurrent access
543 pthread_cond_signal(&_bm._threadSyncCondition);
546 // on boucle en attendant que le fils ait termine
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 );
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);
567 UNDER_LOCK( cout << "Status is: " << WIFCONTINUED( child_rc) << endl); // not compilable on sarge
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.
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 );
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 );
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 );
602 // On teste si le thread doit etre detruit
603 pthread_testcancel();
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 <-------- @@@
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 <-------- @@@
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();
652 UNDER_LOCK( cout << "Father does nothing to his child" << endl );
656 UNDER_LOCK( cout << "Father is sending SIGSTOP signal to his child" << endl );
657 kill(child, SIGSTOP);
661 UNDER_LOCK( cout << "Father is sending SIGCONT signal to his child" << endl );
662 kill(child, SIGCONT);
666 UNDER_LOCK( cout << "Father is sending SIGTERM signal to his child" << endl );
667 kill(child, SIGTERM);
671 UNDER_LOCK( cout << "Father is sending SIGKILL signal to his child" << endl );
672 kill(child, SIGKILL);
684 pthread_mutex_unlock(&_bm._threads_mutex);
685 // @@@ --------> SECTION CRITIQUE <-------- @@@
687 // On fait une petite pause pour ne pas surcharger inutilement le processeur
702 void BatchManager_Local::ThreadAdapter::fils()
704 Parametre param = _job.getParametre();
705 Parametre::iterator it;
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 );
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);
719 // Build the argument array argv from the command
720 char ** argv = new char * [command.size() + 1];
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];
729 argv[command.size()] = NULL;
731 UNDER_LOCK( cout << "*** debug_command = " << comstr << endl );
732 UNDER_LOCK( cout << "*** debug_command = " << argv[0] << endl );
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
737 Environnement env = _job.getEnvironnement();
741 envp = new char * [env.size() + 1]; // 1 pour le NULL terminal
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;
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);
752 // assert (i == env.size())
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 );
763 // On positionne les limites systeme imposees au fils
764 if (param.find(MAXCPUTIME) != param.end()) {
765 int maxcputime = param[MAXCPUTIME];
767 limit.rlim_cur = maxcputime;
768 limit.rlim_max = int(maxcputime * 1.1);
769 setrlimit(RLIMIT_CPU, &limit);
772 if (param.find(MAXDISKSIZE) != param.end()) {
773 int maxdisksize = param[MAXDISKSIZE];
775 limit.rlim_cur = maxdisksize * 1024;
776 limit.rlim_max = int(maxdisksize * 1.1) * 1024;
777 setrlimit(RLIMIT_FSIZE, &limit);
780 if (param.find(MAXRAMSIZE) != param.end()) {
781 int maxramsize = param[MAXRAMSIZE];
783 limit.rlim_cur = maxramsize * 1024 * 1024;
784 limit.rlim_max = int(maxramsize * 1.1) * 1024 * 1024;
785 setrlimit(RLIMIT_AS, &limit);
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 );
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)
800 // On ferme les descripteurs de fichiers standards
801 //close(STDIN_FILENO);
802 //close(STDOUT_FILENO);
803 //close(STDERR_FILENO);
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
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 );
815 } catch (GenericException & e) {
817 std::cerr << "Caught exception : " << e.type << " : " << e.message << std::endl;
825 BatchManager_Local::Process BatchManager_Local::ThreadAdapter::launchWin32ChildProcess()
827 Parametre param = _job.getParametre();
828 Parametre::iterator it;
829 PROCESS_INFORMATION pi;
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);
838 throw RunTimeException("Parameter \"EXECUTABLE\" is mandatory for local batch submission");
841 // Build the command string from the command argument vector
843 for (unsigned int i=0 ; i<exec_command.size() ; i++) {
844 if (i>0) comstr += " ";
845 comstr += exec_command[i];
848 UNDER_LOCK( cout << "*** debug_command = " << comstr << endl );
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
853 // Note that if no environment is specified, we reuse the current environment.
854 Environnement env = _job.getEnvironnement();
855 char * chNewEnv = NULL;
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;
868 // Terminate the block with a NULL byte.
869 *lpszCurrentVariable = '\0';
874 ZeroMemory( &si, sizeof(si) );
876 ZeroMemory( &pi, sizeof(pi) );
878 // Copy the command to a non-const buffer
879 char * buffer = strdup(comstr.c_str());
881 // launch the new process
882 BOOL res = CreateProcess(NULL, buffer, NULL, NULL, FALSE,
883 CREATE_NO_WINDOW, chNewEnv, NULL, &si, &pi);
885 if (buffer) free(buffer);
886 if (!res) throw RunTimeException("Error while creating new process");
888 CloseHandle(pi.hThread);
890 } catch (GenericException & e) {
892 std::cerr << "Caught exception : " << e.type << " : " << e.message << std::endl;
901 void BatchManager_Local::kill_child_on_exit(void * p_pid)
904 //TODO: porting of following functionality
905 pid_t child = * static_cast<pid_t *>(p_pid);
908 kill(child, SIGTERM);
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.
916 void BatchManager_Local::delete_on_exit(void * arg)
918 ThreadAdapter * p_ta = static_cast<ThreadAdapter *>(arg);
922 void BatchManager_Local::setFailedOnCancel(void * arg)
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);
929 // Unlock the master thread. From here, the batch manager instance should not be used.
930 pthread_cond_signal(&p_ta->getBatchManager()._threadSyncCondition);