Salome HOME
Copyright update 2021
[tools/libbatch.git] / src / Vishnu / BatchManager_Vishnu.cxx
1 // Copyright (C) 2007-2021  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, or (at your option) any later version.
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  *  BatchManager_Vishnu.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 <Constants.hxx>
39 #include <Utils.hxx>
40
41 #include "BatchManager_Vishnu.hxx"
42 #include "JobInfo_Vishnu.hxx"
43 #include "Log.hxx"
44
45 using namespace std;
46
47 namespace Batch {
48
49   BatchManager_Vishnu::BatchManager_Vishnu(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_Vishnu::~BatchManager_Vishnu()
60   {
61   }
62
63   // Method to submit a job to the batch manager
64   const JobId BatchManager_Vishnu::runJob(const Job & job)
65   {
66     // build command file to submit the job
67     string cmdFile = buildCommandFile(job);
68
69     // define extra parameters (that can not be defined in the command file)
70     Parametre params = job.getParametre();
71     ostringstream extraParams;
72     if (params.find(NBPROC) != params.end())
73       extraParams << "-P " << params[NBPROC] << " ";
74     if (params.find(MAXRAMSIZE) != params.end())
75       extraParams << "-m " << params[MAXRAMSIZE] << " ";
76
77     // define command to submit batch
78     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
79     subCommand += "vishnu_connect && ";
80     subCommand += "vishnu_submit_job " + extraParams.str() + _hostname + " " + cmdFile + " && ";
81     subCommand += "vishnu_close";
82     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
83     command += " 2>&1";
84     LOG(command);
85
86     // submit job
87     string output;
88     int status = Utils::getCommandOutput(command, output);
89     LOG(output);
90     if (status != 0) throw RunTimeException("Can't submit job, error was: " + output);
91
92     // find id of submitted job in output
93     string search = "Job Id     : ";
94     string::size_type pos = output.find(search);
95     if (pos == string::npos)
96       throw RunTimeException("Error in the submission of the job on the remote host");
97     pos += search.size();
98     string::size_type endl_pos = output.find('\n', pos);
99     string::size_type count = (endl_pos == string::npos)? string::npos : endl_pos - pos;
100     string jobref = output.substr(pos, count);
101     if (jobref.size() == 0)
102       throw RunTimeException("Error in the submission of the job on the remote host");
103
104     JobId id(this, jobref);
105     return id;
106   }
107
108
109   void BatchManager_Vishnu::exportInputFiles(const Job& job)
110   {
111     Parametre params = job.getParametre();
112     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
113     subCommand += "vishnu_connect && ";
114
115     // create remote directories
116     subCommand += "vishnu_create_dir -p " + _hostname + ":" + params[WORKDIR].str() + "/logs && ";
117
118     // copy executable
119     string executeFile = params[EXECUTABLE];
120     if (executeFile.size() != 0) {
121       subCommand += "vishnu_copy_file " + executeFile + " " +
122                     _hostname + ":" + params[WORKDIR].str() + "/ && ";
123     }
124
125     // copy filesToExportList
126     const Versatile & V = params[INFILE];
127     Versatile::const_iterator Vit;
128     for (Vit=V.begin(); Vit!=V.end(); Vit++) {
129       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
130       Couple inputFile = cpt;
131
132       // Get absolute paths
133       char * buf = getcwd(NULL, 0);
134       string cwd = buf;
135       free(buf);
136
137       string absremote = (Utils::isAbsolutePath(inputFile.getRemote()))?
138                          inputFile.getRemote() :
139                          params[WORKDIR].str() + "/" + inputFile.getRemote();
140       string abslocal = (Utils::isAbsolutePath(inputFile.getLocal()))?
141                         inputFile.getLocal() :
142                         cwd + "/" + inputFile.getLocal();
143
144       if (Vit != V.begin())
145         subCommand += " && ";
146       subCommand += "vishnu_copy_file " + abslocal + " " + _hostname + ":" + absremote;
147     }
148     subCommand += " && vishnu_close";
149
150     // Execute command
151     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
152     command += " 2>&1";
153     LOG(command);
154     string output;
155     int status = Utils::getCommandOutput(command, output);
156     LOG(output);
157     if (status != 0)
158       throw RunTimeException("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_Vishnu::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 RunTimeException("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 RunTimeException("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 = Utils::createAndOpenTemporaryFile("vishnu-script", tempOutputFile);
192
193     tempOutputFile << "#!/bin/sh" << endl;
194     tempOutputFile << "#% vishnu_output=" << workDir << "/logs/output.log." << rootNameToExecute << endl;
195     tempOutputFile << "#% vishnu_rror=" << 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;
225     if (params.find(ARGUMENTS) != params.end()) {
226       Versatile V = params[ARGUMENTS];
227       for(Versatile::const_iterator it=V.begin(); it!=V.end(); it++) {
228         StringType argt = * static_cast<StringType *>(*it);
229         string     arg  = argt;
230         tempOutputFile << " " << arg;
231       }
232     }
233     tempOutputFile << endl;
234
235     tempOutputFile.flush();
236     tempOutputFile.close();
237
238     LOG("Batch script file generated is: " << tmpFileName);
239     return tmpFileName;
240   }
241
242   void BatchManager_Vishnu::deleteJob(const JobId & jobid)
243   {
244     // define command to delete job
245     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
246     subCommand += "vishnu_connect && ";
247     subCommand += "vishnu_cancel_job " + _hostname + " " + jobid.getReference() + " && ";
248     subCommand += "vishnu_close";
249     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
250     LOG(command);
251
252     int status = system(command.c_str());
253     if (status)
254       throw RunTimeException("Can't delete job " + jobid.getReference());
255
256     LOG("job " << jobid.getReference() << " killed");
257   }
258
259   JobInfo BatchManager_Vishnu::queryJob(const JobId & jobid)
260   {
261     // define command to query batch
262     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
263     subCommand += "vishnu_connect && ";
264     subCommand += "vishnu_get_job_info " + _hostname + " " + jobid.getReference() + " && ";
265     subCommand += "vishnu_close";
266     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
267     LOG(command);
268
269     string output;
270     int status = Utils::getCommandOutput(command, output);
271     if (status != 0)
272       throw RunTimeException("Can't query job " + jobid.getReference());
273     JobInfo_Vishnu jobinfo = JobInfo_Vishnu(jobid.getReference(), output);
274     return jobinfo;
275   }
276
277   void BatchManager_Vishnu::importOutputFiles(const Job & job, const std::string directory)
278   {
279     // Create local result directory
280     char * buf = getcwd(NULL, 0);
281     string cwd = buf;
282     free(buf);
283     string absdir = (Utils::isAbsolutePath(directory))? directory : cwd + "/" + directory;
284     int status = CommunicationProtocol::getInstance(SH).makeDirectory(absdir, "", "");
285     if (status != 0) {
286       throw RunTimeException("Can't create result directory");
287     }
288
289     string subCommand = string("export OMNIORB_CONFIG=$VISHNU_CONFIG_FILE; ");
290     subCommand += "vishnu_connect && ";
291
292     // Copy output files
293     Parametre params = job.getParametre();
294     const Versatile & V = params[OUTFILE];
295     Versatile::const_iterator Vit;
296     for (Vit=V.begin(); Vit!=V.end(); Vit++) {
297       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
298       Couple outputFile = cpt;
299
300       // Get absolute paths
301       string absremote = (Utils::isAbsolutePath(outputFile.getRemote()))?
302                          outputFile.getRemote() :
303                          params[WORKDIR].str() + "/" + outputFile.getRemote();
304       string abslocal = (Utils::isAbsolutePath(outputFile.getLocal()))?
305                         outputFile.getLocal() :
306                         absdir + "/" + outputFile.getLocal();
307
308       subCommand += "vishnu_copy_file " + _hostname + ":" + absremote + " " + abslocal + " && ";
309     }
310
311     // Copy logs
312     subCommand += "vishnu_copy_file -r " +_hostname + ":" + params[WORKDIR].str() + "/logs" + " " + absdir + " && ";
313     subCommand += "vishnu_close";
314
315     // Execute command
316     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
317     command += " 2>&1";
318     LOG(command);
319     string output;
320     status = Utils::getCommandOutput(command, output);
321     LOG(output);
322     if (status != 0)
323       throw RunTimeException("Can't import output files, error was: " + output);
324   }
325
326 }