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