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