Salome HOME
Rename files:
[tools/libbatch.git] / src / PBS / BatchManager_PBS.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_PBS.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 <cstdlib>
33 #include <fstream>
34 #include <sstream>
35
36 #include <Constants.hxx>
37 #include <Utils.hxx>
38 #include <NotYetImplementedException.hxx>
39
40 #include "BatchManager_PBS.hxx"
41 #include "JobInfo_PBS.hxx"
42
43 using namespace std;
44
45 namespace Batch {
46
47   BatchManager_PBS::BatchManager_PBS(const FactBatchManager * parent, const char * host,
48                                        const char * username,
49                                        CommunicationProtocolType protocolType, const char * mpiImpl)
50     : BatchManager(parent, host, username, protocolType, mpiImpl)
51   {
52     // Nothing to do
53   }
54
55   // Destructeur
56   BatchManager_PBS::~BatchManager_PBS()
57   {
58     // Nothing to do
59   }
60
61   // Methode pour le controle des jobs : soumet un job au gestionnaire
62   const JobId BatchManager_PBS::submitJob(const Job & job)
63   {
64     Parametre params = job.getParametre();
65     const std::string workDir = params[WORKDIR];
66
67     // export input files on cluster
68     exportInputFiles(job);
69
70     // build batch script for job
71     string scriptFile = buildSubmissionScript(job);
72
73     // define command to submit batch
74     string subCommand = string("cd ") + workDir + "; qsub " + scriptFile;
75     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
76     command += " 2>&1";
77     cerr << command.c_str() << endl;
78
79     // submit job
80     string output;
81     int status = Utils::getCommandOutput(command, output);
82     cout << output;
83     if (status != 0) throw RunTimeException("Can't submit job, error was: " + output);
84
85     // normally output contains only id of submitted job, we just need to remove the final \n
86     string jobref = output.substr(0, output.size() - 1);
87     JobId id(this, jobref);
88
89     return id;
90   }
91
92   // Ce manager permet de faire de la reprise
93   const Batch::JobId
94   BatchManager_PBS::addJob(const Batch::Job & job, const std::string reference)
95   {
96     return JobId(this, reference);
97   }
98
99   // Methode pour le controle des jobs : retire un job du gestionnaire
100   void BatchManager_PBS::deleteJob(const JobId & jobid)
101   {
102     int status;
103     int ref;
104     istringstream iss(jobid.getReference());
105     iss >> ref;
106
107     // define command to delete batch
108     string subCommand = string("qdel ") + iss.str();
109     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
110     cerr << command.c_str() << endl;
111     status = system(command.c_str());
112     if (status)
113       throw RunTimeException("Error of connection on remote host");
114
115     cerr << "jobId = " << ref << "killed" << endl;
116   }
117
118   // Methode pour le controle des jobs : suspend un job en file d'attente
119   void BatchManager_PBS::holdJob(const JobId & jobid)
120   {
121     throw NotYetImplementedException("BatchManager_PBS::holdJob");
122   }
123
124   // Methode pour le controle des jobs : relache un job suspendu
125   void BatchManager_PBS::releaseJob(const JobId & jobid)
126   {
127     throw NotYetImplementedException("BatchManager_PBS::releaseJob");
128   }
129
130
131   // Methode pour le controle des jobs : modifie un job en file d'attente
132   void BatchManager_PBS::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
133   {
134     throw NotYetImplementedException("BatchManager_PBS::alterJob");
135   }
136
137   // Methode pour le controle des jobs : modifie un job en file d'attente
138   void BatchManager_PBS::alterJob(const JobId & jobid, const Parametre & param)
139   {
140     alterJob(jobid, param, Environnement());
141   }
142
143   // Methode pour le controle des jobs : modifie un job en file d'attente
144   void BatchManager_PBS::alterJob(const JobId & jobid, const Environnement & env)
145   {
146     alterJob(jobid, Parametre(), env);
147   }
148
149   // Methode pour le controle des jobs : renvoie l'etat du job
150   JobInfo BatchManager_PBS::queryJob(const JobId & jobid)
151   {
152     int id;
153     istringstream iss(jobid.getReference());
154     iss >> id;
155
156     // define command to query batch
157     string subCommand = string("qstat -f ") + iss.str();
158     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
159     cerr << command.c_str() << endl;
160
161     string output;
162     int status = Utils::getCommandOutput(command, output);
163     if(status && status != 153 && status != 256*153)
164       throw RunTimeException("Error of connection on remote host");
165
166     JobInfo_PBS ji = JobInfo_PBS(id, output);
167     return ji;
168   }
169
170   // Methode pour le controle des jobs : teste si un job est present en machine
171   bool BatchManager_PBS::isRunning(const JobId & jobid)
172   {
173     throw NotYetImplementedException("BatchManager_PBS::isRunning");
174   }
175
176   std::string BatchManager_PBS::buildSubmissionScript(const Job & job)
177   {
178     Parametre params = job.getParametre();
179     Environnement env = job.getEnvironnement();
180
181     // Mandatory parameters
182     string workDir;
183     if (params.find(WORKDIR) != params.end()) 
184       workDir = params[WORKDIR].str();
185     else 
186       throw RunTimeException("params[WORKDIR] is not defined ! Please defined it, cannot submit this job");
187     string fileToExecute;
188     if (params.find(EXECUTABLE) != params.end()) 
189       fileToExecute = params[EXECUTABLE].str();
190     else 
191       throw RunTimeException("params[EXECUTABLE] is not defined ! Please defined it, cannot submit this job");
192
193     // Optional parameters
194     int nbproc = 1;
195     if (params.find(NBPROC) != params.end())
196       nbproc = params[NBPROC];
197     int nbprocpernode = 1;
198     if (params.find(NBPROCPERNODE) != params.end())
199       nbprocpernode = params[NBPROCPERNODE];
200     int edt = 0;
201     if (params.find(MAXWALLTIME) != params.end()) 
202       edt = params[MAXWALLTIME];
203     int mem = 0;
204     if (params.find(MAXRAMSIZE) != params.end()) 
205       mem = params[MAXRAMSIZE];
206     string queue = "";
207     if (params.find(QUEUE) != params.end()) 
208       queue = params[QUEUE].str();
209
210     string::size_type p1 = fileToExecute.find_last_of("/");
211     string::size_type p2 = fileToExecute.find_last_of(".");
212     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
213     string fileNameToExecute = fileToExecute.substr(p1+1);
214
215     // Create batch submit file
216     ofstream tempOutputFile;
217     std::string TmpFileName = Utils::createAndOpenTemporaryFile("PBS-script", tempOutputFile);
218
219     tempOutputFile << "#! /bin/sh -f" << endl;
220     if (params.find(NAME) != params.end()) {
221       tempOutputFile << "#PBS -N " << params[NAME] << endl;
222     }
223
224     if (nbproc > 0)
225     {
226       int nb_full_nodes = nbproc / nbprocpernode;
227       int nb_proc_on_last_node = nbproc % nbprocpernode;
228
229       // In exclusive mode, we reserve all procs on the nodes
230       if (params.find(EXCLUSIVE) != params.end() && params[EXCLUSIVE] && nb_proc_on_last_node > 0) {
231         nb_full_nodes += 1;
232         nb_proc_on_last_node = 0;
233       }
234
235       tempOutputFile << "#PBS -l nodes=";
236
237       // Full nodes
238       if (nb_full_nodes > 0) {
239         tempOutputFile << nb_full_nodes << ":ppn=" << nbprocpernode;
240         if (nb_proc_on_last_node > 0) {
241           tempOutputFile << "+";
242         }
243       }
244
245       // Partly reserved node
246       if (nb_proc_on_last_node > 0) {
247         tempOutputFile << "1:ppn=" << nb_proc_on_last_node;
248       }
249
250       tempOutputFile << endl;
251     }
252     if (queue != "")
253       tempOutputFile << "#PBS -q " << queue << endl;
254     if( edt > 0 )
255       tempOutputFile << "#PBS -l walltime=" << edt*60 << endl;
256     if( mem > 0 )
257       tempOutputFile << "#PBS -l mem=" << mem << "MB" << endl;
258     tempOutputFile << "#PBS -o " << workDir << "/logs/output.log." << rootNameToExecute << endl;
259     tempOutputFile << "#PBS -e " << workDir << "/logs/error.log."  << rootNameToExecute << endl;
260
261     // Define environment for the job
262     if (!env.empty()) {
263       tempOutputFile << "#PBS -v ";
264       Environnement::const_iterator iter;
265       for (iter = env.begin() ; iter != env.end() ; ++iter) {
266         tempOutputFile << iter->first << "=" << iter->second << ",";
267       }
268       tempOutputFile << endl;
269     }
270
271     // Define NODEFILE
272     tempOutputFile << "export LIBBATCH_NODEFILE=$PBS_NODEFILE" << endl;
273
274     // Launch the executable
275     tempOutputFile << "cd " << workDir << endl;
276     tempOutputFile << "./" + fileNameToExecute << endl;
277     tempOutputFile.flush();
278     tempOutputFile.close();
279
280     cerr << "Batch script file generated is: " << TmpFileName.c_str() << endl;
281
282     string remoteFileName = rootNameToExecute + "_Batch.sh";
283     int status = _protocol.copyFile(TmpFileName, "", "",
284                                     workDir + "/" + remoteFileName,
285                                     _hostname, _username);
286     if (status)
287       throw RunTimeException("Error of connection on remote host, cannot copy batch submission file");
288     return remoteFileName;
289   }
290 }