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