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