Salome HOME
Added support for Microsoft Visual C++ (also experimental)
[tools/libbatch.git] / src / PBS / Batch_BatchManager_ePBS.cxx
1 //  Copyright (C) 2007-2008  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_ePBS.cxx : emulation of PBS 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 <iostream>
33 #include <fstream>
34 #include <sstream>
35 #include <sys/stat.h>
36
37 #include "Batch_config.h"
38
39 #ifdef MSVC
40 #include <io.h>
41 #else
42 #include <libgen.h>
43 #endif
44
45 #include "Batch_BatchManager_ePBS.hxx"
46
47 using namespace std;
48
49 namespace Batch {
50
51   BatchManager_ePBS::BatchManager_ePBS(const FactBatchManager * parent, const char * host,
52                                        const char * protocol, const char * mpiImpl)
53     : BatchManager_eClient(parent, host, protocol, mpiImpl)
54   {
55     // Nothing to do
56   }
57
58   // Destructeur
59   BatchManager_ePBS::~BatchManager_ePBS()
60   {
61     // Nothing to do
62   }
63
64   // Methode pour le controle des jobs : soumet un job au gestionnaire
65   const JobId BatchManager_ePBS::submitJob(const Job & job)
66   {
67     int status;
68     Parametre params = job.getParametre();
69     const std::string dirForTmpFiles = params[TMPDIR];
70     const string fileToExecute = params[EXECUTABLE];
71     string::size_type p1 = fileToExecute.find_last_of("/");
72     string::size_type p2 = fileToExecute.find_last_of(".");
73     std::string fileNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
74
75     // export input files on cluster
76     exportInputFiles(job);
77
78     // build batch script for job
79     buildBatchScript(job);
80
81     // define name of log file (local)
82     string logFile = generateTemporaryFileName("PBS-submitlog");
83
84     // define command to submit batch
85     string command = "\"";
86
87     // Test protocol
88     if( _protocol == "rsh" )
89       command += RSH;
90     else if( _protocol == "ssh" )
91       command += SSH;
92     else
93       throw EmulationException("Unknown protocol : only rsh and ssh are known !");
94
95     command += "\" ";
96
97     if(_username != ""){
98       command += _username + "@";
99     }
100
101     command += _hostname + " ";
102 #ifndef WIN32
103     command += "\"";
104 #endif
105     command += "cd " ;
106     command += dirForTmpFiles ;
107     command += "; qsub " ;
108     command += fileNameToExecute ;
109     command += "_Batch.sh";
110 #ifndef WIN32
111     command += "\"";
112 #endif
113     command += " > ";
114     command += logFile;
115     cerr << command.c_str() << endl;
116     status = system(command.c_str());
117     if(status)
118       throw EmulationException("Error of connection on remote host");
119
120     // read id of submitted job in log file
121     char line[128];
122     FILE *fp = fopen(logFile.c_str(),"r");
123     fgets( line, 128, fp);
124     fclose(fp);
125
126     string sline(line);
127     size_t pos = sline.find(".");
128     string strjob;
129     if(pos == string::npos)
130       strjob = sline;
131     else
132       strjob = sline.substr(0,pos);
133
134     JobId id(this, strjob);
135     return id;
136   }
137
138   // Methode pour le controle des jobs : retire un job du gestionnaire
139   void BatchManager_ePBS::deleteJob(const JobId & jobid)
140   {
141     int status;
142     int ref;
143     istringstream iss(jobid.getReference());
144     iss >> ref;
145
146     // define command to submit batch
147     string command;
148     command = _protocol;
149     command += " ";
150
151     if (_username != ""){
152       command += _username;
153       command += "@";
154     }
155
156     command += _hostname;
157     command += " \"qdel " ;
158     command += iss.str();
159     command += "\"";
160     cerr << command.c_str() << endl;
161     status = system(command.c_str());
162     if(status)
163       throw EmulationException("Error of connection on remote host");
164
165     cerr << "jobId = " << ref << "killed" << endl;
166   }
167
168   // Methode pour le controle des jobs : suspend un job en file d'attente
169   void BatchManager_ePBS::holdJob(const JobId & jobid)
170   {
171     throw EmulationException("Not yet implemented");
172   }
173
174   // Methode pour le controle des jobs : relache un job suspendu
175   void BatchManager_ePBS::releaseJob(const JobId & jobid)
176   {
177     throw EmulationException("Not yet implemented");
178   }
179
180
181   // Methode pour le controle des jobs : modifie un job en file d'attente
182   void BatchManager_ePBS::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
183   {
184     throw EmulationException("Not yet implemented");
185   }
186
187   // Methode pour le controle des jobs : modifie un job en file d'attente
188   void BatchManager_ePBS::alterJob(const JobId & jobid, const Parametre & param)
189   {
190     alterJob(jobid, param, Environnement());
191   }
192
193   // Methode pour le controle des jobs : modifie un job en file d'attente
194   void BatchManager_ePBS::alterJob(const JobId & jobid, const Environnement & env)
195   {
196     alterJob(jobid, Parametre(), env);
197   }
198
199   // Methode pour le controle des jobs : renvoie l'etat du job
200   JobInfo BatchManager_ePBS::queryJob(const JobId & jobid)
201   {
202     int id;
203     istringstream iss(jobid.getReference());
204     iss >> id;
205
206     // define name of log file (local)
207     string logFile = generateTemporaryFileName(string("PBS-querylog-id") + jobid.getReference());
208
209     // define command to query batch
210     string command = "\"";
211
212     // Test protocol
213     if( _protocol == "rsh" )
214       command += RSH;
215     else if( _protocol == "ssh" )
216       command += SSH;
217     else
218       throw EmulationException("Unknown protocol : only rsh and ssh are known !");
219
220     command += "\" ";
221
222     if (_username != ""){
223       command += _username + "@";
224     }
225
226     command += _hostname + " ";
227 #ifndef WIN32
228     command += "\"";
229 #endif
230     command += "qstat -f " ;
231     command += iss.str();
232 #ifndef WIN32
233     command += "\"";
234 #endif
235     command += " > ";
236     command += logFile;
237     cerr << command.c_str() << endl;
238     int status = system(command.c_str());
239     if(status && status != 153 && status != 256*153)
240       throw EmulationException("Error of connection on remote host");
241
242     JobInfo_ePBS ji = JobInfo_ePBS(id,logFile);
243     return ji;
244   }
245
246   // Methode pour le controle des jobs : teste si un job est present en machine
247   bool BatchManager_ePBS::isRunning(const JobId & jobid)
248   {
249     throw EmulationException("Not yet implemented");
250   }
251
252   void BatchManager_ePBS::buildBatchScript(const Job & job)
253   {
254     int status;
255     Parametre params = job.getParametre();
256     Environnement env = job.getEnvironnement();
257     const long nbproc = params[NBPROC];
258     const long edt = params[MAXWALLTIME];
259     const long mem = params[MAXRAMSIZE];
260     const string workDir = params[WORKDIR];
261     const std::string dirForTmpFiles = params[TMPDIR];
262     const string fileToExecute = params[EXECUTABLE];
263     const string home = params[HOMEDIR];
264     const std::string queue = params[QUEUE];
265     std::string rootNameToExecute;
266     std::string fileNameToExecute;
267     std::string filelogtemp;
268     if( fileToExecute.size() > 0 ){
269       string::size_type p1 = fileToExecute.find_last_of("/");
270       string::size_type p2 = fileToExecute.find_last_of(".");
271       rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
272
273 #ifdef MSVC
274       char fname[_MAX_FNAME];
275       char ext[_MAX_EXT];
276       _splitpath_s(fileToExecute.c_str(), NULL, 0, NULL, 0, fname, _MAX_FNAME, ext, _MAX_EXT);
277       string execBaseName = string(fname) + ext;
278 #else
279       char* basec=strdup(fileToExecute.c_str());
280       string execBaseName = string(basename(basec));
281       free(basec);
282 #endif
283
284       fileNameToExecute = "~/" + dirForTmpFiles + "/" + execBaseName;
285
286       int idx = dirForTmpFiles.find("Batch/");
287       filelogtemp = dirForTmpFiles.substr(idx+6, dirForTmpFiles.length());
288     }
289     else{
290       rootNameToExecute = "command";
291     }
292
293     ofstream tempOutputFile;
294     std::string TmpFileName = createAndOpenTemporaryFile("PBS-script", tempOutputFile);
295
296     tempOutputFile << "#! /bin/sh -f" << endl;
297     if (queue != "")
298       tempOutputFile << "#BSUB -q " << queue << endl;
299     if( edt > 0 )
300       tempOutputFile << "#PBS -l walltime=" << edt*60 << endl ;
301     if( mem > 0 )
302       tempOutputFile << "#PBS -l mem=" << mem << "mb" << endl ;
303     if( fileToExecute.size() > 0 ){
304       tempOutputFile << "#PBS -o " << home << "/" << dirForTmpFiles << "/output.log." << filelogtemp << endl ;
305       tempOutputFile << "#PBS -e " << home << "/" << dirForTmpFiles << "/error.log." << filelogtemp << endl ;
306     }
307     else{
308       tempOutputFile << "#PBS -o " << dirForTmpFiles << "/" << env["LOGFILE"] << ".output.log" << endl ;
309       tempOutputFile << "#PBS -e " << dirForTmpFiles << "/" << env["LOGFILE"] << ".error.log" << endl ;
310     }
311     if( workDir.size() > 0 )
312       tempOutputFile << "cd " << workDir << endl ;
313     if( fileToExecute.size() > 0 ){
314       tempOutputFile << _mpiImpl->boot("${PBS_NODEFILE}",nbproc);
315       tempOutputFile << _mpiImpl->run("${PBS_NODEFILE}",nbproc,fileNameToExecute);
316       tempOutputFile << _mpiImpl->halt();
317     }
318     else{
319       tempOutputFile << "source " << env["SOURCEFILE"] << endl ;
320       tempOutputFile << env["COMMAND"];
321     }
322
323     tempOutputFile.flush();
324     tempOutputFile.close();
325 #ifdef WIN32
326     _chmod(
327 #else
328     chmod(
329 #endif
330       TmpFileName.c_str(), 0x1ED);
331     cerr << TmpFileName.c_str() << endl;
332
333     string command = "\"";
334
335     // Test protocol
336     if( _protocol == "rsh" ) {
337       command += RCP;
338     } else if( _protocol == "ssh" ) {
339       command += SCP;
340     } else
341       throw EmulationException("Unknown protocol : only rsh and ssh are known !");
342
343     command += "\" ";
344
345     command += TmpFileName;
346     command += " ";
347     if(_username != ""){
348       command +=  _username;
349       command += "@";
350     }
351     command += _hostname;
352     command += ":";
353     command += dirForTmpFiles ;
354     command += "/" ;
355     command += rootNameToExecute ;
356     command += "_Batch.sh" ;
357     cerr << command.c_str() << endl;
358     status = system(command.c_str());
359     if(status)
360       throw EmulationException("Error of connection on remote host");
361
362     remove(TmpFileName.c_str());
363   }
364
365 }