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