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