Salome HOME
babdb826a83d1561c65cfc0be6d98fdda2518219
[tools/libbatch.git] / src / Core / Batch_BatchManager_eClient.cxx
1 //  Copyright (C) 2007-2010  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 * BatchManager_eLSF.cxx : emulation of LSF client
24 *
25 * Auteur : Bernard SECHER - CEA DEN
26 * Mail   : mailto:bernard.secher@cea.fr
27 * Date   : Thu Apr 24 10:17:22 2008
28 * Projet : PAL Salome
29 *
30 */
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include <ctime>
36 #include <iostream>
37 #include <fstream>
38 #include <sstream>
39
40 #include <stdlib.h>
41
42 #ifdef WIN32
43 #include <direct.h>
44 #include <io.h>
45 #endif
46
47 #include <Batch_config.h>
48
49 #include "Batch_Constants.hxx"
50 #include "Batch_BatchManager_eClient.hxx"
51 #include "Batch_RunTimeException.hxx"
52
53 #ifdef MSVC
54 #define EXISTS(path) _access_s(path, 0) == 0
55 #else
56 #define EXISTS(path) access(path, F_OK) == 0
57 #endif
58
59 using namespace std;
60
61
62 namespace Batch {
63
64   BatchManager_eClient::BatchManager_eClient(const Batch::FactBatchManager * parent, const char* host,
65                                              const char * username,
66                                              CommunicationProtocolType protocolType, const char* mpiImpl)
67     : BatchManager(parent, host), _protocol(CommunicationProtocol::getInstance(protocolType)),
68       _username(username)
69   {
70     // instanciation of mpi implementation needed to launch executable in batch script
71     _mpiImpl = FactoryMpiImpl(mpiImpl);
72   }
73
74   // Destructeur
75   BatchManager_eClient::~BatchManager_eClient()
76   {
77     if (_mpiImpl)
78       delete _mpiImpl;
79   }
80
81   void BatchManager_eClient::exportInputFiles(const Job& job)
82   {
83     int status;
84     Parametre params = job.getParametre();
85     Versatile V = params[INFILE];
86     Versatile::iterator Vit;
87
88     status = _protocol.makeDirectory(string(params[TMPDIR]) + "/logs", _hostname, _username);
89     if(status) {
90       std::ostringstream oss;
91       oss << status;
92       std::string ex_mess("Error of connection on remote host ! status = ");
93       ex_mess += oss.str();
94       throw EmulationException(ex_mess.c_str());
95     }
96
97     // Second step : copy fileToExecute into
98     // batch tmp files directory
99     string executeFile = params[EXECUTABLE];
100     if (executeFile.size() != 0) {
101       status = _protocol.copyFile(executeFile, "", "",
102                                   params[TMPDIR], _hostname, _username);
103       if(status) {
104         std::ostringstream oss;
105         oss << status;
106         std::string ex_mess("Error of connection on remote host ! status = ");
107         ex_mess += oss.str();
108         throw EmulationException(ex_mess.c_str());
109       }
110
111 #ifdef WIN32
112       // On Windows, we make the remote file executable afterward because
113       // pscp does not preserve access permissions on files
114       string subCommand = string("chmod u+x ") + string(params[TMPDIR]) + "/" +
115                           string(params[EXECUTABLE]);
116       string command = _protocol.getExecCommand(subCommand, _hostname, _username);
117       cerr << command.c_str() << endl;
118       status = system(command.c_str());
119       if(status) {
120         std::ostringstream oss;
121         oss << status;
122         std::string ex_mess("Error of connection on remote host ! status = ");
123         ex_mess += oss.str();
124         throw EmulationException(ex_mess.c_str());
125       }
126 #endif
127     }
128
129     // Third step : copy filesToExportList into
130     // batch tmp files directory
131     for(Vit=V.begin(); Vit!=V.end(); Vit++) {
132       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
133       Couple inputFile = cpt;
134       status = _protocol.copyFile(inputFile.getLocal(), "", "",
135                                   inputFile.getRemote(), _hostname, _username);
136       if(status) {
137         std::ostringstream oss;
138         oss << status;
139         std::string ex_mess("Error of connection on remote host ! status = ");
140         ex_mess += oss.str();
141         throw EmulationException(ex_mess.c_str());
142       }
143     }
144
145   }
146
147   void BatchManager_eClient::importOutputFiles( const Job & job, const string directory )
148   {
149     Parametre params = job.getParametre();
150     Versatile V = params[OUTFILE];
151     Versatile::iterator Vit;
152
153     // Create local result directory
154     int status = CommunicationProtocol::getInstance(SH).makeDirectory(directory, "", "");
155     if (status) {
156       string mess("Directory creation failed. Status is :");
157       ostringstream status_str;
158       status_str << status;
159       mess += status_str.str();
160       cerr << mess << endl;
161     }
162
163     for(Vit=V.begin(); Vit!=V.end(); Vit++) {
164       CoupleType cpt  = *static_cast< CoupleType * >(*Vit);
165       Couple outputFile = cpt;
166       status = _protocol.copyFile(outputFile.getRemote(), _hostname, _username,
167                                   directory, "", "");
168       if (status) {
169         // Try to get what we can (logs files)
170         // throw BatchException("Error of connection on remote host");
171         std::string mess("Copy command failed ! status is :");
172         ostringstream status_str;
173         status_str << status;
174         mess += status_str.str();
175         cerr << mess << endl;
176       }
177     }
178
179     // Copy logs
180     status = _protocol.copyFile(string(params[TMPDIR]) + string("/logs"), _hostname, _username,
181                                 directory, "", "");
182     if (status) {
183       std::string mess("Copy logs directory failed ! status is :");
184       ostringstream status_str;
185       status_str << status;
186       mess += status_str.str();
187       cerr << mess << endl;
188     }
189
190   }
191
192   bool BatchManager_eClient::importDumpStateFile( const Job & job, const string directory )
193   {
194     Parametre params = job.getParametre();
195
196     // Create local result directory
197     int status = CommunicationProtocol::getInstance(SH).makeDirectory(directory, "", "");
198     if (status) {
199       string mess("Directory creation failed. Status is :");
200       ostringstream status_str;
201       status_str << status;
202       mess += status_str.str();
203       cerr << mess << endl;
204     }
205
206     bool ret = true;
207     status = _protocol.copyFile(string(params[TMPDIR]) + string("/dumpState*.xml"), _hostname, _username,
208                                 directory, "", "");
209     if (status) {
210       // Try to get what we can (logs files)
211       // throw BatchException("Error of connection on remote host");
212       std::string mess("Copy command failed ! status is :");
213       ostringstream status_str;
214       status_str << status;
215       mess += status_str.str();
216       cerr << mess << endl;
217       ret = false;
218     }
219     return ret;
220   }
221
222   MpiImpl *BatchManager_eClient::FactoryMpiImpl(string mpiImpl)
223   {
224     if(mpiImpl == "lam")
225       return new MpiImpl_LAM();
226     else if(mpiImpl == "mpich1")
227       return new MpiImpl_MPICH1();
228     else if(mpiImpl == "mpich2")
229       return new MpiImpl_MPICH2();
230     else if(mpiImpl == "openmpi")
231       return new MpiImpl_OPENMPI();
232     else if(mpiImpl == "slurm")
233       return new MpiImpl_SLURM();
234     else if(mpiImpl == "prun")
235       return new MpiImpl_PRUN();
236     else if(mpiImpl == "nompi")
237       return NULL;
238     else{
239       ostringstream oss;
240       oss << mpiImpl << " : not yet implemented";
241       throw EmulationException(oss.str().c_str());
242     }
243   }
244
245   /**
246    * This method generates a temporary file name with the pattern "<tmpdir>/<prefix>-XXXXXX" where
247    * <tmpdir> is the directory for temporary files (see BatchManager_eClient::getTmpDir()) and the
248    * X's are replaced by random characters. Note that this method is less secure than
249    * BatchManager_eClient::createAndOpenTemporaryFile, so use the latter whenever possible.
250    * \param prefix the prefix to use for the temporary file.
251    * \return a name usable for a temporary file.
252    */
253   string BatchManager_eClient::generateTemporaryFileName(const string & prefix)
254   {
255     string fileName = getTmpDir() + "/" + prefix + "-XXXXXX";
256     char randstr[7];
257
258     do {
259       sprintf(randstr, "%06d", rand() % 1000000);
260       fileName.replace(fileName.size()-6, 6, randstr);
261     } while (EXISTS(fileName.c_str()));
262
263     return fileName;
264   }
265
266   /**
267    * This method creates a temporary file and opens an output stream to write into this file.
268    * The file is created with the pattern "<tmpdir>/<prefix>-XXXXXX" where <tmpdir> is the directory
269    * for temporary files (see BatchManager_eClient::getTmpDir()) and the X's are replaced by random
270    * characters. The caller is responsible for closing and deleting the file when it is no more used.
271    * \param prefix the prefix to use for the temporary file.
272    * \param outputStream an output stream that will be opened for writing in the temporary file. If
273    * the stream is already open, it will be closed first.
274    * \return the name of the created file.
275    */
276   string BatchManager_eClient::createAndOpenTemporaryFile(const string & prefix, ofstream & outputStream)
277   {
278     if (outputStream.is_open())
279       outputStream.close();
280
281 #ifdef WIN32
282
283     string fileName = generateTemporaryFileName(prefix);
284     outputStream.open(fileName.c_str());
285
286 #else
287
288     string fileName = getTmpDir() + "/" + prefix + "-XXXXXX";
289     char * buf = new char[fileName.size()+1];
290     fileName.copy(buf, fileName.size());
291     buf[fileName.size()] = '\0';
292
293     int fd = mkstemp(buf);
294     if (fd == -1) {
295       delete[] buf;
296       throw RunTimeException(string("Can't create temporary file ") + fileName);
297     }
298     fileName = buf;
299     delete[] buf;
300
301     outputStream.open(fileName.c_str());
302     close(fd);  // Close the file descriptor so that the file is not opened twice
303
304 #endif
305
306     if (outputStream.fail())
307       throw RunTimeException(string("Can't open temporary file ") + fileName);
308
309     return fileName;
310   }
311
312   /**
313    * This method finds the name of the directory to use for temporary files in libBatch. This name
314    * is <tempdir>/libBatch-<username>-XXXXXX. <tempdir> is found by looking for environment
315    * variables TEMP, TMP, TEMPDIR, TMPDIR, and defaults to "/tmp" if none of them is defined.
316    * <username> is found by looking for environment variables USER and USERNAME, and defaults to
317    * "unknown". XXXXXX represents random characters. The directory name is generated only once for
318    * each BatchManager_eClient instance, and the directory is created at this moment. Subsequent
319    * calls will always return the same path and the existence of the directory will not be
320    * rechecked.
321    * \return the name of the directory to use for temporary files.
322    */
323   const std::string & BatchManager_eClient::getTmpDir()
324   {
325     if (tmpDirName.empty()) {
326       const char * baseDir = getenv("TEMP");
327       if (baseDir == NULL) baseDir = getenv("TMP");
328       if (baseDir == NULL) baseDir = getenv("TEMPDIR");
329       if (baseDir == NULL) baseDir = getenv("TMPDIR");
330       if (baseDir == NULL) baseDir = "/tmp";
331
332       const char * userName = getenv("USER");
333       if (userName == NULL) userName = getenv("USERNAME");
334       if (userName == NULL) userName = "unknown";
335
336       string baseName = string(baseDir) + "/libBatch-" + userName + "-XXXXXX";
337       srand(time(NULL));
338
339 #ifdef WIN32
340
341       char randstr[7];
342       do {
343         sprintf(randstr, "%06d", rand() % 1000000);
344         baseName.replace(baseName.size()-6, 6, randstr);
345       } while (EXISTS(baseName.c_str()));
346       if (_mkdir(baseName.c_str()) != 0)
347         throw RunTimeException(string("Can't create temporary directory ") + baseName);
348       tmpDirName = baseName;
349
350 #else
351
352       char * buf = new char[baseName.size() + 1];
353       baseName.copy(buf, baseName.size());
354       buf[baseName.size()] = '\0';
355       if (mkdtemp(buf) == NULL) {
356         delete[] buf;
357         throw RunTimeException(string("Can't create temporary directory ") + baseName);
358       }
359       tmpDirName = buf;
360       delete[] buf;
361
362 #endif
363
364     }
365
366     return tmpDirName;
367   }
368
369 }