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