Salome HOME
927f3cec315bfa2d589f4d44e32e95482ec666e2
[tools/libbatch.git] / src / Vishnu / Batch_BatchManager_eVishnu.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  *  Batch_BatchManager_eVishnu.cxx :
24  *
25  *  Created on: 24 june 2011
26  *  Author : Renaud BARATE - EDF R&D
27  */
28
29 #ifndef WIN32
30 #include <unistd.h>
31 #endif
32
33 #include <cstdlib>
34 #include <iostream>
35 #include <fstream>
36 #include <sstream>
37
38 #include <Batch_NotYetImplementedException.hxx>
39 #include <Batch_Constants.hxx>
40 #include <Batch_Utils.hxx>
41
42 #include "Batch_BatchManager_eVishnu.hxx"
43 #include "Batch_JobInfo_eVishnu.hxx"
44
45 using namespace std;
46
47 namespace Batch {
48
49   BatchManager_eVishnu::BatchManager_eVishnu(const FactBatchManager * parent,
50                                              const char * host,
51                                              const char * username,
52                                              CommunicationProtocolType protocolType,
53                                              const char * mpiImpl)
54     : // Force SH protocol for Vishnu
55       BatchManager(parent, host, username, SH, mpiImpl)
56   {
57   }
58
59   BatchManager_eVishnu::~BatchManager_eVishnu()
60   {
61   }
62
63   // Method to submit a job to the batch manager
64   const JobId BatchManager_eVishnu::submitJob(const Job & job)
65   {
66     // export input files on cluster
67     exportInputFiles(job);
68
69     // build command file to submit the job
70     string cmdFile = buildCommandFile(job);
71
72     // define extra parameters (that can not be defined in the command file)
73     Parametre params = job.getParametre();
74     ostringstream extraParams;
75     if (params.find(NBPROC) != params.end())
76       extraParams << "-P " << params[NBPROC] << " ";
77     if (params.find(MAXRAMSIZE) != params.end())
78       extraParams << "-m " << params[MAXRAMSIZE] << " ";
79
80     // define command to submit batch
81     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
82     subCommand += "vishnu_connect && ";
83     subCommand += "vishnu_submit_job " + extraParams.str() + _hostname + " " + cmdFile + " && ";
84     subCommand += "vishnu_close";
85     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
86     command += " 2>&1";
87     cerr << command.c_str() << endl;
88
89     // submit job
90     string output;
91     int status = Utils::getCommandOutput(command, output);
92     cout << output;
93     if (status != 0) throw RunTimeException("Can't submit job, error was: " + output);
94
95     // find id of submitted job in output
96     string search = "Job Id     : ";
97     string::size_type pos = output.find(search);
98     if (pos == string::npos)
99       throw RunTimeException("Error in the submission of the job on the remote host");
100     pos += search.size();
101     string::size_type endl_pos = output.find('\n', pos);
102     string::size_type count = (endl_pos == string::npos)? string::npos : endl_pos - pos;
103     string jobref = output.substr(pos, count);
104     if (jobref.size() == 0)
105       throw RunTimeException("Error in the submission of the job on the remote host");
106
107     JobId id(this, jobref);
108     return id;
109   }
110
111
112   void BatchManager_eVishnu::exportInputFiles(const Job& job)
113   {
114     Parametre params = job.getParametre();
115     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
116     subCommand += "vishnu_connect && ";
117
118     // create remote directories
119     subCommand += "vishnu_create_dir -p " + _hostname + ":" + params[WORKDIR].str() + "/logs && ";
120
121     // copy executable
122     string executeFile = params[EXECUTABLE];
123     if (executeFile.size() != 0) {
124       subCommand += "vishnu_copy_file " + executeFile + " " +
125                     _hostname + ":" + params[WORKDIR].str() + "/ && ";
126     }
127
128     // copy filesToExportList
129     const Versatile & V = params[INFILE];
130     Versatile::const_iterator Vit;
131     for (Vit=V.begin(); Vit!=V.end(); Vit++) {
132       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
133       Couple inputFile = cpt;
134
135       // Get absolute paths
136       char * buf = getcwd(NULL, 0);
137       string cwd = buf;
138       free(buf);
139
140       string absremote = (Utils::isAbsolutePath(inputFile.getRemote()))?
141                          inputFile.getRemote() :
142                          params[WORKDIR].str() + "/" + inputFile.getRemote();
143       string abslocal = (Utils::isAbsolutePath(inputFile.getLocal()))?
144                         inputFile.getLocal() :
145                         cwd + "/" + inputFile.getLocal();
146
147       if (Vit != V.begin())
148         subCommand += " && ";
149       subCommand += "vishnu_copy_file " + abslocal + " " + _hostname + ":" + absremote;
150     }
151     subCommand += " && vishnu_close";
152
153     // Execute command
154     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
155     command += " 2>&1";
156     cerr << command.c_str() << endl;
157     string output;
158     int status = Utils::getCommandOutput(command, output);
159     cout << output;
160     if (status != 0)
161       throw RunTimeException("Can't copy input files, error was: " + output);
162   }
163
164   /**
165    * Create Vishnu command file and copy it on the server.
166    * Return the name of the remote file.
167    */
168   string BatchManager_eVishnu::buildCommandFile(const Job & job)
169   {
170     Parametre params = job.getParametre();
171
172     // Job Parameters
173     string workDir = "";
174     string fileToExecute = "";
175     string queue = "";
176
177     // Mandatory parameters
178     if (params.find(WORKDIR) != params.end()) 
179       workDir = params[WORKDIR].str();
180     else 
181       throw RunTimeException("params[WORKDIR] is not defined. Please define it, cannot submit this job.");
182     if (params.find(EXECUTABLE) != params.end()) 
183       fileToExecute = params[EXECUTABLE].str();
184     else 
185       throw RunTimeException("params[EXECUTABLE] is not defined. Please define it, cannot submit this job.");
186
187     string::size_type p1 = fileToExecute.find_last_of("/");
188     string::size_type p2 = fileToExecute.find_last_of(".");
189     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
190     string fileNameToExecute = fileToExecute.substr(p1+1);
191
192     // Create batch submit file
193     ofstream tempOutputFile;
194     string tmpFileName = Utils::createAndOpenTemporaryFile("vishnu-script", tempOutputFile);
195
196     tempOutputFile << "#!/bin/sh" << endl;
197     tempOutputFile << "#% vishnu_output=" << workDir << "/logs/output.log." << rootNameToExecute << endl;
198     tempOutputFile << "#% vishnu_error=" << workDir << "/logs/error.log." << rootNameToExecute << endl;
199
200     if (params.find(NAME) != params.end())
201       tempOutputFile << "#% vishnu_job_name=\"" << params[NAME] << "\"" << endl;
202
203     // Optional parameters
204     if (params.find(MAXWALLTIME) != params.end()) {
205       long totalMinutes = params[MAXWALLTIME];
206       long h = totalMinutes / 60;
207       long m = totalMinutes - h * 60;
208       tempOutputFile << "#% vishnu_wallclocklimit=" << h << ":";
209       if (m < 10)
210         tempOutputFile << "0";
211       tempOutputFile << m << ":00" << endl;
212     }
213     if (params.find(QUEUE) != params.end())
214       tempOutputFile << "#% vishnu_queue=" << params[QUEUE] << endl;
215
216     // Define environment for the job
217     Environnement env = job.getEnvironnement();
218     for (Environnement::const_iterator iter = env.begin() ; iter != env.end() ; ++iter) {
219       tempOutputFile << "export " << iter->first << "=" << iter->second << endl;
220     }
221
222     // Node file
223     tempOutputFile << "export LIBBATCH_NODEFILE=$VISHNU_BATCHJOB_NODEFILE" << endl;
224
225     // Launch the executable
226     tempOutputFile << "cd " << workDir << endl;
227     tempOutputFile << "./" + fileNameToExecute << endl;
228
229     tempOutputFile.flush();
230     tempOutputFile.close();
231
232     cerr << "Batch script file generated is: " << tmpFileName << endl;
233     return tmpFileName;
234   }
235
236   void BatchManager_eVishnu::deleteJob(const JobId & jobid)
237   {
238     // define command to delete job
239     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
240     subCommand += "vishnu_connect && ";
241     subCommand += "vishnu_cancel_job " + _hostname + " " + jobid.getReference() + " && ";
242     subCommand += "vishnu_close";
243     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
244     cerr << command.c_str() << endl;
245
246     int status = system(command.c_str());
247     if (status)
248       throw RunTimeException("Can't delete job " + jobid.getReference());
249
250     cerr << "job " << jobid.getReference() << " killed" << endl;
251   }
252
253   void BatchManager_eVishnu::holdJob(const JobId & jobid)
254   {
255     throw NotYetImplementedException("BatchManager_eVishnu::holdJob");
256   }
257
258   void BatchManager_eVishnu::releaseJob(const JobId & jobid)
259   {
260     throw NotYetImplementedException("BatchManager_eVishnu::releaseJob");
261   }
262
263   void BatchManager_eVishnu::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
264   {
265     throw NotYetImplementedException("BatchManager_eVishnu::alterJob");
266   }
267
268   void BatchManager_eVishnu::alterJob(const JobId & jobid, const Parametre & param)
269   {
270     throw NotYetImplementedException("BatchManager_eVishnu::alterJob");
271   }
272
273   void BatchManager_eVishnu::alterJob(const JobId & jobid, const Environnement & env)
274   {
275     throw NotYetImplementedException("BatchManager_eVishnu::alterJob");
276   }
277
278   JobInfo BatchManager_eVishnu::queryJob(const JobId & jobid)
279   {
280     // define command to query batch
281     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
282     subCommand += "vishnu_connect && ";
283     subCommand += "vishnu_get_job_info " + _hostname + " " + jobid.getReference() + " && ";
284     subCommand += "vishnu_close";
285     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
286     cerr << command.c_str() << endl;
287
288     string output;
289     int status = Utils::getCommandOutput(command, output);
290     if (status != 0)
291       throw RunTimeException("Can't query job " + jobid.getReference());
292     JobInfo_eVishnu jobinfo = JobInfo_eVishnu(jobid.getReference(), output);
293     return jobinfo;
294   }
295
296   const JobId BatchManager_eVishnu::addJob(const Job & job, const string reference)
297   {
298     return JobId(this, reference);
299   }
300
301   void BatchManager_eVishnu::importOutputFiles(const Job & job, const std::string directory)
302   {
303     // Create local result directory
304     char * buf = getcwd(NULL, 0);
305     string cwd = buf;
306     free(buf);
307     string absdir = (Utils::isAbsolutePath(directory))? directory : cwd + "/" + directory;
308     int status = CommunicationProtocol::getInstance(SH).makeDirectory(absdir, "", "");
309     if (status != 0) {
310       throw RunTimeException("Can't create result directory");
311     }
312
313     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
314     subCommand += "vishnu_connect && ";
315
316     // Copy output files
317     Parametre params = job.getParametre();
318     const Versatile & V = params[OUTFILE];
319     Versatile::const_iterator Vit;
320     for (Vit=V.begin(); Vit!=V.end(); Vit++) {
321       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
322       Couple outputFile = cpt;
323
324       // Get absolute paths
325       string absremote = (Utils::isAbsolutePath(outputFile.getRemote()))?
326                          outputFile.getRemote() :
327                          params[WORKDIR].str() + "/" + outputFile.getRemote();
328       string abslocal = (Utils::isAbsolutePath(outputFile.getLocal()))?
329                         outputFile.getLocal() :
330                         absdir + "/" + outputFile.getLocal();
331
332       subCommand += "vishnu_copy_file " + _hostname + ":" + absremote + " " + abslocal + " && ";
333     }
334
335     // Copy logs
336     subCommand += "vishnu_copy_file -r " +_hostname + ":" + params[WORKDIR].str() + "/logs" + " " + absdir + " && ";
337     subCommand += "vishnu_close";
338
339     // Execute command
340     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
341     command += " 2>&1";
342     cerr << command.c_str() << endl;
343     string output;
344     status = Utils::getCommandOutput(command, output);
345     cout << output;
346     if (status != 0)
347       throw RunTimeException("Can't import output files, error was: " + output);
348   }
349
350 }