Salome HOME
Merge from BR_DIET
[tools/libbatch.git] / src / Vishnu / Batch_BatchManager_eVishnu.cxx
1 //  Copyright (C) 2007-2011  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_FactBatchManager_eVishnu.hxx"
39 #include "Batch_BatchManager_eVishnu.hxx"
40 #include "Batch_JobInfo_eVishnu.hxx"
41
42 using namespace std;
43
44 namespace Batch {
45
46   BatchManager_eVishnu::BatchManager_eVishnu(const FactBatchManager * parent,
47                                              const char * host,
48                                              const char * username,
49                                              CommunicationProtocolType protocolType,
50                                              const char * mpiImpl,
51                                              int nb_proc_per_node)
52     : BatchManager(parent, host),
53       // Force SH protocol for Vishnu
54       BatchManager_eClient(parent, host, username, SH, mpiImpl),
55       _nb_proc_per_node(nb_proc_per_node)
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     int status;
67     Parametre params = job.getParametre();
68     const string workDir = params[WORKDIR];
69
70     // export input files on cluster
71     exportInputFiles(job);
72
73     // build command file to submit the job
74     string cmdFile = buildCommandFile(job);
75
76     // define name of log file (local)
77     string logFile = generateTemporaryFileName("vishnu-submitlog");
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 " + _hostname + " " + cmdFile;
83     string command = _protocol.getExecCommand(subCommand,
84                                               _hostname,
85                                               _username);
86     command += " > ";
87     command += logFile;
88     cerr << command.c_str() << endl;
89     status = system(command.c_str());
90     if (status)
91     {
92       ifstream error_message(logFile.c_str());
93       string mess;
94       string temp;
95       while(getline(error_message, temp))
96         mess += temp;
97       error_message.close();
98       throw EmulationException("Error of connection on remote host, error was: " + mess);
99     }
100
101     // read id of submitted job in log file
102     string jobref;
103     ifstream idfile(logFile.c_str());
104     string line;
105     while (idfile && line.compare(0, 13, "Job Id     : ") != 0)
106       getline(idfile, line);
107     idfile.close();
108     if (line.compare(0, 13, "Job Id     : ") == 0)
109       jobref = line.substr(13);
110     if (jobref.size() == 0)
111       throw EmulationException("Error in the submission of the job on the remote host");
112
113     JobId id(this, jobref);
114     return id;
115   }
116
117
118   void BatchManager_eVishnu::exportInputFiles(const Job& job)
119   {
120     int status;
121     Parametre params = job.getParametre();
122     const Versatile & V = params[INFILE];
123     Versatile::const_iterator Vit;
124
125     // create remote directories
126     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
127     subCommand += "vishnu_connect -p 2; ";
128     subCommand += "vishnu_create_dir -p " + _hostname + ":" + params[WORKDIR].str() + "/logs";
129     string command = _protocol.getExecCommand(subCommand,
130                                               _hostname,
131                                               _username);
132     cerr << command.c_str() << endl;
133     status = system(command.c_str());
134     if (status != 0)
135       throw EmulationException("Can't create remote directories");
136
137     // copy executable
138     string executeFile = params[EXECUTABLE];
139     if (executeFile.size() != 0) {
140
141       string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
142       subCommand += "vishnu_connect -p 2; ";
143       subCommand += "vishnu_copy_file " + executeFile + " " + _hostname + ":" + params[WORKDIR].str() + "/";
144       string command = _protocol.getExecCommand(subCommand,
145                                                 _hostname,
146                                                 _username);
147       cerr << command.c_str() << endl;
148       status = system(command.c_str());
149       if (status != 0)
150         throw EmulationException("Can't copy executable");
151     }
152
153     // copy filesToExportList
154     for (Vit=V.begin(); Vit!=V.end(); Vit++) {
155       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
156       Couple inputFile = cpt;
157
158       // Get absolute paths
159       char * buf = getcwd(NULL, 0);
160       string cwd = buf;
161       free(buf);
162
163       string absremote = (Utils::isAbsolutePath(inputFile.getRemote()))?
164                          inputFile.getRemote() :
165                          params[WORKDIR].str() + "/" + inputFile.getRemote();
166       string abslocal = (Utils::isAbsolutePath(inputFile.getLocal()))?
167                         inputFile.getLocal() :
168                         cwd + "/" + inputFile.getLocal();
169
170       string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
171       subCommand += "vishnu_connect -p 2; ";
172       subCommand += "vishnu_copy_file " + abslocal + " " + _hostname + ":" + absremote;
173       string command = _protocol.getExecCommand(subCommand,
174                                                 _hostname,
175                                                 _username);
176       cerr << command.c_str() << endl;
177       status = system(command.c_str());
178       if (status != 0)
179         throw EmulationException("Can't copy file");
180     }
181   }
182
183   /**
184    * Create Vishnu command file and copy it on the server.
185    * Return the name of the remote file.
186    */
187   string BatchManager_eVishnu::buildCommandFile(const Job & job)
188   {
189     Parametre params = job.getParametre();
190
191     // Job Parameters
192     string workDir = "";
193     string fileToExecute = "";
194     string queue = "";
195
196     // Mandatory parameters
197     if (params.find(WORKDIR) != params.end()) 
198       workDir = params[WORKDIR].str();
199     else 
200       throw EmulationException("params[WORKDIR] is not defined. Please define it, cannot submit this job.");
201     if (params.find(EXECUTABLE) != params.end()) 
202       fileToExecute = params[EXECUTABLE].str();
203     else 
204       throw EmulationException("params[EXECUTABLE] is not defined. Please define it, cannot submit this job.");
205
206     string::size_type p1 = fileToExecute.find_last_of("/");
207     string::size_type p2 = fileToExecute.find_last_of(".");
208     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
209     string fileNameToExecute = fileToExecute.substr(p1+1);
210
211     // Create batch submit file
212     ofstream tempOutputFile;
213     string tmpFileName = createAndOpenTemporaryFile("vishnu-script", tempOutputFile);
214
215     tempOutputFile << "#!/bin/sh" << endl;
216     tempOutputFile << "#% vishnu_output=" << workDir << "/logs/output.log." << rootNameToExecute << endl;
217     tempOutputFile << "#% vishnu_error=" << workDir << "/logs/error.log." << rootNameToExecute << endl;
218
219     if (params.find(NAME) != params.end())
220       tempOutputFile << "#% vishnu_job_name=\"" << params[NAME] << "\"" << endl;
221
222     // Optional parameters
223     int nbproc = 1;
224     if (params.find(NBPROC) != params.end())
225       nbproc = params[NBPROC];
226
227     //int nodes_requested = (nbproc + _nb_proc_per_node -1) / _nb_proc_per_node;
228     //tempOutputFile << "#SBATCH --nodes=" << nodes_requested << endl;
229     //tempOutputFile << "#SBATCH --ntasks-per-node=" << _nb_proc_per_node << endl;
230
231     if (params.find(MAXWALLTIME) != params.end()) {
232       long totalMinutes = params[MAXWALLTIME];
233       long h = totalMinutes / 60;
234       long m = totalMinutes - h * 60;
235       tempOutputFile << "#% vishnu_wallclocklimit=" << h << ":";
236       if (m < 10)
237         tempOutputFile << "0";
238       tempOutputFile << m << ":00" << endl;
239     }
240     //if (params.find(MAXRAMSIZE) != params.end())
241     //  tempOutputFile << "#SBATCH --mem=" << params[MAXRAMSIZE] << endl;
242     if (params.find(QUEUE) != params.end())
243       tempOutputFile << "#% vishnu_queue=" << params[QUEUE] << endl;
244
245     // Define environment for the job
246     Environnement env = job.getEnvironnement();
247     for (Environnement::const_iterator iter = env.begin() ; iter != env.end() ; ++iter) {
248       tempOutputFile << "export " << iter->first << "=" << iter->second << endl;
249     }
250
251     // generate nodes file
252     //tempOutputFile << "LIBBATCH_NODEFILE=`mktemp nodefile-XXXXXXXXXX`" << endl;
253     //tempOutputFile << "srun hostname > $LIBBATCH_NODEFILE" << endl;
254     //tempOutputFile << "export LIBBATCH_NODEFILE" << endl;
255
256     // Launch the executable
257     tempOutputFile << "cd " << workDir << endl;
258     tempOutputFile << "./" + fileNameToExecute << endl;
259
260     tempOutputFile.flush();
261     tempOutputFile.close();
262
263     cerr << "Batch script file generated is: " << tmpFileName << endl;
264     return tmpFileName;
265   }
266
267   void BatchManager_eVishnu::deleteJob(const JobId & jobid)
268   {
269     string vishnuJobId;
270     istringstream iss(jobid.getReference());
271     getline(iss, vishnuJobId, ':');
272
273     // define command to delete job
274     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
275     subCommand += "vishnu_connect -p 2; ";
276     subCommand += "vishnu_cancel_job " + _hostname + " " + vishnuJobId;
277     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
278     cerr << command.c_str() << endl;
279
280     int status = system(command.c_str());
281     if (status)
282       throw EmulationException("Can't delete job " + jobid.getReference());
283
284     cerr << "job " << jobid.getReference() << " killed" << endl;
285   }
286
287   void BatchManager_eVishnu::holdJob(const JobId & jobid)
288   {
289     throw NotYetImplementedException("BatchManager_eVishnu::holdJob");
290   }
291
292   void BatchManager_eVishnu::releaseJob(const JobId & jobid)
293   {
294     throw NotYetImplementedException("BatchManager_eVishnu::releaseJob");
295   }
296
297   void BatchManager_eVishnu::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
298   {
299     throw NotYetImplementedException("BatchManager_eVishnu::alterJob");
300   }
301
302   void BatchManager_eVishnu::alterJob(const JobId & jobid, const Parametre & param)
303   {
304     throw NotYetImplementedException("BatchManager_eVishnu::alterJob");
305   }
306
307   void BatchManager_eVishnu::alterJob(const JobId & jobid, const Environnement & env)
308   {
309     throw NotYetImplementedException("BatchManager_eVishnu::alterJob");
310   }
311
312   JobInfo BatchManager_eVishnu::queryJob(const JobId & jobid)
313   {
314     // define name of log file (local)
315     string logFile = generateTemporaryFileName("vishnu-querylog-" + jobid.getReference());
316
317     string vishnuJobId;
318     istringstream iss(jobid.getReference());
319     getline(iss, vishnuJobId, ':');
320
321     // define command to query batch
322     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
323     subCommand += "vishnu_connect -p 2; ";
324     subCommand += "vishnu_get_job_info " + _hostname + " " + vishnuJobId;
325     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
326     command += " > ";
327     command += logFile;
328     cerr << command.c_str() << endl;
329     int status = system(command.c_str());
330     if (status != 0)
331       throw EmulationException("Can't query job " + jobid.getReference());
332
333     JobInfo_eVishnu jobinfo = JobInfo_eVishnu(jobid.getReference(), logFile);
334     return jobinfo;
335   }
336
337   const JobId BatchManager_eVishnu::addJob(const Job & job, const string reference)
338   {
339     return JobId(this, reference);
340   }
341
342   void BatchManager_eVishnu::importOutputFiles(const Job & job, const std::string directory)
343   {
344     Parametre params = job.getParametre();
345     const Versatile & V = params[OUTFILE];
346     Versatile::const_iterator Vit;
347
348     // Create local result directory
349     char * buf = getcwd(NULL, 0);
350     string cwd = buf;
351     free(buf);
352     string absdir = (Utils::isAbsolutePath(directory))? directory : cwd + "/" + directory;
353     int status = CommunicationProtocol::getInstance(SH).makeDirectory(absdir, "", "");
354     if (status) {
355       string mess("Directory creation failed. Status is :");
356       ostringstream status_str;
357       status_str << status;
358       mess += status_str.str();
359       cerr << mess << endl;
360     }
361
362     for (Vit=V.begin(); Vit!=V.end(); Vit++) {
363       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
364       Couple outputFile = cpt;
365
366       // Get absolute paths
367       string absremote = (Utils::isAbsolutePath(outputFile.getRemote()))?
368                          outputFile.getRemote() :
369                          params[WORKDIR].str() + "/" + outputFile.getRemote();
370       string abslocal = (Utils::isAbsolutePath(outputFile.getLocal()))?
371                         outputFile.getLocal() :
372                         absdir + "/" + outputFile.getLocal();
373
374       string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
375       subCommand += "vishnu_connect -p 2; ";
376       subCommand += "vishnu_copy_file " + _hostname + ":" + absremote + " " + abslocal;
377       string command = _protocol.getExecCommand(subCommand,
378                                                 _hostname,
379                                                 _username);
380       cerr << command.c_str() << endl;
381       status = system(command.c_str());
382       if (status != 0)
383         throw EmulationException("Can't copy file");
384     }
385
386     // Copy logs
387     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
388     subCommand += "vishnu_connect -p 2; ";
389     subCommand += "vishnu_copy_file -r " +_hostname + ":" + params[WORKDIR].str() + "/logs" + " " + absdir;
390     string command = _protocol.getExecCommand(subCommand,
391                                               _hostname,
392                                               _username);
393     cerr << command.c_str() << endl;
394     status = system(command.c_str());
395     if (status != 0)
396       throw EmulationException("Can't copy logs");
397   }
398
399 }