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