Salome HOME
f1e999e3679f711f490d672f4560ad9593f43a5f
[tools/libbatch.git] / src / Slurm / Batch_BatchManager_eSlurm.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_eSlurm.cxx :
24  *
25  *  Created on: 12 may 2011
26  *  Author : Renaud BARATE - EDF R&D
27  */
28
29 #include <cstdlib>
30 #include <fstream>
31
32 #include <Batch_NotYetImplementedException.hxx>
33 #include <Batch_Constants.hxx>
34 #include <Batch_Utils.hxx>
35
36 #include "Batch_BatchManager_eSlurm.hxx"
37 #include "Batch_JobInfo_eSlurm.hxx"
38
39 using namespace std;
40
41 namespace Batch {
42
43   BatchManager_eSlurm::BatchManager_eSlurm(const FactBatchManager * parent,
44                                            const char * host,
45                                            const char * username,
46                                            CommunicationProtocolType protocolType,
47                                            const char * mpiImpl)
48     : BatchManager(parent, host, username, protocolType, mpiImpl)
49   {
50   }
51
52   BatchManager_eSlurm::~BatchManager_eSlurm()
53   {
54   }
55
56   // Method to submit a job to the batch manager
57   const JobId BatchManager_eSlurm::submitJob(const Job & job)
58   {
59     Parametre params = job.getParametre();
60     const string workDir = params[WORKDIR];
61
62     // export input files on cluster
63     exportInputFiles(job);
64
65     // build command file to submit the job and copy it on the server
66     string cmdFile = buildCommandFile(job);
67
68     // define command to submit batch
69     string subCommand = string("cd ") + workDir + "; sbatch " + cmdFile;
70     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
71     command += " 2>&1";
72     cout << command.c_str() << endl;
73
74     // submit job
75     string output;
76     int status = Utils::getCommandOutput(command, output);
77     cout << output;
78     if (status != 0) throw RunTimeException("Can't submit job, error was: " + output);
79
80     // find id of submitted job in output
81     string search = "Submitted batch job ";
82     string::size_type pos = output.find(search);
83     if (pos == string::npos)
84       throw RunTimeException("Error in the submission of the job on the remote host");
85     pos += search.size();
86     string::size_type endl_pos = output.find('\n', pos);
87     string::size_type count = (endl_pos == string::npos)? string::npos : endl_pos - pos;
88     string jobref = output.substr(pos, count);
89
90     JobId id(this, jobref);
91     return id;
92   }
93
94   /**
95    * Create Slurm command file and copy it on the server.
96    * Return the name of the remote file.
97    */
98   string BatchManager_eSlurm::buildCommandFile(const Job & job)
99   {
100     Parametre params = job.getParametre();
101
102     // Job Parameters
103     string workDir = "";
104     string fileToExecute = "";
105     string queue = "";
106
107     // Mandatory parameters
108     if (params.find(WORKDIR) != params.end()) 
109       workDir = params[WORKDIR].str();
110     else 
111       throw RunTimeException("params[WORKDIR] is not defined. Please define it, cannot submit this job.");
112     if (params.find(EXECUTABLE) != params.end()) 
113       fileToExecute = params[EXECUTABLE].str();
114     else 
115       throw RunTimeException("params[EXECUTABLE] is not defined. Please define it, cannot submit this job.");
116
117     string::size_type p1 = fileToExecute.find_last_of("/");
118     string::size_type p2 = fileToExecute.find_last_of(".");
119     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
120     string fileNameToExecute = fileToExecute.substr(p1+1);
121
122     // Create batch submit file
123     ofstream tempOutputFile;
124     string tmpFileName = Utils::createAndOpenTemporaryFile("slurm-script", tempOutputFile);
125
126     tempOutputFile << "#!/bin/bash" << endl;
127     tempOutputFile << "#SBATCH --output=" << workDir << "/logs/output.log." << rootNameToExecute << endl;
128     tempOutputFile << "#SBATCH --error=" << workDir << "/logs/error.log." << rootNameToExecute << endl;
129
130     if (params.find(NAME) != params.end())
131       tempOutputFile << "#SBATCH --job-name=\"" << params[NAME] << "\"" << endl;
132
133     // Optional parameters
134     int nbproc = 1;
135     if (params.find(NBPROC) != params.end())
136       nbproc = params[NBPROC];
137     tempOutputFile << "#SBATCH --ntasks=" << nbproc << endl;
138
139     if (params.find(EXCLUSIVE) != params.end()) {
140       if (params[EXCLUSIVE])
141         tempOutputFile << "#SBATCH --exclusive" << endl;
142       else
143         tempOutputFile << "#SBATCH --share" << endl;
144     }
145
146     if (params.find(MAXWALLTIME) != params.end())
147       tempOutputFile << "#SBATCH --time=" << params[MAXWALLTIME] << endl;
148     if (params.find(MAXRAMSIZE) != params.end())
149       tempOutputFile << "#SBATCH --mem=" << params[MAXRAMSIZE] << endl;
150     if (params.find(QUEUE) != params.end())
151       tempOutputFile << "#SBATCH --partition=" << params[QUEUE] << endl;
152
153     // Define environment for the job
154     Environnement env = job.getEnvironnement();
155     for (Environnement::const_iterator iter = env.begin() ; iter != env.end() ; ++iter) {
156       tempOutputFile << "export " << iter->first << "=" << iter->second << endl;
157     }
158
159     // generate nodes file
160     tempOutputFile << "LIBBATCH_NODEFILE=`mktemp nodefile-XXXXXXXXXX`" << endl;
161     tempOutputFile << "srun hostname > $LIBBATCH_NODEFILE" << endl;
162     tempOutputFile << "export LIBBATCH_NODEFILE" << endl;
163
164     // Launch the executable
165     tempOutputFile << "cd " << workDir << endl;
166     tempOutputFile << "./" + fileNameToExecute << endl;
167
168     // Remove the node file
169     tempOutputFile << "rm $LIBBATCH_NODEFILE" << endl;
170
171     tempOutputFile.flush();
172     tempOutputFile.close();
173
174     cerr << "Batch script file generated is: " << tmpFileName << endl;
175
176     string remoteFileName = rootNameToExecute + "_slurm.cmd";
177     int status = _protocol.copyFile(tmpFileName, "", "",
178                                     workDir + "/" + remoteFileName,
179                                     _hostname, _username);
180     if (status)
181       throw RunTimeException("Cannot copy command file on host " + _hostname);
182
183     return remoteFileName;
184   }
185
186   void BatchManager_eSlurm::deleteJob(const JobId & jobid)
187   {
188     // define command to delete job
189     string subCommand = "scancel " + jobid.getReference();
190     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
191     cerr << command.c_str() << endl;
192
193     int status = system(command.c_str());
194     if (status)
195       throw RunTimeException("Can't delete job " + jobid.getReference());
196
197     cerr << "job " << jobid.getReference() << " killed" << endl;
198   }
199
200   void BatchManager_eSlurm::holdJob(const JobId & jobid)
201   {
202     throw NotYetImplementedException("BatchManager_eSlurm::holdJob");
203   }
204
205   void BatchManager_eSlurm::releaseJob(const JobId & jobid)
206   {
207     throw NotYetImplementedException("BatchManager_eSlurm::releaseJob");
208   }
209
210   void BatchManager_eSlurm::alterJob(const JobId & jobid, const Parametre & param, const Environnement & env)
211   {
212     throw NotYetImplementedException("BatchManager_eSlurm::alterJob");
213   }
214
215   void BatchManager_eSlurm::alterJob(const JobId & jobid, const Parametre & param)
216   {
217     throw NotYetImplementedException("BatchManager_eSlurm::alterJob");
218   }
219
220   void BatchManager_eSlurm::alterJob(const JobId & jobid, const Environnement & env)
221   {
222     throw NotYetImplementedException("BatchManager_eSlurm::alterJob");
223   }
224
225   JobInfo BatchManager_eSlurm::queryJob(const JobId & jobid)
226   {
227     // define command to query batch
228     string subCommand = "squeue -o %t -j " + jobid.getReference();
229     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
230     cerr << command.c_str() << endl;
231     string output;
232     Utils::getCommandOutput(command, output);
233     // We don't test the return code here because with jobs finished since a long time Slurm
234     // returns an error and a message like "slurm_load_jobs error: Invalid job id specified".
235     // So we consider that the job is finished when we get an error.
236
237     JobInfo_eSlurm jobinfo = JobInfo_eSlurm(jobid.getReference(), output);
238     return jobinfo;
239   }
240
241   const JobId BatchManager_eSlurm::addJob(const Job & job, const string reference)
242   {
243     return JobId(this, reference);
244   }
245
246 }