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