Salome HOME
c4f5bc5801db6bf1c2694aa78853a14c236444d2
[tools/libbatch.git] / src / CCC / BatchManager_CCC.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_CCC.cxx : emulation of CCC client for CCRT machines
24  *
25  * Auteur : Bernard SECHER - CEA DEN
26  * Mail   : mailto:bernard.secher@cea.fr
27  * Date   : Thu Apr 24 10:17:22 2010
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 <string>
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 <Constants.hxx>
50 #include <NotYetImplementedException.hxx>
51 #include <Utils.hxx>
52
53 #include "BatchManager_CCC.hxx"
54 #include "JobInfo_CCC.hxx"
55 #include "Log.hxx"
56
57 using namespace std;
58
59 namespace Batch {
60
61   BatchManager_CCC::BatchManager_CCC(const FactBatchManager * parent, const char * host,
62                                        const char * username,
63                                        CommunicationProtocolType protocolType, const char * mpiImpl)
64   : BatchManager(parent, host, username, protocolType, mpiImpl)
65   {
66     // Nothing to do
67   }
68
69   // Destructeur
70   BatchManager_CCC::~BatchManager_CCC()
71   {
72     // Nothing to do
73   }
74
75   // Methode pour le controle des jobs : soumet un job au gestionnaire
76   const JobId BatchManager_CCC::submitJob(const Job & job)
77   {
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     LOG("Export des fichiers en entree");
87     exportInputFiles(job);
88
89     // build batch script for job
90     LOG("Construction du script de batch");
91     buildBatchScript(job);
92     LOG("Script envoye");
93
94     // define command to submit batch
95     string subCommand = string("bash -l -c \\\"cd ") + workDir + "; ccc_msub " + fileNameToExecute + "_Batch.sh\\\"";
96     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
97     command += " 2>&1";
98     LOG(command);
99
100     // submit job
101     string output;
102     int status = Utils::getCommandOutput(command, output);
103     LOG(output);
104     if (status != 0) throw RunTimeException("Can't submit job, error was: " + output);
105
106     // find id of submitted job in output
107     istringstream idfile(output);
108     string sidj;
109     idfile >> sidj;
110     idfile >> sidj;
111     idfile >> sidj;
112     idfile >> sidj;
113     if (sidj.size() == 0)
114       throw RunTimeException("Error in the submission of the job on the remote host");
115
116     JobId id(this, sidj);
117     return id;
118   }
119
120   // Methode pour le controle des jobs : retire un job du gestionnaire
121   void BatchManager_CCC::deleteJob(const JobId & jobid)
122   {
123     int status;
124     int ref;
125     istringstream iss(jobid.getReference());
126     iss >> ref;
127
128     // define command to delete batch
129     string subCommand = string("bash -l -c \\\"ccc_mdel ") + iss.str() + string("\\\"");
130     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
131     LOG(command);
132     status = system(command.c_str());
133     if (status)
134       throw RunTimeException("Error of connection on remote host");
135
136     LOG("jobId = " << ref << "killed");
137   }
138
139   // Methode pour le controle des jobs : renvoie l'etat du job
140   JobInfo BatchManager_CCC::queryJob(const JobId & jobid)
141   {
142     int id;
143     istringstream iss(jobid.getReference());
144     iss >> id;
145
146     // define command to query batch
147     string subCommand = string("bash -l -c \\\"bjobs ") + iss.str() + string("\\\"");
148     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
149     LOG(command);
150
151     string output;
152     int status = Utils::getCommandOutput(command, output);
153     if (status)
154       throw RunTimeException("Error of connection on remote host");
155
156     JobInfo_CCC ji = JobInfo_CCC(id, output);
157     return ji;
158   }
159
160
161
162   // Methode pour le controle des jobs : teste si un job est present en machine
163   bool BatchManager_CCC::isRunning(const JobId & jobid)
164   {
165     throw NotYetImplementedException("BatchManager_CCC::isRunning");
166   }
167
168   void BatchManager_CCC::buildBatchScript(const Job & job)
169   {
170 #ifndef WIN32 //TODO: need for porting on Windows
171     Parametre params = job.getParametre();
172
173     // Job Parameters
174     string workDir       = "";
175     string fileToExecute = "";
176     int nbproc           = 0;
177     int edt              = 0;
178     int mem              = 0;
179     string queue         = "";
180
181     // Mandatory parameters
182     if (params.find(WORKDIR) != params.end()) 
183       workDir = params[WORKDIR].str();
184     else 
185       throw RunTimeException("params[WORKDIR] is not defined ! Please defined it, cannot submit this job");
186     if (params.find(EXECUTABLE) != params.end()) 
187       fileToExecute = params[EXECUTABLE].str();
188     else 
189       throw RunTimeException("params[EXECUTABLE] is not defined ! Please defined it, cannot submit this job");
190
191     // Optional parameters
192     if (params.find(NBPROC) != params.end()) 
193       nbproc = params[NBPROC];
194     if (params.find(MAXWALLTIME) != params.end()) 
195       edt = (long)params[MAXWALLTIME] * 60;
196     if (params.find(MAXRAMSIZE) != params.end()) 
197       mem = params[MAXRAMSIZE];
198     if (params.find(QUEUE) != params.end()) 
199       queue = params[QUEUE].str();
200
201     string::size_type p1 = fileToExecute.find_last_of("/");
202     string::size_type p2 = fileToExecute.find_last_of(".");
203     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
204     string fileNameToExecute = fileToExecute.substr(p1+1);
205  
206     // Create batch submit file
207     ofstream tempOutputFile;
208     std::string TmpFileName = Utils::createAndOpenTemporaryFile("LSF-script", tempOutputFile);
209
210     tempOutputFile << "#!/bin/bash" << endl ;
211     if (queue != "")
212       tempOutputFile << "#MSUB -q " << queue << endl;
213     if( edt > 0 )
214       tempOutputFile << "#MSUB -T " << edt << endl ;
215     if( mem > 0 )
216       tempOutputFile << "#MSUB -M " << mem << endl ;
217     tempOutputFile << "#MSUB -n " << nbproc << endl ;
218     size_t pos = workDir.find("$HOME");
219     string baseDir;
220     if( pos != string::npos )
221       baseDir = getHomeDir(workDir) + workDir.substr(pos+5,workDir.length()-5);
222     else{
223       pos = workDir.find("~");
224       if( pos != string::npos )
225         baseDir = getHomeDir(workDir) + workDir.substr(pos+1,workDir.length()-1);
226       else
227         baseDir = workDir;
228     }
229     tempOutputFile << "#MSUB -o " << baseDir << "/logs/output.log." << rootNameToExecute << endl ;
230     tempOutputFile << "#MSUB -e " << baseDir << "/logs/error.log." << rootNameToExecute << endl ;
231
232     if (params.find(EXTRAPARAMS) != params.end())
233       tempOutputFile << params[EXTRAPARAMS] << endl;
234
235     tempOutputFile << "cd " << workDir << endl ;
236
237     // generate nodes file
238     tempOutputFile << "bool=0" << endl;
239     tempOutputFile << "for i in $LSB_MCPU_HOSTS; do" << endl;
240     tempOutputFile << "  if test $bool = 0; then" << endl;
241     tempOutputFile << "    n=$i" << endl;
242     tempOutputFile << "    bool=1" << endl;
243     tempOutputFile << "  else" << endl;
244     tempOutputFile << "    for ((j=0;j<$i;j++)); do" << endl;
245     tempOutputFile << "      echo $n >> nodesFile." << rootNameToExecute << endl;
246     tempOutputFile << "    done" << endl;
247     tempOutputFile << "    bool=0" << endl;
248     tempOutputFile << "  fi" << endl;
249     tempOutputFile << "done" << endl;
250
251     // Abstraction of PBS_NODEFILE - TODO
252     tempOutputFile << "export LIBBATCH_NODEFILE=nodesFile." << rootNameToExecute << endl;
253
254     // Allow resource sharing in CCRT nodes
255     tempOutputFile << "export OMPI_MCA_orte_process_binding=none" << endl;
256
257     // Launch the executable
258     tempOutputFile << "./" + fileNameToExecute << endl;
259     tempOutputFile.flush();
260     tempOutputFile.close();
261
262     Utils::chmod(TmpFileName.c_str(), 0x1ED);
263     LOG("Batch script file generated is: " << TmpFileName.c_str());
264
265     int status = _protocol.copyFile(TmpFileName, "", "",
266                                     workDir + "/" + rootNameToExecute + "_Batch.sh",
267                                     _hostname, _username);
268     if (status)
269       throw RunTimeException("Error of connection on remote host");
270
271 #endif
272
273   }
274
275   std::string BatchManager_CCC::getHomeDir(std::string tmpdir)
276   {
277     std::string home;
278
279     string subCommand = string("echo ");
280     subCommand += tmpdir;
281     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
282     LOG(command);
283
284     string output;
285     int status = Utils::getCommandOutput(command, output);
286
287     if (status)
288       throw RunTimeException("Error of launching home command on remote host");
289
290     std::istringstream file_home(output);
291     std::getline(file_home, home);
292     return home;
293   }
294
295 }