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