Salome HOME
Copyright update 2021
[tools/libbatch.git] / src / Slurm / BatchManager_Slurm.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_Slurm.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 <NotYetImplementedException.hxx>
33 #include <Constants.hxx>
34 #include <Utils.hxx>
35 #include <Log.hxx>
36
37 #include "BatchManager_Slurm.hxx"
38 #include "JobInfo_Slurm.hxx"
39
40 using namespace std;
41
42 namespace Batch {
43
44   BatchManager_Slurm::BatchManager_Slurm(const FactBatchManager * parent,
45                                            const char * host,
46                                            const char * username,
47                                            CommunicationProtocolType protocolType,
48                                            const char * mpiImpl)
49     : BatchManager(parent, host, username, protocolType, mpiImpl)
50   {
51   }
52
53   BatchManager_Slurm::~BatchManager_Slurm()
54   {
55   }
56
57   // Method to submit a job to the batch manager
58   const JobId BatchManager_Slurm::runJob(const Job & job)
59   {
60     Parametre params = job.getParametre();
61     const string workDir = params[WORKDIR];
62
63     // build command file to submit the job and copy it on the server
64     string cmdFile = buildCommandFile(job);
65
66     // define command to submit batch
67     string subCommand = string("bash -l -c \\\"cd ") + workDir + "; sbatch " + cmdFile + "\\\"";
68     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
69     command += " 2>&1";
70     LOG(command);
71
72     // submit job
73     string output;
74     int status = Utils::getCommandOutput(command, output);
75     LOG(output);
76     if (status != 0) throw RunTimeException("Can't submit job, error was: " + output);
77
78     // find id of submitted job in output
79     string search = "Submitted batch job ";
80     string::size_type pos = output.find(search);
81     if (pos == string::npos)
82       throw RunTimeException("Error in the submission of the job on the remote host");
83     pos += search.size();
84     string::size_type endl_pos = output.find('\n', pos);
85     string::size_type count = (endl_pos == string::npos)? string::npos : endl_pos - pos;
86     string jobref = output.substr(pos, count);
87
88     JobId id(this, jobref);
89     return id;
90   }
91
92   /**
93    * Create Slurm command file and copy it on the server.
94    * Return the name of the remote file.
95    */
96   string BatchManager_Slurm::buildCommandFile(const Job & job)
97   {
98     Parametre params = job.getParametre();
99
100     // Job Parameters
101     string workDir = "";
102     string fileToExecute = "";
103     string queue = "";
104
105     // Mandatory parameters
106     if (params.find(WORKDIR) != params.end()) 
107       workDir = params[WORKDIR].str();
108     else 
109       throw RunTimeException("params[WORKDIR] is not defined. Please define it, cannot submit this job.");
110     if (params.find(EXECUTABLE) != params.end()) 
111       fileToExecute = params[EXECUTABLE].str();
112     else 
113       throw RunTimeException("params[EXECUTABLE] is not defined. Please define it, cannot submit this job.");
114
115     string::size_type p1 = fileToExecute.find_last_of("/");
116     string::size_type p2 = fileToExecute.find_last_of(".");
117     string rootNameToExecute = fileToExecute.substr(p1+1,p2-p1-1);
118     string fileNameToExecute = fileToExecute.substr(p1+1);
119
120     // Create batch submit file
121     ofstream tempOutputFile;
122     string tmpFileName = Utils::createAndOpenTemporaryFile("slurm-script", tempOutputFile);
123
124     tempOutputFile << "#!/bin/bash -l" << endl;
125     tempOutputFile << "#SBATCH --output=" << workDir << "/logs/output.log." << rootNameToExecute << endl;
126     tempOutputFile << "#SBATCH --error=" << workDir << "/logs/error.log." << rootNameToExecute << endl;
127
128     if (params.find(NAME) != params.end())
129       tempOutputFile << "#SBATCH --job-name=\"" << params[NAME] << "\"" << endl;
130
131     // Optional parameters
132     int nbproc = 1;
133     if (params.find(NBPROC) != params.end())
134       nbproc = params[NBPROC];
135     tempOutputFile << "#SBATCH --ntasks=" << nbproc << endl;
136
137     if (params.find(EXCLUSIVE) != params.end()) {
138       if (params[EXCLUSIVE])
139         tempOutputFile << "#SBATCH --exclusive" << endl;
140       else
141         tempOutputFile << "#SBATCH --share" << endl;
142     }
143
144     if (params.find(MAXWALLTIME) != params.end())
145       tempOutputFile << "#SBATCH --time=" << params[MAXWALLTIME] << endl;
146     if (params.find(MAXRAMSIZE) != params.end())
147       tempOutputFile << "#SBATCH --mem=" << params[MAXRAMSIZE] << endl;
148     else if (params.find(MEMPERCPU) != params.end())
149       tempOutputFile << "#SBATCH --mem-per-cpu=" << params[MEMPERCPU] << endl;
150     if (params.find(QUEUE) != params.end())
151       tempOutputFile << "#SBATCH --qos=" << params[QUEUE] << endl;
152     if (params.find(PARTITION) != params.end())
153       tempOutputFile << "#SBATCH --partition=" << params[PARTITION] << endl;
154     if (params.find(WCKEY) != params.end())
155       tempOutputFile << "#SBATCH --wckey=" << params[WCKEY] << endl;
156     if (params.find(NBNODE) != params.end())
157       tempOutputFile << "#SBATCH --nodes=" << params[NBNODE] << endl;
158     if (params.find(EXTRAPARAMS) != params.end())
159       tempOutputFile << params[EXTRAPARAMS] << endl;
160
161     // Define environment for the job
162     Environnement env = job.getEnvironnement();
163     for (Environnement::const_iterator iter = env.begin() ; iter != env.end() ; ++iter) {
164       tempOutputFile << "export " << iter->first << "=" << iter->second << endl;
165     }
166
167     // generate nodes file
168     tempOutputFile << "LIBBATCH_NODEFILE=$(mktemp nodefile-XXXXXXXXXX)" << endl;
169     tempOutputFile << "srun hostname > \"$LIBBATCH_NODEFILE\"" << endl;
170     tempOutputFile << "export LIBBATCH_NODEFILE" << endl;
171
172     // Launch the executable
173     tempOutputFile << "cd " << workDir << endl;
174     tempOutputFile << "./" + fileNameToExecute;
175     if (params.find(ARGUMENTS) != params.end()) {
176       Versatile V = params[ARGUMENTS];
177       for(Versatile::const_iterator it=V.begin(); it!=V.end(); it++) {
178         StringType argt = * static_cast<StringType *>(*it);
179         string     arg  = argt;
180         tempOutputFile << " " << arg;
181       }
182     }
183     tempOutputFile << endl;
184
185     // Remove the node file
186     tempOutputFile << "rm \"$LIBBATCH_NODEFILE\"" << endl;
187
188     tempOutputFile.flush();
189     tempOutputFile.close();
190
191     LOG("Batch script file generated is: " << tmpFileName);
192
193     string remoteFileName = rootNameToExecute + "_slurm.cmd";
194     int status = _protocol.copyFile(tmpFileName, "", "",
195                                     workDir + "/" + remoteFileName,
196                                     _hostname, _username);
197     if (status)
198       throw RunTimeException("Cannot copy command file on host " + _hostname);
199
200     return remoteFileName;
201   }
202
203   void BatchManager_Slurm::deleteJob(const JobId & jobid)
204   {
205     // define command to delete job
206     string subCommand = string("bash -l -c \\\"scancel ") + jobid.getReference() + "\\\"";
207     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
208     LOG(command);
209
210     int status = system(command.c_str());
211     if (status)
212       throw RunTimeException("Can't delete job " + jobid.getReference());
213
214     LOG("job " << jobid.getReference() << " killed");
215   }
216
217   JobInfo BatchManager_Slurm::queryJob(const JobId & jobid)
218   {
219     // First try to query the job with "squeue" command
220     string subCommand = string("bash -l -c \\\"squeue -h -o %T -j ") + jobid.getReference() + " 2>/dev/null" + "\\\"";
221     string command = _protocol.getExecCommand(subCommand, _hostname, _username);
222     LOG(command);
223     string output;
224     int status = Utils::getCommandOutput(command, output);
225     LOG("status: " << status << ", output: " << output);
226     bool found = false;
227     JobInfo jobinfo;
228     if (status == 0) {
229         try {
230             jobinfo = JobInfo_Slurm(jobid.getReference(), output);
231             found = true;
232         } catch (const RunTimeException & exc) {
233             LOG(exc);
234         }
235     }
236
237     // If "squeue" failed, the job may be finished. In this case, try to query the job with
238     // "sacct".
239     if (! found) {
240         string subCommand = string("bash -l -c \\\"sacct -X -o State%-10 -n -j ") + jobid.getReference() + "\\\"";
241         string command = _protocol.getExecCommand(subCommand, _hostname, _username);
242         LOG(command);
243         string output;
244         int status = Utils::getCommandOutput(command, output);
245         LOG("status: " << status << ", output: " << output);
246         if (status == 0) {
247             try {
248                 jobinfo = JobInfo_Slurm(jobid.getReference(), output);
249             } catch (const RunTimeException & exc) {
250                 LOG(exc);
251                 throw(exc);
252             }
253         } else {
254             throw RunTimeException("sacct command failed with return code: " + status);
255         }
256     }
257     return jobinfo;
258   }
259
260 }