Salome HOME
Removed some warnings
[tools/libbatch.git] / src / SGE / Batch_BatchManager_eSGE.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_eSGE.cxx : emulation of SGE 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 <sys/stat.h>
39
40 #include <stdlib.h>
41 #include <string.h>
42
43 #ifdef WIN32
44 #include <io.h>
45 #else
46 #include <libgen.h>
47 #endif
48
49 #include "Batch_BatchManager_eSGE.hxx"
50 #include "Batch_JobInfo_eSGE.hxx"
51
52 using namespace std;
53
54 namespace Batch {
55
56   BatchManager_eSGE::BatchManager_eSGE(const FactBatchManager * parent, const char * host,
57                                        const char * username,
58                                        CommunicationProtocolType protocolType, const char * mpiImpl)
59   : BatchManager(parent, host),
60     BatchManager_eClient(parent, host, username, protocolType, mpiImpl)
61   {
62     // Nothing to do
63   }
64
65   // Destructeur
66   BatchManager_eSGE::~BatchManager_eSGE()
67   {
68     // Nothing to do
69   }
70
71   // Methode pour le controle des jobs : soumet un job au gestionnaire
72   const JobId BatchManager_eSGE::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     exportInputFiles(job);
84
85     // build batch script for job
86     buildBatchScript(job);
87
88     // define name of log file (local)
89     string logFile = generateTemporaryFileName("SGE-submitlog");
90
91     // define command to submit batch
92     string subCommand = string("cd ") + workDir + "; qsub " + fileNameToExecute + "_Batch.sh";
93     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
94     command += " > ";
95     command += logFile;
96     command += " 2>&1";
97     cerr << command.c_str() << endl;
98     status = system(command.c_str());
99     if(status)
100     {
101       ifstream error_message(logFile.c_str());
102       std::string mess;
103       std::string temp;
104       while(std::getline(error_message, temp))
105         mess += temp;
106       error_message.close();
107       throw EmulationException("Error of connection on remote host, error was: " + mess);
108     }
109
110     // read id of submitted job in log file
111     char line[128];
112     FILE *fp = fopen(logFile.c_str(),"r");
113     fgets( line, 128, fp);
114     fclose(fp);
115
116     string strjob;
117     istringstream iss(line);
118     iss >> strjob >> strjob >> strjob;
119
120     JobId id(this, strjob);
121     return id;
122   }
123
124   // Ce manager permet de faire de la reprise
125   const Batch::JobId
126   BatchManager_eSGE::addJob(const Batch::Job & job, const std::string reference)
127   {
128     return JobId(this, reference);
129   }
130
131   // Methode pour le controle des jobs : retire un job du gestionnaire
132   void BatchManager_eSGE::deleteJob(const JobId & jobid)
133   {
134     int status;
135     int ref;
136     istringstream iss(jobid.getReference());
137     iss >> ref;
138
139     // define command to delete batch
140     string subCommand = string("qdel ") + iss.str();
141     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
142     cerr << command.c_str() << endl;
143     status = system(command.c_str());
144     if(status)
145       throw EmulationException("Error of connection on remote host");
146
147     cerr << "jobId = " << ref << "killed" << endl;
148   }
149
150   // Methode pour le controle des jobs : suspend un job en file d'attente
151   void BatchManager_eSGE::holdJob(const JobId & jobid)
152   {
153     throw EmulationException("Not yet implemented");
154   }
155
156   // Methode pour le controle des jobs : relache un job suspendu
157   void BatchManager_eSGE::releaseJob(const JobId & jobid)
158   {
159     throw EmulationException("Not yet implemented");
160   }
161
162
163   // Methode pour le controle des jobs : modifie un job en file d'attente
164   void BatchManager_eSGE::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
165   {
166     throw EmulationException("Not yet implemented");
167   }
168
169   // Methode pour le controle des jobs : modifie un job en file d'attente
170   void BatchManager_eSGE::alterJob(const JobId & jobid, const Parametre & param)
171   {
172     alterJob(jobid, param, Environnement());
173   }
174
175   // Methode pour le controle des jobs : modifie un job en file d'attente
176   void BatchManager_eSGE::alterJob(const JobId & jobid, const Environnement & env)
177   {
178     alterJob(jobid, Parametre(), env);
179   }
180
181   // Methode pour le controle des jobs : renvoie l'etat du job
182   JobInfo BatchManager_eSGE::queryJob(const JobId & jobid)
183   {
184     int id;
185     istringstream iss(jobid.getReference());
186     iss >> id;
187
188     // define name of log file (local)
189     string logFile = generateTemporaryFileName(string("SGE-querylog-id") + jobid.getReference());
190
191     // define command to query batch
192     string subCommand = string("qstat | grep ") + iss.str();
193     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
194     command += " > ";
195     command += logFile;
196     cerr << command.c_str() << endl;
197     int status = system(command.c_str());
198     if (status && status != 256)
199       throw EmulationException("Error of connection on remote host");
200
201     JobInfo_eSGE ji = JobInfo_eSGE(id,logFile);
202     return ji;
203   }
204
205   // Methode pour le controle des jobs : teste si un job est present en machine
206   bool BatchManager_eSGE::isRunning(const JobId & jobid)
207   {
208     throw EmulationException("Not yet implemented");
209   }
210
211   void BatchManager_eSGE::buildBatchScript(const Job & job)
212   {
213 #ifndef WIN32
214     //TODO porting on Win32 platform
215     std::cerr << "BuildBatchScript" << std::endl;
216     Parametre params = job.getParametre();
217
218     // Job Parameters
219     string workDir       = "";
220     string fileToExecute = "";
221     int nbproc           = 0;
222     int edt              = 0;
223     int mem              = 0;
224     string queue         = "";
225
226     // Mandatory parameters
227     if (params.find(WORKDIR) != params.end()) 
228       workDir = params[WORKDIR].str();
229     else 
230       throw EmulationException("params[WORKDIR] is not defined ! Please defined it, cannot submit this job");
231     if (params.find(EXECUTABLE) != params.end()) 
232       fileToExecute = params[EXECUTABLE].str();
233     else 
234       throw EmulationException("params[EXECUTABLE] is not defined ! Please defined it, cannot submit this job");
235
236     // Optional parameters
237     if (params.find(NBPROC) != params.end()) 
238       nbproc = params[NBPROC];
239     if (params.find(MAXWALLTIME) != params.end()) 
240       edt = params[MAXWALLTIME];
241     if (params.find(MAXRAMSIZE) != params.end()) 
242       mem = params[MAXRAMSIZE];
243     if (params.find(QUEUE) != params.end()) 
244       queue = params[QUEUE].str();
245
246     string::size_type p1 = fileToExecute.find_last_of("/");
247     string::size_type p2 = fileToExecute.find_last_of(".");
248     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
249     string fileNameToExecute = fileToExecute.substr(p1+1);
250
251     // Create batch submit file
252     ofstream tempOutputFile;
253     std::string TmpFileName = createAndOpenTemporaryFile("SGE-script", tempOutputFile);
254
255     tempOutputFile << "#! /bin/sh -f" << endl;
256     if (queue != "")
257       tempOutputFile << "#$ -q " << queue << endl;
258     tempOutputFile << "#$ -pe mpich " << nbproc << endl;
259     if( edt > 0 )
260       tempOutputFile << "#$ -l h_rt=" << getWallTime(edt) << endl ;
261     if( mem > 0 )
262       tempOutputFile << "#$ -l h_vmem=" << mem << "M" << endl ;
263     tempOutputFile << "#$ -o " << workDir << "/logs/output.log." << rootNameToExecute << endl ;
264     tempOutputFile << "#$ -e " << workDir << "/logs/error.log." << rootNameToExecute << endl ;
265
266     // Abstraction of PBS_NODEFILE - TODO
267     tempOutputFile << "export LIBBATCH_NODEFILE=$TMPDIR/machines" << endl;
268
269     // Launch the executable
270     tempOutputFile << "cd " << workDir << endl ;
271     tempOutputFile << "./" + fileNameToExecute << endl;
272     tempOutputFile.flush();
273     tempOutputFile.close();
274
275     BATCH_CHMOD(TmpFileName.c_str(), 0x1ED);
276     cerr << "Batch script file generated is: " << TmpFileName.c_str() << endl;
277
278     int status = _protocol.copyFile(TmpFileName, "", "",
279                                     workDir + "/" + rootNameToExecute + "_Batch.sh",
280                                     _hostname, _username);
281     if (status)
282       throw EmulationException("Error of connection on remote host");
283
284 #endif //WIN32
285   }
286
287   std::string BatchManager_eSGE::getWallTime(const long edt)
288   {
289     long h, m;
290     h = edt / 60;
291     m = edt - h*60;
292     ostringstream oss;
293     if( m >= 10 )
294       oss << h << ":" << m;
295     else
296       oss << h << ":0" << m;
297     return oss.str();
298   }
299
300 }