Salome HOME
Moved username initialization to the constructor in BatchManager_eClients
[tools/libbatch.git] / src / PBS / Batch_BatchManager_ePBS.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_ePBS.cxx : emulation of PBS client
24  *
25  * Auteur : Bernard SECHER - CEA DEN, AndrĂ© RIBES - EDF R&D
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 #include <Batch_config.h>
43
44 #ifdef MSVC
45 #include <io.h>
46 #else
47 #include <libgen.h>
48 #endif
49
50 #include "Batch_BatchManager_ePBS.hxx"
51 #include "Batch_JobInfo_ePBS.hxx"
52
53 using namespace std;
54
55 namespace Batch {
56
57   BatchManager_ePBS::BatchManager_ePBS(const FactBatchManager * parent, const char * host,
58                                        const char * username,
59                                        CommunicationProtocolType protocolType, const char * mpiImpl, 
60                                        int nb_proc_per_node)
61     : BatchManager_eClient(parent, host, username, protocolType, mpiImpl),
62     BatchManager(parent, host)
63   {
64     // Nothing to do
65     _nb_proc_per_node = nb_proc_per_node;
66   }
67
68   // Destructeur
69   BatchManager_ePBS::~BatchManager_ePBS()
70   {
71     // Nothing to do
72   }
73
74   // Methode pour le controle des jobs : soumet un job au gestionnaire
75   const JobId BatchManager_ePBS::submitJob(const Job & job)
76   {
77     int status;
78     Parametre params = job.getParametre();
79     const std::string workDir = params[WORKDIR];
80     const string fileToExecute = params[EXECUTABLE];
81     string::size_type p1 = fileToExecute.find_last_of("/");
82     string::size_type p2 = fileToExecute.find_last_of(".");
83     std::string fileNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
84
85     // export input files on cluster
86     exportInputFiles(job);
87
88     // build batch script for job
89     buildBatchScript(job);
90
91     // define name of log file (local)
92     string logFile = generateTemporaryFileName("PBS-submitlog");
93
94     // define command to submit batch
95     string subCommand = string("cd ") + workDir + "; qsub " + fileNameToExecute + "_Batch.sh";
96     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
97     command += " > ";
98     command += logFile;
99     command += " 2>&1";
100     cerr << command.c_str() << endl;
101     status = system(command.c_str());
102     if(status)
103     {
104       ifstream error_message(logFile.c_str());
105       std::string mess;
106       std::string temp;
107       while(std::getline(error_message, temp))
108         mess += temp;
109       error_message.close();
110       throw EmulationException("Error of connection on remote host, error was: " + mess);
111     }
112
113     // read id of submitted job in log file
114     ifstream idfile(logFile.c_str());
115     string sline;
116     idfile >> sline;
117     idfile.close();
118     if (sline.size() == 0)
119       throw EmulationException("Error in the submission of the job on the remote host");
120
121     JobId id(this, sline);
122     return id;
123   }
124
125   // Ce manager permet de faire de la reprise
126   const Batch::JobId
127   BatchManager_ePBS::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_ePBS::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("qdel ") + iss.str();
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_ePBS::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_ePBS::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_ePBS::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_ePBS::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_ePBS::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_ePBS::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("PBS-querylog-id") + jobid.getReference());
191
192     // define command to query batch
193     string subCommand = string("qstat -f ") + iss.str();
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 != 153 && status != 256*153)
200       throw EmulationException("Error of connection on remote host");
201
202     JobInfo_ePBS ji = JobInfo_ePBS(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_ePBS::isRunning(const JobId & jobid)
208   {
209     throw EmulationException("Not yet implemented");
210   }
211
212   void BatchManager_ePBS::buildBatchScript(const Job & job)
213   {
214     std::cerr << "BuildBatchScript" << std::endl;
215     Parametre params = job.getParametre();
216     Environnement env = job.getEnvironnement();
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("PBS-script", tempOutputFile);
254
255     tempOutputFile << "#! /bin/sh -f" << endl;
256     if (nbproc > 0)
257     {
258       // Division - arrondi supĂ©rieur
259       int nodes_requested = (nbproc + _nb_proc_per_node -1) / _nb_proc_per_node;
260       tempOutputFile << "#PBS -l nodes=" << nodes_requested << ":ppn=" << _nb_proc_per_node << endl;
261     }
262     if (queue != "")
263       tempOutputFile << "#PBS -q " << queue << endl;
264     if( edt > 0 )
265       tempOutputFile << "#PBS -l walltime=" << edt*60 << endl;
266     if( mem > 0 )
267       tempOutputFile << "#PBS -l mem=" << mem << "MB" << endl;
268     tempOutputFile << "#PBS -o " << workDir << "/logs/output.log." << rootNameToExecute << endl;
269     tempOutputFile << "#PBS -e " << workDir << "/logs/error.log."  << rootNameToExecute << endl;
270
271     // Define environment for the job
272     if (!env.empty()) {
273       tempOutputFile << "#PBS -v ";
274       Environnement::const_iterator iter;
275       for (iter = env.begin() ; iter != env.end() ; ++iter) {
276         tempOutputFile << iter->first << "=" << iter->second << ",";
277       }
278       tempOutputFile << endl;
279     }
280
281     // Abstraction of PBS_NODEFILE - TODO
282     tempOutputFile << "export LIBBATCH_NODEFILE=$PBS_NODEFILE" << endl;
283
284     // Launch the executable
285     tempOutputFile << "cd " << workDir << endl;
286     tempOutputFile << "./" + fileNameToExecute << endl;
287     tempOutputFile.flush();
288     tempOutputFile.close();
289
290     BATCH_CHMOD(TmpFileName.c_str(), 0x1ED);
291     cerr << "Batch script file generated is: " << TmpFileName.c_str() << endl;
292
293     int status = _protocol.copyFile(TmpFileName, "", "",
294                                     workDir + "/" + rootNameToExecute + "_Batch.sh",
295                                     _hostname, _username);
296     if (status)
297       throw EmulationException("Error of connection on remote host, cannot copy batch submission file");
298   }
299 }