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 // On retrouve le thread_id du thread
143 // @@@ --------> SECTION CRITIQUE <-------- @@@
144 pthread_mutex_lock(&_threads_mutex);
145 bool idFound = (_threads.find(id) != _threads.end());
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);
152 cout << "Cannot delete job " << jobid.getReference() <<
153 ". Job is already finished." << endl;
156 pthread_mutex_unlock(&_threads_mutex);
157 // @@@ --------> SECTION CRITIQUE <-------- @@@
160 throw RunTimeException(string("Job with id ") + jobid.getReference() + " does not exist");
163 // Methode pour le controle des jobs : suspend un job en file d'attente
164 void BatchManager_Local::holdJob(const JobId & jobid)
167 istringstream iss(jobid.getReference());
170 UNDER_LOCK( cout << "BatchManager is sending HOLD command to the thread " << id << endl );
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 <-------- @@@
181 // Methode pour le controle des jobs : relache un job suspendu
182 void BatchManager_Local::releaseJob(const JobId & jobid)
185 istringstream iss(jobid.getReference());
188 UNDER_LOCK( cout << "BatchManager is sending RELEASE command to the thread " << id << endl );
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 <-------- @@@
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)
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)
208 alterJob(jobid, param, Environnement());
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)
214 alterJob(jobid, Parametre(), env);
219 // Methode pour le controle des jobs : renvoie l'etat du job
220 JobInfo BatchManager_Local::queryJob(const JobId & jobid)
223 istringstream iss(jobid.getReference());
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());
235 param = pos->second.param;
236 env = pos->second.env;
238 pthread_mutex_unlock(&_threads_mutex);
239 // @@@ --------> SECTION CRITIQUE <-------- @@@
240 //UNDER_LOCK( cout << "JobInfo BatchManager_Local::queryJob(const JobId & jobid) : APRES section critique" << endl );
242 if (!found) throw InvalidArgumentException("Invalid JobId argument for queryJob");
244 JobInfo_Local ji(param, env);
250 // Methode pour le controle des jobs : teste si un job est present en machine
251 bool BatchManager_Local::isRunning(const JobId & jobid)
254 istringstream iss(jobid.getReference());
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 );
269 vector<string> BatchManager_Local::exec_command(const Parametre & param) const
271 ostringstream exec_sub_cmd;
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 << " && ";
279 exec_sub_cmd << "cd " << param[WORKDIR] << " && " << param[EXECUTABLE];
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);
286 exec_sub_cmd << " " << arg;
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";
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";
311 Parametre::const_iterator it = param.find(USER);
312 if (it != param.end()) {
313 user = string(it->second);
316 return _protocol.getExecCommandArgs(exec_sub_cmd.str(), param[EXECUTIONHOST], user);
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)
330 // Methode d'execution du thread
331 void * BatchManager_Local::ThreadAdapter::run(void * arg)
333 ThreadAdapter * p_ta = static_cast<ThreadAdapter *>(arg);
336 // On bloque tous les signaux pour ce thread
338 sigfillset(&setmask);
339 pthread_sigmask(SIG_BLOCK, &setmask, NULL);
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);
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()
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));
356 // Le code retour cumule (ORed) de tous les appels
357 // Nul en cas de reussite de l'ensemble des operations
360 // Cette table contient la liste des fichiers a detruire a la fin du processus
361 std::vector<string> files_to_delete;
365 // On copie les fichiers d'entree pour le fils
366 const Parametre param = p_ta->_job.getParametre();
367 Parametre::const_iterator it;
369 // On initialise la variable workdir a la valeur du Current Working Directory
375 getcwd(cwd, PATH_MAX);
377 string workdir = cwd;
380 if ( (it = param.find(WORKDIR)) != param.end() ) {
381 workdir = static_cast<string>( (*it).second );
384 string executionhost = string(param[EXECUTIONHOST]);
386 if ( (it = param.find(USER)) != param.end() ) {
387 user = string(it->second);
390 if ( (it = param.find(INFILE)) != param.end() ) {
391 Versatile V = (*it).second;
392 Versatile::iterator Vit;
394 for(Vit=V.begin(); Vit!=V.end(); Vit++) {
395 CoupleType cpt = *static_cast< CoupleType * >(*Vit);
397 string local = cp.getLocal();
398 string remote = cp.getRemote();
400 std::cerr << workdir << std::endl;
401 std::cerr << remote << std::endl;
403 int status = p_ta->getBatchManager().getProtocol().copyFile(local, "", "",
404 workdir + "/" + remote,
405 executionhost, user);
410 // On enregistre le fichier comme etant a detruire
411 files_to_delete.push_back(workdir + "/" + remote);
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);
426 child = p_ta->launchWin32ChildProcess();
430 if (child < 0) { // erreur
431 UNDER_LOCK( cerr << "Fork impossible (rc=" << child << ")" << endl );
433 } else if (child > 0) { // pere
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;
447 for(Vit=V.begin(); Vit!=V.end(); Vit++) {
448 CoupleType cpt = *static_cast< CoupleType * >(*Vit);
450 string local = cp.getLocal();
451 string remote = cp.getRemote();
453 int status = p_ta->getBatchManager().getProtocol().copyFile(workdir + "/" + remote,
460 // On enregistre le fichier comme etant a detruire
461 files_to_delete.push_back(workdir + "/" + remote);
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 );
476 remove_cmd = string("\"") + remove_cmd + string("\"");
478 system(remove_cmd.c_str());*/
482 pthread_mutex_lock(&p_ta->_bm._threads_mutex);
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;
487 // On retire la fonction de nettoyage de la memoire
488 pthread_cleanup_pop(0);
490 // On retire la fonction de suppression du fils
491 pthread_cleanup_pop(0);
493 // remove setFailedOnCancel function from cancel stack
494 pthread_cleanup_pop(0);
496 pthread_mutex_unlock(&p_ta->_bm._threads_mutex);
498 // On invoque la fonction de nettoyage de la memoire
501 UNDER_LOCK( cout << "Father is leaving" << endl );
509 void BatchManager_Local::ThreadAdapter::pere(Process child)
511 time_t child_starttime = time(NULL);
513 // On enregistre le fils dans la table des threads
514 pthread_t thread_id = pthread_self();
516 Parametre param = _job.getParametre();
517 Environnement env = _job.getEnvironnement();
519 ostringstream id_sst;
521 param[ID] = id_sst.str();
522 param[STATE] = Batch::RUNNING;
527 _bm._threads[_id].thread_id = thread_id;
529 _bm._threads[_id].pid = child;
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);
536 // Unlock the master thread. From here, all shared variables must be protected
537 // from concurrent access
538 pthread_cond_signal(&_bm._threadSyncCondition);
541 // on boucle en attendant que le fils ait termine
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 );
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);
562 UNDER_LOCK( cout << "Status is: " << WIFCONTINUED( child_rc) << endl); // not compilable on sarge
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.
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 );
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 );
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 );
597 // On teste si le thread doit etre detruit
598 pthread_testcancel();
602 // On regarde si le fils n'a pas depasse son temps (wallclock time)
603 time_t child_currenttime = time(NULL);
604 time_t child_elapsedtime = child_currenttime - child_starttime;
605 if (param.find(MAXWALLTIME) != param.end()) {
606 int 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 > int(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 <-------- @@@
623 } else if (child_elapsedtime > 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 <-------- @@@
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();
647 UNDER_LOCK( cout << "Father does nothing to his child" << endl );
651 UNDER_LOCK( cout << "Father is sending SIGSTOP signal to his child" << endl );
652 kill(child, SIGSTOP);
656 UNDER_LOCK( cout << "Father is sending SIGCONT signal to his child" << endl );
657 kill(child, SIGCONT);
661 UNDER_LOCK( cout << "Father is sending SIGTERM signal to his child" << endl );
662 kill(child, SIGTERM);
666 UNDER_LOCK( cout << "Father is sending SIGKILL signal to his child" << endl );
667 kill(child, SIGKILL);
679 pthread_mutex_unlock(&_bm._threads_mutex);
680 // @@@ --------> SECTION CRITIQUE <-------- @@@
682 // On fait une petite pause pour ne pas surcharger inutilement le processeur
697 void BatchManager_Local::ThreadAdapter::fils()
699 Parametre param = _job.getParametre();
700 Parametre::iterator it;
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 );
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);
714 // Build the argument array argv from the command
715 char ** argv = new char * [command.size() + 1];
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];
724 argv[command.size()] = NULL;
726 UNDER_LOCK( cout << "*** debug_command = " << comstr << endl );
727 UNDER_LOCK( cout << "*** debug_command = " << argv[0] << endl );
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
732 Environnement env = _job.getEnvironnement();
736 envp = new char * [env.size() + 1]; // 1 pour le NULL terminal
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;
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);
747 // assert (i == env.size())
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 );
758 // On positionne les limites systeme imposees au fils
759 if (param.find(MAXCPUTIME) != param.end()) {
760 int maxcputime = param[MAXCPUTIME];
762 limit.rlim_cur = maxcputime;
763 limit.rlim_max = int(maxcputime * 1.1);
764 setrlimit(RLIMIT_CPU, &limit);
767 if (param.find(MAXDISKSIZE) != param.end()) {
768 int maxdisksize = param[MAXDISKSIZE];
770 limit.rlim_cur = maxdisksize * 1024;
771 limit.rlim_max = int(maxdisksize * 1.1) * 1024;
772 setrlimit(RLIMIT_FSIZE, &limit);
775 if (param.find(MAXRAMSIZE) != param.end()) {
776 int maxramsize = param[MAXRAMSIZE];
778 limit.rlim_cur = maxramsize * 1024 * 1024;
779 limit.rlim_max = int(maxramsize * 1.1) * 1024 * 1024;
780 setrlimit(RLIMIT_AS, &limit);
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 );
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)
795 // On ferme les descripteurs de fichiers standards
796 //close(STDIN_FILENO);
797 //close(STDOUT_FILENO);
798 //close(STDERR_FILENO);
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
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 );
810 } catch (GenericException & e) {
812 std::cerr << "Caught exception : " << e.type << " : " << e.message << std::endl;
820 BatchManager_Local::Process BatchManager_Local::ThreadAdapter::launchWin32ChildProcess()
822 Parametre param = _job.getParametre();
823 Parametre::iterator it;
824 PROCESS_INFORMATION pi;
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);
833 throw RunTimeException("Parameter \"EXECUTABLE\" is mandatory for local batch submission");
836 // Build the command string from the command argument vector
838 for (unsigned int i=0 ; i<exec_command.size() ; i++) {
839 if (i>0) comstr += " ";
840 comstr += exec_command[i];
843 UNDER_LOCK( cout << "*** debug_command = " << comstr << endl );
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
848 // Note that if no environment is specified, we reuse the current environment.
849 Environnement env = _job.getEnvironnement();
850 char * chNewEnv = NULL;
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;
863 // Terminate the block with a NULL byte.
864 *lpszCurrentVariable = '\0';
869 ZeroMemory( &si, sizeof(si) );
871 ZeroMemory( &pi, sizeof(pi) );
873 // Copy the command to a non-const buffer
874 char * buffer = strdup(comstr.c_str());
876 // launch the new process
877 BOOL res = CreateProcess(NULL, buffer, NULL, NULL, FALSE,
878 CREATE_NO_WINDOW, chNewEnv, NULL, &si, &pi);
880 if (buffer) free(buffer);
881 if (!res) throw RunTimeException("Error while creating new process");
883 CloseHandle(pi.hThread);
885 } catch (GenericException & e) {
887 std::cerr << "Caught exception : " << e.type << " : " << e.message << std::endl;
896 void BatchManager_Local::kill_child_on_exit(void * p_pid)
899 //TODO: porting of following functionality
900 pid_t child = * static_cast<pid_t *>(p_pid);
903 kill(child, SIGTERM);
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.
911 void BatchManager_Local::delete_on_exit(void * arg)
913 ThreadAdapter * p_ta = static_cast<ThreadAdapter *>(arg);
917 void BatchManager_Local::setFailedOnCancel(void * arg)
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);
924 // Unlock the master thread. From here, the batch manager instance should not be used.
925 pthread_cond_signal(&p_ta->getBatchManager()._threadSyncCondition);