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