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