Salome HOME
bb890364b118f7908bc4e89baa991fcac27b05b7
[tools/libbatch.git] / src / CCC / Batch_BatchManager_eCCC.cxx
1 //  Copyright (C) 2007-2011  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_BatchManager_eCCC.hxx"
52 #include "Batch_JobInfo_eCCC.hxx"
53
54 using namespace std;
55
56 namespace Batch {
57
58   BatchManager_eCCC::BatchManager_eCCC(const FactBatchManager * parent, const char * host,
59                                        const char * username,
60                                        CommunicationProtocolType protocolType, const char * mpiImpl)
61   : BatchManager(parent, host),
62     BatchManager_eClient(parent, host, username, protocolType, mpiImpl)
63   {
64     // Nothing to do
65   }
66
67   // Destructeur
68   BatchManager_eCCC::~BatchManager_eCCC()
69   {
70     // Nothing to do
71   }
72
73   // Methode pour le controle des jobs : soumet un job au gestionnaire
74   const JobId BatchManager_eCCC::submitJob(const Job & job)
75   {
76     int status;
77     Parametre params = job.getParametre();
78     const std::string workDir = params[WORKDIR];
79     const string fileToExecute = params[EXECUTABLE];
80     string::size_type p1 = fileToExecute.find_last_of("/");
81     string::size_type p2 = fileToExecute.find_last_of(".");
82     std::string fileNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
83
84     // export input files on cluster
85     cerr << "Export des fichiers en entree" << endl;
86     exportInputFiles(job);
87
88     // build batch script for job
89     cerr << "Construction du script de batch" << endl;
90     buildBatchScript(job);
91     cerr << "Script envoye" << endl;
92
93     // define name of log file (local)
94     string logFile = generateTemporaryFileName("CCC-submitlog");
95
96     // define command to submit batch
97     string subCommand = string('bash -l -c "cd ') + workDir + '; ccc_msub ' + fileNameToExecute + '_Batch.sh"';
98     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
99     command += " > ";
100     command += logFile;
101     command += " 2>&1";
102     cerr << command.c_str() << endl;
103     status = system(command.c_str());
104     if(status)
105     {
106       ifstream error_message(logFile.c_str());
107       std::string mess;
108       std::string temp;
109       while(std::getline(error_message, temp))
110         mess += temp;
111       error_message.close();
112       throw EmulationException("Error of connection on remote host, error was: " + mess);
113     }
114
115     // read id of submitted job in log file
116     ifstream idfile(logFile.c_str());
117     string sidj;
118     idfile >> sidj;
119     idfile >> sidj;
120     idfile >> sidj;
121     idfile >> sidj;
122     idfile.close();
123     if (sidj.size() == 0)
124       throw EmulationException("Error in the submission of the job on the remote host");
125
126     JobId id(this, sidj);
127     return id;
128   }
129
130   // Ce manager permet de faire de la reprise
131   const Batch::JobId
132   BatchManager_eCCC::addJob(const Batch::Job & job, const std::string reference)
133   {
134     return JobId(this, reference);
135   }
136
137   // Methode pour le controle des jobs : retire un job du gestionnaire
138   void BatchManager_eCCC::deleteJob(const JobId & jobid)
139   {
140     int status;
141     int ref;
142     istringstream iss(jobid.getReference());
143     iss >> ref;
144
145     // define command to delete batch
146     string subCommand = string('bash -l -c "ccc_mdel ') + iss.str() + string('"');
147     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
148     cerr << command.c_str() << endl;
149     status = system(command.c_str());
150     if (status)
151       throw EmulationException("Error of connection on remote host");
152
153     cerr << "jobId = " << ref << "killed" << endl;
154   }
155
156   // Methode pour le controle des jobs : suspend un job en file d'attente
157   void BatchManager_eCCC::holdJob(const JobId & jobid)
158   {
159     throw EmulationException("Not yet implemented");
160   }
161
162   // Methode pour le controle des jobs : relache un job suspendu
163   void BatchManager_eCCC::releaseJob(const JobId & jobid)
164   {
165     throw EmulationException("Not yet implemented");
166   }
167
168
169   // Methode pour le controle des jobs : modifie un job en file d'attente
170   void BatchManager_eCCC::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
171   {
172     throw EmulationException("Not yet implemented");
173   }
174
175   // Methode pour le controle des jobs : modifie un job en file d'attente
176   void BatchManager_eCCC::alterJob(const JobId & jobid, const Parametre & param)
177   {
178     alterJob(jobid, param, Environnement());
179   }
180
181   // Methode pour le controle des jobs : modifie un job en file d'attente
182   void BatchManager_eCCC::alterJob(const JobId & jobid, const Environnement & env)
183   {
184     alterJob(jobid, Parametre(), env);
185   }
186
187   // Methode pour le controle des jobs : renvoie l'etat du job
188   JobInfo BatchManager_eCCC::queryJob(const JobId & jobid)
189   {
190     int id;
191     istringstream iss(jobid.getReference());
192     iss >> id;
193
194     // define name of log file (local)
195     string logFile = generateTemporaryFileName(string("CCC-querylog-id") + jobid.getReference());
196
197     // define command to query batch
198     string subCommand = string("bjobs ") + iss.str();
199     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
200     command += " > ";
201     command += logFile;
202     cerr << command.c_str() << endl;
203     int status = system(command.c_str());
204     if (status)
205       throw EmulationException("Error of connection on remote host");
206
207     JobInfo_eCCC ji = JobInfo_eCCC(id,logFile);
208     return ji;
209   }
210
211
212
213   // Methode pour le controle des jobs : teste si un job est present en machine
214   bool BatchManager_eCCC::isRunning(const JobId & jobid)
215   {
216     throw EmulationException("Not yet implemented");
217   }
218
219   void BatchManager_eCCC::buildBatchScript(const Job & job)
220   {
221 #ifndef WIN32 //TODO: need for porting on Windows
222     Parametre params = job.getParametre();
223
224     // Job Parameters
225     string workDir       = "";
226     string fileToExecute = "";
227     int nbproc           = 0;
228     int edt              = 0;
229     int mem              = 0;
230     string queue         = "";
231
232     // Mandatory parameters
233     if (params.find(WORKDIR) != params.end()) 
234       workDir = params[WORKDIR].str();
235     else 
236       throw EmulationException("params[WORKDIR] is not defined ! Please defined it, cannot submit this job");
237     if (params.find(EXECUTABLE) != params.end()) 
238       fileToExecute = params[EXECUTABLE].str();
239     else 
240       throw EmulationException("params[EXECUTABLE] is not defined ! Please defined it, cannot submit this job");
241
242     // Optional parameters
243     if (params.find(NBPROC) != params.end()) 
244       nbproc = params[NBPROC];
245     if (params.find(MAXWALLTIME) != params.end()) 
246       edt = (long)params[MAXWALLTIME] * 60;
247     if (params.find(MAXRAMSIZE) != params.end()) 
248       mem = params[MAXRAMSIZE];
249     if (params.find(QUEUE) != params.end()) 
250       queue = params[QUEUE].str();
251
252     string::size_type p1 = fileToExecute.find_last_of("/");
253     string::size_type p2 = fileToExecute.find_last_of(".");
254     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
255     string fileNameToExecute = fileToExecute.substr(p1+1);
256  
257     // Create batch submit file
258     ofstream tempOutputFile;
259     std::string TmpFileName = createAndOpenTemporaryFile("LSF-script", tempOutputFile);
260
261     tempOutputFile << "#!/bin/bash" << endl ;
262     if (queue != "")
263       tempOutputFile << "#MSUB -q " << queue << endl;
264     if( edt > 0 )
265       tempOutputFile << "#MSUB -T " << edt << endl ;
266     if( mem > 0 )
267       tempOutputFile << "#MSUB -M " << mem << endl ;
268     tempOutputFile << "#MSUB -n " << nbproc << endl ;
269     size_t pos = workDir.find("$HOME");
270     string baseDir;
271     if( pos != string::npos )
272       baseDir = getHomeDir(workDir) + workDir.substr(pos+5,workDir.length()-5);
273     else{
274       pos = workDir.find("~");
275       if( pos != string::npos )
276         baseDir = getHomeDir(workDir) + workDir.substr(pos+1,workDir.length()-1);
277       else
278         baseDir = workDir;
279     }
280     tempOutputFile << "#MSUB -o " << baseDir << "/logs/output.log." << rootNameToExecute << endl ;
281     tempOutputFile << "#MSUB -e " << baseDir << "/logs/error.log." << rootNameToExecute << endl ;
282
283     tempOutputFile << "cd " << workDir << endl ;
284
285     // generate nodes file
286     tempOutputFile << "bool=0" << endl;
287     tempOutputFile << "for i in $LSB_MCPU_HOSTS; do" << endl;
288     tempOutputFile << "  if test $bool = 0; then" << endl;
289     tempOutputFile << "    n=$i" << endl;
290     tempOutputFile << "    bool=1" << endl;
291     tempOutputFile << "  else" << endl;
292     tempOutputFile << "    for ((j=0;j<$i;j++)); do" << endl;
293     tempOutputFile << "      echo $n >> nodesFile." << rootNameToExecute << endl;
294     tempOutputFile << "    done" << endl;
295     tempOutputFile << "    bool=0" << endl;
296     tempOutputFile << "  fi" << endl;
297     tempOutputFile << "done" << endl;
298
299     // Abstraction of PBS_NODEFILE - TODO
300     tempOutputFile << "export LIBBATCH_NODEFILE=nodesFile." << rootNameToExecute << endl;
301
302     // Allow resource sharing in CCRT nodes
303     tempOutputFile << "export OMPI_MCA_orte_process_binding=none" << endl;
304
305     // Launch the executable
306     tempOutputFile << "./" + fileNameToExecute << endl;
307     tempOutputFile.flush();
308     tempOutputFile.close();
309
310     BATCH_CHMOD(TmpFileName.c_str(), 0x1ED);
311     cerr << "Batch script file generated is: " << TmpFileName.c_str() << endl;
312
313     int status = _protocol.copyFile(TmpFileName, "", "",
314                                     workDir + "/" + rootNameToExecute + "_Batch.sh",
315                                     _hostname, _username);
316     if (status)
317       throw EmulationException("Error of connection on remote host");
318
319 #endif
320
321   }
322
323   std::string BatchManager_eCCC::getHomeDir(std::string tmpdir)
324   {
325     std::string home;
326     int idx = tmpdir.find("Batch/");
327     std::string filelogtemp = tmpdir.substr(idx+6, tmpdir.length());
328     filelogtemp = "/tmp/logs" + filelogtemp + "_home";
329
330     string subCommand = string("echo $HOME");
331     string command = _protocol.getExecCommand(subCommand, _hostname, _username) + " > " + filelogtemp;
332     cerr << command.c_str() << endl;
333     int status = system(command.c_str());
334     if (status)
335       throw EmulationException("Error of launching home command on remote host");
336
337     std::ifstream file_home(filelogtemp.c_str());
338     std::getline(file_home, home);
339     file_home.close();
340     return home;
341   }
342
343 }