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