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