Remove utility/ dependencies on network.h and main.h
[alexxy/gromacs.git] / src / gromacs / utility / fatalerror.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #include "fatalerror.h"
38 #include "gromacs/legacyheaders/gmx_fatal_collective.h"
39
40 #ifdef HAVE_CONFIG_H
41 #include <config.h>
42 #endif
43
44 #include <ctype.h>
45 #include <errno.h>
46 #include <stdarg.h>
47 #include <stdlib.h>
48 #include <string.h>
49
50 #include <exception>
51
52 #include "thread_mpi/threads.h"
53
54 #include "gromacs/legacyheaders/types/commrec.h"
55
56 #include "gromacs/fileio/futil.h"
57 #include "gromacs/fileio/gmxfio.h"
58 #include "gromacs/utility/basenetwork.h"
59 #include "gromacs/utility/baseversion.h"
60 #include "gromacs/utility/cstringutil.h"
61 #include "gromacs/utility/gmxmpi.h"
62 #include "gromacs/utility/programcontext.h"
63 #include "gromacs/utility/smalloc.h"
64
65 static gmx_bool            bDebug         = FALSE;
66 static FILE               *log_file       = NULL;
67
68 static tMPI_Thread_mutex_t debug_mutex     = TMPI_THREAD_MUTEX_INITIALIZER;
69 static tMPI_Thread_mutex_t where_mutex     = TMPI_THREAD_MUTEX_INITIALIZER;
70
71 gmx_bool bDebugMode(void)
72 {
73     return bDebug;
74 }
75
76 void gmx_fatal_set_log_file(FILE *fp)
77 {
78     log_file = fp;
79 }
80
81 void _where(const char *file, int line)
82 {
83     static gmx_bool bFirst = TRUE;
84     static int      nskip  = -1;
85     static int      nwhere =  0;
86     FILE           *fp;
87     char           *temp;
88
89     if (bFirst)
90     {
91         tMPI_Thread_mutex_lock(&where_mutex);
92         if (bFirst) /* we repeat the check in the locked section because things
93                        might have changed */
94         {
95             if ((temp = getenv("WHERE")) != NULL)
96             {
97                 nskip = strtol(temp, NULL, 10);
98             }
99             bFirst = FALSE;
100         }
101         tMPI_Thread_mutex_unlock(&where_mutex);
102     }
103
104     if (nskip >= 0)
105     {
106         /* Skip the first n occasions, this allows to see where it goes wrong */
107         if (nwhere >= nskip)
108         {
109             if (log_file)
110             {
111                 fp = log_file;
112             }
113             else
114             {
115                 fp = stderr;
116             }
117             fprintf(fp, "WHERE %d, file %s - line %d\n", nwhere, file, line);
118         }
119         nwhere++;
120     }
121 }
122
123 static int fatal_errno = 0;
124
125 static void quit_gmx(const char *msg)
126 {
127     tMPI_Thread_mutex_lock(&debug_mutex);
128     if (fatal_errno == 0)
129     {
130         if (log_file)
131         {
132             fprintf(log_file, "%s\n", msg);
133         }
134         fprintf(stderr, "%s\n", msg);
135         /* we set it to no-zero because if this function is called, something
136            has gone wrong */
137         fatal_errno = 255;
138     }
139     else
140     {
141         if (fatal_errno != -1)
142         {
143             errno = fatal_errno;
144         }
145         perror(msg);
146     }
147
148 #ifdef GMX_LIB_MPI
149     if (gmx_mpi_initialized())
150     {
151         int  nnodes;
152         int  noderank;
153
154         nnodes   = gmx_node_num();
155         noderank = gmx_node_rank();
156
157         if (nnodes > 1)
158         {
159             fprintf(stderr, "Error on node %d, will try to stop all the nodes\n",
160                     noderank);
161         }
162         gmx_abort(noderank, nnodes, -1);
163     }
164 #endif
165
166     if (debug)
167     {
168         fflush(debug);
169     }
170     if (bDebugMode())
171     {
172         fprintf(stderr, "dump core (y/n):");
173         fflush(stderr);
174         if (toupper(getc(stdin)) != 'N')
175         {
176             (void) abort();
177         }
178     }
179
180     exit(fatal_errno);
181     tMPI_Thread_mutex_unlock(&debug_mutex);
182 }
183
184 /* The function below should be identical to quit_gmx,
185  * except that is does not actually quit and call gmx_abort.
186  */
187 static void quit_gmx_noquit(const char *msg)
188 {
189     tMPI_Thread_mutex_lock(&debug_mutex);
190     if (!fatal_errno)
191     {
192         if (log_file)
193         {
194             fprintf(log_file, "%s\n", msg);
195         }
196         fprintf(stderr, "%s\n", msg);
197         /* we set it to no-zero because if this function is called, something
198            has gone wrong */
199         fatal_errno = 255;
200     }
201     else
202     {
203         if (fatal_errno != -1)
204         {
205             errno = fatal_errno;
206         }
207         perror(msg);
208     }
209
210 #ifndef GMX_LIB_MPI
211     if (debug)
212     {
213         fflush(debug);
214     }
215     if (bDebugMode())
216     {
217         fprintf(stderr, "dump core (y/n):");
218         fflush(stderr);
219         if (toupper(getc(stdin)) != 'N')
220         {
221             (void) abort();
222         }
223     }
224 #endif
225
226     tMPI_Thread_mutex_unlock(&debug_mutex);
227 }
228
229 void gmx_fatal(int f_errno, const char *file, int line, const char *fmt, ...)
230 {
231     va_list ap;
232     char    msg[STRLEN];
233
234     va_start(ap, fmt);
235     vsprintf(msg, fmt, ap);
236     va_end(ap);
237
238     tMPI_Thread_mutex_lock(&debug_mutex);
239     fatal_errno = f_errno;
240     tMPI_Thread_mutex_unlock(&debug_mutex);
241
242     _gmx_error("fatal", msg, file, line);
243 }
244
245 void gmx_fatal_collective(int f_errno, const char *file, int line,
246                           const t_commrec *cr, gmx_domdec_t *dd,
247                           const char *fmt, ...)
248 {
249     va_list     ap;
250     char        msg[STRLEN];
251 #ifdef GMX_MPI
252     int         result;
253 #endif
254
255 #ifdef GMX_MPI
256     /* Check if we are calling on all processes in MPI_COMM_WORLD */
257     if (cr != NULL)
258     {
259         MPI_Comm_compare(cr->mpi_comm_mysim, MPI_COMM_WORLD, &result);
260     }
261     else
262     {
263         MPI_Comm_compare(dd->mpi_comm_all, MPI_COMM_WORLD, &result);
264     }
265     /* Any result except MPI_UNEQUAL allows us to call MPI_Finalize */
266     const bool bFinalize = (result != MPI_UNEQUAL);
267 #else
268     const bool bFinalize = true;
269 #endif
270
271     if ((cr != NULL && MASTER(cr)  ) ||
272         (dd != NULL && DDMASTER(dd)))
273     {
274         va_start(ap, fmt);
275         vsprintf(msg, fmt, ap);
276         va_end(ap);
277
278         tMPI_Thread_mutex_lock(&debug_mutex);
279         fatal_errno = f_errno;
280         tMPI_Thread_mutex_unlock(&debug_mutex);
281
282         if (bFinalize)
283         {
284             /* Use an error handler that does not quit */
285             set_gmx_error_handler(quit_gmx_noquit);
286         }
287
288         _gmx_error("fatal", msg, file, line);
289     }
290
291 #ifdef GMX_MPI
292     if (bFinalize)
293     {
294         /* Broadcast the fatal error number possibly modified
295          * on the master process, in case the user would like
296          * to use the return status on a non-master process.
297          * The master process in cr and dd always has global rank 0.
298          */
299         MPI_Bcast(&fatal_errno, sizeof(fatal_errno), MPI_BYTE,
300                   0, MPI_COMM_WORLD);
301
302         /* Finalize nicely instead of aborting */
303         MPI_Finalize();
304     }
305     else
306     {
307         /* Let all other processes wait till the master has printed
308          * the error message and issued MPI_Abort.
309          */
310         MPI_Barrier(MPI_COMM_WORLD);
311     }
312 #endif
313
314     exit(fatal_errno);
315 }
316
317 /*
318  * These files are global variables in the gromacs preprocessor
319  * Every routine in a file that includes gmx_fatal.h can write to these
320  * debug channels. Depending on the debuglevel used
321  * 0 to 3 of these filed are redirected to /dev/null
322  *
323  */
324 FILE    *debug           = NULL;
325 gmx_bool gmx_debug_at    = FALSE;
326
327 void init_debug(const int dbglevel, const char *dbgfile)
328 {
329     tMPI_Thread_mutex_lock(&debug_mutex);
330     if (!bDebug) /* another thread hasn't already run this*/
331     {
332         no_buffers();
333         debug  = gmx_fio_fopen(dbgfile, "w+");
334         bDebug = TRUE;
335         if (dbglevel >= 2)
336         {
337             gmx_debug_at = TRUE;
338         }
339     }
340     tMPI_Thread_mutex_unlock(&debug_mutex);
341 }
342
343 static const char *gmxuser = "Please report this to the mailing list (gmx-users@gromacs.org)";
344
345 static void        (*gmx_error_handler)(const char *msg) = quit_gmx;
346
347 void set_gmx_error_handler(void (*func)(const char *msg))
348 {
349     tMPI_Thread_mutex_lock(&debug_mutex);
350     gmx_error_handler = func;
351     tMPI_Thread_mutex_unlock(&debug_mutex);
352 }
353
354 char *gmx_strerror(const char *key)
355 {
356     typedef struct {
357         const char *key, *msg;
358     } error_msg_t;
359     error_msg_t msg[] = {
360         { "bug",    "Possible bug" },
361         { "call",   "Routine should not have been called" },
362         { "comm",   "Communication (parallel processing) problem" },
363         { "fatal",  "Fatal error" },
364         { "cmd",    "Invalid command line argument" },
365         { "file",   "File input/output error" },
366         { "impl",   "Implementation restriction" },
367         { "incons", "Software inconsistency error" },
368         { "input",  "Input error or input inconsistency" },
369         { "mem",    "Memory allocation/freeing error" },
370         { "open",   "Can not open file" },
371         { "range",  "Range checking error" },
372         { NULL,     NULL}
373     };
374
375     if (key == NULL)
376     {
377         return strdup("Empty message");
378     }
379     else
380     {
381         for (size_t i = 0; msg[i].key != NULL; ++i)
382         {
383             if (strcmp(key, msg[i].key) == 0)
384             {
385                 return strdup(msg[i].msg);
386             }
387         }
388         char buf[1024];
389         sprintf(buf, "No error message associated with key %s\n%s", key, gmxuser);
390         return strdup(buf);
391     }
392 }
393
394
395 void _gmx_error(const char *key, const char *msg, const char *file, int line)
396 {
397     char        buf[10240], errerrbuf[1024];
398     const char *llines = "-------------------------------------------------------";
399     char       *strerr;
400
401     /* protect the audience from suggestive discussions */
402
403     if (msg == NULL)
404     {
405         sprintf(errerrbuf, "Empty fatal_error message. %s", gmxuser);
406     }
407     // In case ProgramInfo is not initialized and there is an issue with the
408     // initialization, fall back to "GROMACS".
409     const char *programName = "GROMACS";
410     try
411     {
412         programName = gmx::getProgramContext().displayName();
413     }
414     catch (const std::exception &)
415     {
416     }
417
418     strerr = gmx_strerror(key);
419     sprintf(buf, "\n%s\nProgram %s, %s\n"
420             "Source code file: %s, line: %d\n\n"
421             "%s:\n%s\nFor more information and tips for troubleshooting, please check the GROMACS\n"
422             "website at http://www.gromacs.org/Documentation/Errors\n%s\n",
423             llines, programName, gmx_version(), file, line,
424             strerr, msg ? msg : errerrbuf, llines);
425     free(strerr);
426
427     gmx_error_handler(buf);
428 }
429
430 void _range_check(int n, int n_min, int n_max, const char *warn_str,
431                   const char *var, const char *file, int line)
432 {
433     char buf[1024];
434
435     if ((n < n_min) || (n >= n_max))
436     {
437         if (warn_str != NULL)
438         {
439             strcpy(buf, warn_str);
440             strcat(buf, "\n");
441         }
442         else
443         {
444             buf[0] = '\0';
445         }
446
447         sprintf(buf+strlen(buf), "Variable %s has value %d. It should have been "
448                 "within [ %d .. %d ]\n", var, n, n_min, n_max);
449
450         _gmx_error("range", buf, file, line);
451     }
452 }
453
454 void gmx_warning(const char *fmt, ...)
455 {
456     va_list ap;
457     char    msg[STRLEN];
458
459     va_start(ap, fmt);
460     vsprintf(msg, fmt, ap);
461     va_end(ap);
462
463     fprintf(stderr, "\nWARNING: %s\n\n", msg);
464 }