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