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