Salome HOME
Fix remote directories in file transfer and merge some tests
[tools/libbatch.git] / src / CCC / Batch_BatchManager_eCCC.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_eCCC.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 #include <sys/stat.h>
40
41 #include <stdlib.h>
42 #include <string.h>
43
44 #ifdef WIN32
45 #include <io.h>
46 #else
47 #include <libgen.h>
48 #endif
49
50 #include <Batch_Constants.hxx>
51 #include <Batch_NotYetImplementedException.hxx>
52 #include <Batch_Utils.hxx>
53
54 #include "Batch_BatchManager_eCCC.hxx"
55 #include "Batch_JobInfo_eCCC.hxx"
56
57 using namespace std;
58
59 namespace Batch {
60
61   BatchManager_eCCC::BatchManager_eCCC(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_eCCC::~BatchManager_eCCC()
71   {
72     // Nothing to do
73   }
74
75   // Methode pour le controle des jobs : soumet un job au gestionnaire
76   const JobId BatchManager_eCCC::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     cerr << "Export des fichiers en entree" << endl;
87     exportInputFiles(job);
88
89     // build batch script for job
90     cerr << "Construction du script de batch" << endl;
91     buildBatchScript(job);
92     cerr << "Script envoye" << endl;
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     cerr << command.c_str() << endl;
99
100     // submit job
101     string output;
102     int status = Utils::getCommandOutput(command, output);
103     cout << 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   // Ce manager permet de faire de la reprise
121   const Batch::JobId
122   BatchManager_eCCC::addJob(const Batch::Job & job, const std::string reference)
123   {
124     return JobId(this, reference);
125   }
126
127   // Methode pour le controle des jobs : retire un job du gestionnaire
128   void BatchManager_eCCC::deleteJob(const JobId & jobid)
129   {
130     int status;
131     int ref;
132     istringstream iss(jobid.getReference());
133     iss >> ref;
134
135     // define command to delete batch
136     string subCommand = string("bash -l -c \\\"ccc_mdel ") + iss.str() + string("\\\"");
137     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
138     cerr << command.c_str() << endl;
139     status = system(command.c_str());
140     if (status)
141       throw RunTimeException("Error of connection on remote host");
142
143     cerr << "jobId = " << ref << "killed" << endl;
144   }
145
146   // Methode pour le controle des jobs : suspend un job en file d'attente
147   void BatchManager_eCCC::holdJob(const JobId & jobid)
148   {
149     throw NotYetImplementedException("BatchManager_eCCC::holdJob");
150   }
151
152   // Methode pour le controle des jobs : relache un job suspendu
153   void BatchManager_eCCC::releaseJob(const JobId & jobid)
154   {
155     throw NotYetImplementedException("BatchManager_eCCC::releaseJob");
156   }
157
158
159   // Methode pour le controle des jobs : modifie un job en file d'attente
160   void BatchManager_eCCC::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
161   {
162     throw NotYetImplementedException("BatchManager_eCCC::alterJob");
163   }
164
165   // Methode pour le controle des jobs : modifie un job en file d'attente
166   void BatchManager_eCCC::alterJob(const JobId & jobid, const Parametre & param)
167   {
168     alterJob(jobid, param, Environnement());
169   }
170
171   // Methode pour le controle des jobs : modifie un job en file d'attente
172   void BatchManager_eCCC::alterJob(const JobId & jobid, const Environnement & env)
173   {
174     alterJob(jobid, Parametre(), env);
175   }
176
177   // Methode pour le controle des jobs : renvoie l'etat du job
178   JobInfo BatchManager_eCCC::queryJob(const JobId & jobid)
179   {
180     int id;
181     istringstream iss(jobid.getReference());
182     iss >> id;
183
184     // define command to query batch
185     string subCommand = string("bash -l -c \\\"bjobs ") + iss.str() + string("\\\"");
186     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
187     cerr << command.c_str() << endl;
188
189     string output;
190     int status = Utils::getCommandOutput(command, output);
191     if (status)
192       throw RunTimeException("Error of connection on remote host");
193
194     JobInfo_eCCC ji = JobInfo_eCCC(id, output);
195     return ji;
196   }
197
198
199
200   // Methode pour le controle des jobs : teste si un job est present en machine
201   bool BatchManager_eCCC::isRunning(const JobId & jobid)
202   {
203     throw NotYetImplementedException("BatchManager_eCCC::isRunning");
204   }
205
206   void BatchManager_eCCC::buildBatchScript(const Job & job)
207   {
208 #ifndef WIN32 //TODO: need for porting on Windows
209     Parametre params = job.getParametre();
210
211     // Job Parameters
212     string workDir       = "";
213     string fileToExecute = "";
214     int nbproc           = 0;
215     int edt              = 0;
216     int mem              = 0;
217     string queue         = "";
218
219     // Mandatory parameters
220     if (params.find(WORKDIR) != params.end()) 
221       workDir = params[WORKDIR].str();
222     else 
223       throw RunTimeException("params[WORKDIR] is not defined ! Please defined it, cannot submit this job");
224     if (params.find(EXECUTABLE) != params.end()) 
225       fileToExecute = params[EXECUTABLE].str();
226     else 
227       throw RunTimeException("params[EXECUTABLE] is not defined ! Please defined it, cannot submit this job");
228
229     // Optional parameters
230     if (params.find(NBPROC) != params.end()) 
231       nbproc = params[NBPROC];
232     if (params.find(MAXWALLTIME) != params.end()) 
233       edt = (long)params[MAXWALLTIME] * 60;
234     if (params.find(MAXRAMSIZE) != params.end()) 
235       mem = params[MAXRAMSIZE];
236     if (params.find(QUEUE) != params.end()) 
237       queue = params[QUEUE].str();
238
239     string::size_type p1 = fileToExecute.find_last_of("/");
240     string::size_type p2 = fileToExecute.find_last_of(".");
241     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
242     string fileNameToExecute = fileToExecute.substr(p1+1);
243  
244     // Create batch submit file
245     ofstream tempOutputFile;
246     std::string TmpFileName = Utils::createAndOpenTemporaryFile("LSF-script", tempOutputFile);
247
248     tempOutputFile << "#!/bin/bash" << endl ;
249     if (queue != "")
250       tempOutputFile << "#MSUB -q " << queue << endl;
251     if( edt > 0 )
252       tempOutputFile << "#MSUB -T " << edt << endl ;
253     if( mem > 0 )
254       tempOutputFile << "#MSUB -M " << mem << endl ;
255     tempOutputFile << "#MSUB -n " << nbproc << endl ;
256     size_t pos = workDir.find("$HOME");
257     string baseDir;
258     if( pos != string::npos )
259       baseDir = getHomeDir(workDir) + workDir.substr(pos+5,workDir.length()-5);
260     else{
261       pos = workDir.find("~");
262       if( pos != string::npos )
263         baseDir = getHomeDir(workDir) + workDir.substr(pos+1,workDir.length()-1);
264       else
265         baseDir = workDir;
266     }
267     tempOutputFile << "#MSUB -o " << baseDir << "/logs/output.log." << rootNameToExecute << endl ;
268     tempOutputFile << "#MSUB -e " << baseDir << "/logs/error.log." << rootNameToExecute << endl ;
269
270     tempOutputFile << "cd " << workDir << endl ;
271
272     // generate nodes file
273     tempOutputFile << "bool=0" << endl;
274     tempOutputFile << "for i in $LSB_MCPU_HOSTS; do" << endl;
275     tempOutputFile << "  if test $bool = 0; then" << endl;
276     tempOutputFile << "    n=$i" << endl;
277     tempOutputFile << "    bool=1" << endl;
278     tempOutputFile << "  else" << endl;
279     tempOutputFile << "    for ((j=0;j<$i;j++)); do" << endl;
280     tempOutputFile << "      echo $n >> nodesFile." << rootNameToExecute << endl;
281     tempOutputFile << "    done" << endl;
282     tempOutputFile << "    bool=0" << endl;
283     tempOutputFile << "  fi" << endl;
284     tempOutputFile << "done" << endl;
285
286     // Abstraction of PBS_NODEFILE - TODO
287     tempOutputFile << "export LIBBATCH_NODEFILE=nodesFile." << rootNameToExecute << endl;
288
289     // Allow resource sharing in CCRT nodes
290     tempOutputFile << "export OMPI_MCA_orte_process_binding=none" << endl;
291
292     // Launch the executable
293     tempOutputFile << "./" + fileNameToExecute << endl;
294     tempOutputFile.flush();
295     tempOutputFile.close();
296
297     BATCH_CHMOD(TmpFileName.c_str(), 0x1ED);
298     cerr << "Batch script file generated is: " << TmpFileName.c_str() << endl;
299
300     int status = _protocol.copyFile(TmpFileName, "", "",
301                                     workDir + "/" + rootNameToExecute + "_Batch.sh",
302                                     _hostname, _username);
303     if (status)
304       throw RunTimeException("Error of connection on remote host");
305
306 #endif
307
308   }
309
310   std::string BatchManager_eCCC::getHomeDir(std::string tmpdir)
311   {
312     std::string home;
313
314     string subCommand = string("echo ");
315     subCommand += tmpdir;
316     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
317     cerr << command.c_str() << endl;
318
319     string output;
320     int status = Utils::getCommandOutput(command, output);
321
322     if (status)
323       throw RunTimeException("Error of launching home command on remote host");
324
325     std::istringstream file_home(output);
326     std::getline(file_home, home);
327     return home;
328   }
329
330 }