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