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