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