Salome HOME
Fixed nodes file when nb procs > 128
[tools/libbatch.git] / src / LSF / Batch_BatchManager_eLSF.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_eLSF.cxx : emulation of LSF client
24  *
25  * Auteur : Bernard SECHER - CEA DEN
26  * Mail   : mailto:bernard.secher@cea.fr
27  * Date   : Thu Apr 24 10:17:22 2008
28  * Projet : PAL Salome
29  *
30  */
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include <iostream>
36 #include <fstream>
37 #include <sstream>
38 #include <string>
39 #include <sys/stat.h>
40
41 #include <stdlib.h>
42 #include <string.h>
43
44 #ifdef WIN32
45 #include <io.h>
46 #else
47 #include <libgen.h>
48 #endif
49
50 #include "Batch_BatchManager_eLSF.hxx"
51 #include "Batch_JobInfo_eLSF.hxx"
52
53 using namespace std;
54
55 namespace Batch {
56
57   BatchManager_eLSF::BatchManager_eLSF(const FactBatchManager * parent, const char * host,
58                                        const char * username,
59                                        CommunicationProtocolType protocolType, const char * mpiImpl)
60   : BatchManager(parent, host),
61     BatchManager_eClient(parent, host, username, protocolType, mpiImpl)
62
63   {
64     // Nothing to do
65   }
66
67   // Destructeur
68   BatchManager_eLSF::~BatchManager_eLSF()
69   {
70     // Nothing to do
71   }
72
73   // Methode pour le controle des jobs : soumet un job au gestionnaire
74   const JobId BatchManager_eLSF::submitJob(const Job & job)
75   {
76     int status;
77     Parametre params = job.getParametre();
78     const std::string workDir = params[WORKDIR];
79     const string fileToExecute = params[EXECUTABLE];
80     string::size_type p1 = fileToExecute.find_last_of("/");
81     string::size_type p2 = fileToExecute.find_last_of(".");
82     std::string fileNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
83
84     // export input files on cluster
85     cerr << "Export des fichiers en entree" << endl;
86     exportInputFiles(job);
87
88     // build batch script for job
89     cerr << "Construction du script de batch" << endl;
90     buildBatchScript(job);
91     cerr << "Script envoye" << endl;
92
93     // define name of log file (local)
94     string logFile = generateTemporaryFileName("LSF-submitlog");
95
96     // define command to submit batch
97     string subCommand = string("cd ") + workDir + "; bsub < " + fileNameToExecute + "_Batch.sh";
98     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
99     command += " > ";
100     command += logFile;
101     command += " 2>&1";
102     cerr << command.c_str() << endl;
103     status = system(command.c_str());
104     if(status)
105     {
106       ifstream error_message(logFile.c_str());
107       std::string mess;
108       std::string temp;
109       while(std::getline(error_message, temp))
110         mess += temp;
111       error_message.close();
112       throw EmulationException("Error of connection on remote host, error was: " + mess);
113     }
114
115     // read id of submitted job in log file
116     char line[128];
117     FILE *fp = fopen(logFile.c_str(),"r");
118     fgets( line, 128, fp);
119     fclose(fp);
120
121     string sline(line);
122     int p10 = sline.find("<");
123     int p20 = sline.find(">");
124     string strjob = sline.substr(p10+1,p20-p10-1);
125
126     JobId id(this, strjob);
127     return id;
128   }
129
130   // Ce manager permet de faire de la reprise
131   const Batch::JobId
132   BatchManager_eLSF::addJob(const Batch::Job & job, const std::string reference)
133   {
134     return JobId(this, reference);
135   }
136
137   // Methode pour le controle des jobs : retire un job du gestionnaire
138   void BatchManager_eLSF::deleteJob(const JobId & jobid)
139   {
140     int status;
141     int ref;
142     istringstream iss(jobid.getReference());
143     iss >> ref;
144
145     // define command to delete batch
146     string subCommand = string("bkill ") + iss.str();
147     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
148     cerr << command.c_str() << endl;
149     status = system(command.c_str());
150     if (status)
151       throw EmulationException("Error of connection on remote host");
152
153     cerr << "jobId = " << ref << "killed" << endl;
154   }
155
156   // Methode pour le controle des jobs : suspend un job en file d'attente
157   void BatchManager_eLSF::holdJob(const JobId & jobid)
158   {
159     throw EmulationException("Not yet implemented");
160   }
161
162   // Methode pour le controle des jobs : relache un job suspendu
163   void BatchManager_eLSF::releaseJob(const JobId & jobid)
164   {
165     throw EmulationException("Not yet implemented");
166   }
167
168
169   // Methode pour le controle des jobs : modifie un job en file d'attente
170   void BatchManager_eLSF::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
171   {
172     throw EmulationException("Not yet implemented");
173   }
174
175   // Methode pour le controle des jobs : modifie un job en file d'attente
176   void BatchManager_eLSF::alterJob(const JobId & jobid, const Parametre & param)
177   {
178     alterJob(jobid, param, Environnement());
179   }
180
181   // Methode pour le controle des jobs : modifie un job en file d'attente
182   void BatchManager_eLSF::alterJob(const JobId & jobid, const Environnement & env)
183   {
184     alterJob(jobid, Parametre(), env);
185   }
186
187   // Methode pour le controle des jobs : renvoie l'etat du job
188   JobInfo BatchManager_eLSF::queryJob(const JobId & jobid)
189   {
190     int id;
191     istringstream iss(jobid.getReference());
192     iss >> id;
193
194     // define name of log file (local)
195     string logFile = generateTemporaryFileName(string("LSF-querylog-id") + jobid.getReference());
196
197     // define command to query batch
198     string subCommand = string("bjobs ") + iss.str();
199     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
200     command += " > ";
201     command += logFile;
202     cerr << command.c_str() << endl;
203     int status = system(command.c_str());
204     if (status)
205       throw EmulationException("Error of connection on remote host");
206
207     JobInfo_eLSF ji = JobInfo_eLSF(id,logFile);
208     return ji;
209   }
210
211
212
213   // Methode pour le controle des jobs : teste si un job est present en machine
214   bool BatchManager_eLSF::isRunning(const JobId & jobid)
215   {
216     throw EmulationException("Not yet implemented");
217   }
218
219   void BatchManager_eLSF::buildBatchScript(const Job & job)
220   {
221 #ifndef WIN32 //TODO: need for porting on Windows
222     Parametre params = job.getParametre();
223
224     // Job Parameters
225     string workDir       = "";
226     string fileToExecute = "";
227     int nbproc           = 0;
228     int edt              = 0;
229     int mem              = 0;
230     string queue         = "";
231
232     // Mandatory parameters
233     if (params.find(WORKDIR) != params.end()) 
234       workDir = params[WORKDIR].str();
235     else 
236       throw EmulationException("params[WORKDIR] is not defined ! Please defined it, cannot submit this job");
237     if (params.find(EXECUTABLE) != params.end()) 
238       fileToExecute = params[EXECUTABLE].str();
239     else 
240       throw EmulationException("params[EXECUTABLE] is not defined ! Please defined it, cannot submit this job");
241
242     // Optional parameters
243     if (params.find(NBPROC) != params.end()) 
244       nbproc = params[NBPROC];
245     if (params.find(MAXWALLTIME) != params.end()) 
246       edt = params[MAXWALLTIME];
247     if (params.find(MAXRAMSIZE) != params.end()) 
248       mem = params[MAXRAMSIZE];
249     if (params.find(QUEUE) != params.end()) 
250       queue = params[QUEUE].str();
251
252     string::size_type p1 = fileToExecute.find_last_of("/");
253     string::size_type p2 = fileToExecute.find_last_of(".");
254     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
255     string fileNameToExecute = fileToExecute.substr(p1+1);
256  
257     // Create batch submit file
258     ofstream tempOutputFile;
259     std::string TmpFileName = createAndOpenTemporaryFile("LSF-script", tempOutputFile);
260
261     tempOutputFile << "#! /bin/sh -f" << endl ;
262     if (queue != "")
263       tempOutputFile << "#BSUB -q " << queue << endl;
264     if( edt > 0 )
265       tempOutputFile << "#BSUB -W " << getWallTime(edt) << endl ;
266     if( mem > 0 )
267       tempOutputFile << "#BSUB -M " << mem*1024 << endl ;
268     tempOutputFile << "#BSUB -n " << nbproc << endl ;
269     size_t pos = workDir.find("$HOME");
270     string baseDir;
271     if( pos != string::npos )
272       baseDir = getHomeDir(workDir) + workDir.substr(pos+5,workDir.length()-5);
273     else{
274       pos = workDir.find("~");
275       if( pos != string::npos )
276         baseDir = getHomeDir(workDir) + workDir.substr(pos+1,workDir.length()-1);
277       else
278         baseDir = workDir;
279     }
280     tempOutputFile << "#BSUB -o " << baseDir << "/logs/output.log." << rootNameToExecute << endl ;
281     tempOutputFile << "#BSUB -e " << baseDir << "/logs/error.log." << rootNameToExecute << endl ;
282
283     tempOutputFile << "cd " << workDir << endl ;
284
285     // generate nodes file
286     tempOutputFile << "NODEFILE=`mktemp nodefile-XXXXXXXXXX` || exit 1" << endl;
287     tempOutputFile << "bool=0" << endl;
288     tempOutputFile << "for i in $LSB_MCPU_HOSTS; do" << endl;
289     tempOutputFile << "  if test $bool = 0; then" << endl;
290     tempOutputFile << "    n=$i" << endl;
291     tempOutputFile << "    bool=1" << endl;
292     tempOutputFile << "  else" << endl;
293     tempOutputFile << "    for ((j=0;j<$i;j++)); do" << endl;
294     tempOutputFile << "      echo $n >> $NODEFILE" << endl;
295     tempOutputFile << "    done" << endl;
296     tempOutputFile << "    bool=0" << endl;
297     tempOutputFile << "  fi" << endl;
298     tempOutputFile << "done" << endl;
299
300     // Abstraction of PBS_NODEFILE - TODO
301     tempOutputFile << "export LIBBATCH_NODEFILE=$NODEFILE" << endl;
302
303     // Launch the executable
304     tempOutputFile << "./" + fileNameToExecute << endl;
305
306     // Remove the node file
307     tempOutputFile << "rm $NODEFILE" << endl;
308
309     tempOutputFile.flush();
310     tempOutputFile.close();
311
312     BATCH_CHMOD(TmpFileName.c_str(), 0x1ED);
313     cerr << "Batch script file generated is: " << TmpFileName.c_str() << endl;
314
315     int status = _protocol.copyFile(TmpFileName, "", "",
316                                     workDir + "/" + rootNameToExecute + "_Batch.sh",
317                                     _hostname, _username);
318     if (status)
319       throw EmulationException("Error of connection on remote host");
320
321 #endif
322
323   }
324
325   std::string BatchManager_eLSF::getWallTime(const long edt)
326   {
327     long h, m;
328     h = edt / 60;
329     m = edt - h*60;
330     ostringstream oss;
331     if( m >= 10 )
332       oss << h << ":" << m;
333     else
334       oss << h << ":0" << m;
335     return oss.str();
336   }
337
338   std::string BatchManager_eLSF::getHomeDir(std::string tmpdir)
339   {
340     std::string home;
341     int idx = tmpdir.find("Batch/");
342     std::string filelogtemp = tmpdir.substr(idx+6, tmpdir.length());
343     filelogtemp = "/tmp/logs" + filelogtemp + "_home";
344
345     string subCommand = string("echo $HOME");
346     string command = _protocol.getExecCommand(subCommand, _hostname, _username) + " > " + filelogtemp;
347     cerr << command.c_str() << endl;
348     int status = system(command.c_str());
349     if (status)
350       throw EmulationException("Error of launching home command on remote host");
351
352     std::ifstream file_home(filelogtemp.c_str());
353     std::getline(file_home, home);
354     file_home.close();
355     return home;
356   }
357
358 }