-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathErrorHandling.cpp
More file actions
500 lines (447 loc) · 15.6 KB
/
ErrorHandling.cpp
File metadata and controls
500 lines (447 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*
* ------------------------------------------------------------------------------------------------------------
* SPDX-License-Identifier: LGPL-2.1-only
*
* Copyright (c) 2016-2024 Lawrence Livermore National Security LLC
* Copyright (c) 2018-2024 TotalEnergies
* Copyright (c) 2018-2024 The Board of Trustees of the Leland Stanford Junior University
* Copyright (c) 2023-2024 Chevron
* Copyright (c) 2019- GEOS/GEOSX Contributors
* All rights reserved
*
* See top level LICENSE, COPYRIGHT, CONTRIBUTORS, NOTICE, and ACKNOWLEDGEMENTS files for details.
* ------------------------------------------------------------------------------------------------------------
*/
/**
* @file ErrorHandling.cpp
*/
#include "ErrorHandling.hpp"
#include "LvArray/src/system.hpp"
#include "common/DataTypes.hpp"
#include "common/logger/Logger.hpp"
#include "common/format/StringUtilities.hpp"
#include <fstream>
#include <regex>
#include <string_view>
// signal management
#include <csignal>
#include <cfenv>
#include <cstring>
namespace geos
{
static constexpr std::string_view g_level1Start = " - ";
static constexpr std::string_view g_level1Next = " ";
// static constexpr std::string_view g_level2Start = " - "; // unused for now
static constexpr std::string_view g_level2Next = " ";
static constexpr std::string_view g_level3Start = " - ";
static constexpr std::string_view g_level3Next = " ";
ErrorLogger g_errorLogger{};
ErrorLogger & ErrorLogger::global()
{ return g_errorLogger; }
ErrorLogger::ErrorLogger()
{
setDiagnosticInfoLevel( DiagnosticInfoLevel::Basic );
}
std::string ErrorContext::attributeToString( ErrorContext::Attribute attribute )
{
switch( attribute )
{
case ErrorContext::Attribute::InputFile: return "inputFile";
case ErrorContext::Attribute::InputLine: return "inputLine";
case ErrorContext::Attribute::DataPath: return "dataPath";
case ErrorContext::Attribute::DetectionLoc: return "detectionLocation";
case ErrorContext::Attribute::Signal: return "signal";
default: return "unknown";
}
}
DiagnosticMsgBuilder ErrorLogger::initCurrentExceptionMessage( MsgType msgType,
std::string_view msgContent,
integer rank )
{
DiagnosticMsg diagnosticMsg;
m_getCurrentExceptionMsg = DiagnosticMsgBuilder::init( diagnosticMsg,
msgType, msgContent,
rank )
.addCallStackInfo( LvArray::system::stackTrace( true ) )
.getDiagnosticMsg();
return DiagnosticMsgBuilder::modify( m_getCurrentExceptionMsg );
}
DiagnosticMsgBuilder DiagnosticMsgBuilder::init( DiagnosticMsg & msg,
MsgType msgType,
std::string_view msgContent,
integer rank )
{
return DiagnosticMsgBuilder( msg )
.setType( msgType )
.addToMsg( msgContent )
.addRank( rank );
}
DiagnosticMsgBuilder DiagnosticMsgBuilder::modify( DiagnosticMsg & errorMsg )
{
return DiagnosticMsgBuilder( errorMsg );
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::addContextInfoImpl( ErrorContext && ctxInfo )
{
auto lowerBoundPos = std::lower_bound( m_errorMsg.m_contextsInfo.begin(), m_errorMsg.m_contextsInfo.end(),
ctxInfo.m_priority,
[]( ErrorContext const & ctx, integer priority )
{ return ctx.m_priority >= priority; } );
m_errorMsg.m_contextsInfo.insert( lowerBoundPos, std::move( ctxInfo ) );
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::addDetectionLocation( string_view detectionLocation )
{
addContextInfo( ErrorContext{ string( detectionLocation ),
{ { ErrorContext::Attribute::DetectionLoc,
string( detectionLocation ) } } } );
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::addToMsg( std::exception const & e, bool const toEnd )
{
if( toEnd )
{
m_errorMsg.m_msg = m_errorMsg.m_msg + e.what();
}
else
{
m_errorMsg.m_msg = e.what() + m_errorMsg.m_msg;
}
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::addToMsg( std::string_view errorMsg, bool toEnd )
{
if( toEnd )
{
m_errorMsg.m_msg = m_errorMsg.m_msg + std::string( errorMsg );
}
else
{
m_errorMsg.m_msg = std::string( errorMsg ) + m_errorMsg.m_msg;
}
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::addSignal( integer const sig, bool const toEnd )
{
std::string errorMsg;
if( sig == SIGFPE )
{
errorMsg = "Floating point error encountered:";
if( std::fetestexcept( FE_DIVBYZERO ) )
errorMsg += "\n- Division by zero operation.";
if( std::fetestexcept( FE_INVALID ) )
errorMsg += "\n- Domain error occurred in an earlier floating-point operation.";
if( std::fetestexcept( FE_OVERFLOW ) )
errorMsg += "\n- The result of the earlier floating-point operation was too large to be representable.";
if( std::fetestexcept( FE_UNDERFLOW ) )
errorMsg += "\n- The result of the earlier floating-point operation was subnormal with a loss of precision.";
if( std::fetestexcept( FE_INEXACT ) )
errorMsg += "\n- Inexact result.";
if( !std::fetestexcept( FE_ALL_EXCEPT ) )
errorMsg += "\nUnknown reason.";
}
else
{
errorMsg = GEOS_FMT( "Signal encountered (no. {}): {}",
sig, ::strsignal( sig ));
}
// standard messages
addToMsg( errorMsg, toEnd );
this->addContextInfo( ErrorContext{ "Signal (detected from Signal Handler)",
{ { ErrorContext::Attribute::Signal,
std::to_string( sig ) },
{ ErrorContext::Attribute::DetectionLoc,
string( "Signal handler" ) }
} } );
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::setCodeLocation( std::string_view msgFile,
integer const msgLine )
{
m_errorMsg.m_file = msgFile;
m_errorMsg.m_line = msgLine;
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::setType( MsgType const msgType )
{
m_errorMsg.m_type = msgType;
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::setCause( std::string_view cause )
{
m_errorMsg.m_cause = cause;
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::addRank( integer const rank )
{
m_errorMsg.m_ranksInfo.emplace( rank );
return *this;
}
DiagnosticMsgBuilder & DiagnosticMsgBuilder::addCallStackInfo( std::string_view ossStackTrace )
{
std::string str = std::string( ossStackTrace );
std::istringstream iss( str );
std::string stackLine;
std::size_t index;
std::regex pattern( R"(Frame \d+: \S+)" );
while( std::getline( iss, stackLine ) )
{
if( std::regex_search( stackLine, pattern ))
{
m_errorMsg.m_isValidStackTrace = true;
index = stackLine.find( ':' );
m_errorMsg.m_sourceCallStack.push_back( stackLine.substr( index + 1 ) );
}
}
if( !m_errorMsg.m_isValidStackTrace )
{
m_errorMsg.m_sourceCallStack.push_back( str );
}
return *this;
}
DiagnosticMsg & DiagnosticMsgBuilder::getDiagnosticMsg()
{
return m_errorMsg;
}
void ErrorLogger::streamMultilineYamlAttribute( std::string_view msg, std::ofstream & yamlFile,
std::string_view indent )
{
std::size_t i = 0;
// Loop that runs through the string_view named msg
while( i < msg.size() )
{
// Index of the next line break
std::size_t index = msg.find( "\n", i );
// If there is no line break, the entire string is taken
if( index == std::string_view::npos )
{
index = msg.size();
}
// Writes the current line to the YAML file with the desired indentation
std::string_view msgLine = msg.substr( i, index - i );
yamlFile << indent << msgLine << "\n";
// Move to the next line
i = index + 1;
}
}
void ErrorLogger::createFile()
{
if( stringutilities::endsWith( m_filename, ".yaml" ) )
{
std::ofstream yamlFile( std::string( m_filename ), std::ios::out );
if( yamlFile.is_open() )
{
yamlFile << "errors: \n\n";
yamlFile.close();
}
else
{
GEOS_LOG_RANK( GEOS_FMT( "Unable to open error file for writing: {}", m_filename ) );
}
}
else
{
enableFileOutput( false );
GEOS_LOG_RANK( GEOS_FMT( "{} is a bad file name argument. The file must be in yaml format.", m_filename ) );
}
}
void ErrorLogger::setDiagnosticInfoLevel( DiagnosticInfoLevel const level )
{
switch( level )
{
case DiagnosticInfoLevel::Basic:
m_msgTypeSourceInfoEnabled.fill( false );
break;
case DiagnosticInfoLevel::ErrorSources:
m_msgTypeSourceInfoEnabled.fill( true );
m_msgTypeSourceInfoEnabled[integer( MsgType::Warning )] = false;
break;
case DiagnosticInfoLevel::WarningSources:
m_msgTypeSourceInfoEnabled.fill( true );
break;
default:
// if option has a wrong value, we output every details for any messages
m_msgTypeSourceInfoEnabled.fill( true );
break;
}
}
std::string ErrorLogger::typeToString( MsgType const type )
{
switch( type )
{
case MsgType::Error: return "Error";
case MsgType::Warning: return "Warning";
case MsgType::Exception: return "Exception";
case MsgType::ExternalError: return "ExternalError";
default: return "Unknown";
}
}
bool ErrorLogger::isSourceInfoEnabled( MsgType const type ) const
{
switch( type )
{
case MsgType::Error: return m_msgTypeSourceInfoEnabled[integer( MsgType::Error )];
case MsgType::Warning: return m_msgTypeSourceInfoEnabled[integer( MsgType::Warning )];
case MsgType::Exception: return m_msgTypeSourceInfoEnabled[integer( MsgType::Exception )];
case MsgType::ExternalError: return m_msgTypeSourceInfoEnabled[integer( MsgType::ExternalError )];
default: return m_msgTypeSourceInfoEnabled[integer( MsgType::Undefined )];
}
}
void ErrorLogger::formatMsgForLog( DiagnosticMsg const & errMsg,
std::ostream & os,
bool enableSourceInfo )
{
static constexpr string_view PREFIX = "***** ";
// --- HEADER ---
os << PREFIX << typeToString( errMsg.m_type ) << "\n";
if( enableSourceInfo && !errMsg.m_file.empty() )
{
os << PREFIX<< "LOCATION: " << errMsg.m_file;
if( errMsg.m_line > 0 )
{
os << ":" << errMsg.m_line;
}
os << "\n";
}
if( !errMsg.m_cause.empty())
{
os << PREFIX << errMsg.m_cause << "\n";
}
os << PREFIX << "Rank " << stringutilities::join( errMsg.m_ranksInfo, ", " ) << "\n";
// --- ERROR CONTEXT & MESSAGE ---
std::vector< ErrorContext > const & contexts = errMsg.m_contextsInfo;
if( contexts.empty() || contexts.front().m_formattedContext.empty())
{
os << PREFIX << "Message :\n";
}
else
{
os << PREFIX << "Message from " << contexts.front().m_formattedContext << ":\n";
}
if( !errMsg.m_msg.empty())
{
os << errMsg.m_msg << "\n";
}
if( contexts.size() > 1 )
{
os << PREFIX << "Additional contexts:\n";
for( size_t i = 1; i < contexts.size(); ++i )
{
os << PREFIX << "- " << contexts[i].m_formattedContext << "\n";
}
}
// --- STACKTRACE ---
if( enableSourceInfo && !errMsg.m_sourceCallStack.empty() )
{
os << "\n***** StackTrace of "<< errMsg.m_sourceCallStack.size() << " frames\n";
for( size_t i = 0; i < errMsg.m_sourceCallStack.size(); i++ )
{
os << GEOS_FMT( " - Frame {:2}: {}\n", i, errMsg.m_sourceCallStack[i] );
}
os << "*****\n";
}
// --- ENDING SPACE ---
os << "\n";
}
/**
* @brief Retrieve all informations from the ErrorMsg and format and write into a stream.
* @param errMsg Class containing all the error/warning information
* @param os The output stream to write the content to.
*/
void ErrorLogger::writeToLogStream( DiagnosticMsg & errMsg )
{
std::lock_guard< std::mutex > guard( m_errorHandlerAsciiMutex );
formatMsgForLog( errMsg,
m_stream,
isSourceInfoEnabled( errMsg.m_type ) );
m_stream.flush();
}
void ErrorLogger::writeToYamlStream( DiagnosticMsg & errMsg )
{
std::lock_guard< std::mutex > guard( m_errorHandlerYamlMutex );
std::ofstream yamlFile( std::string( m_filename ), std::ios::app );
if( yamlFile.is_open() )
{
// General errors info (type, rank on which the error occured)
yamlFile << g_level1Start << "type: " << typeToString( errMsg.m_type ) << "\n";
yamlFile << g_level1Next << "rank: " << stringutilities::join( errMsg.m_ranksInfo, "," );
yamlFile << "\n";
// Error message
yamlFile << g_level1Next << "message: >-\n";
streamMultilineYamlAttribute( errMsg.m_msg, yamlFile, g_level2Next );
// context information
if( !errMsg.m_contextsInfo.empty() )
{
std::vector< ErrorContext > contextInfo = errMsg.m_contextsInfo;
// Sort contextual information by decreasing priority
std::sort( contextInfo.begin(), contextInfo.end(),
[]( const ErrorContext & a, const ErrorContext & b ) {
return a.m_priority > b.m_priority;
} );
// Additional informations about the context of the error and priority information of each context
yamlFile << g_level1Next << "contexts:\n";
for( ErrorContext const & ctxInfo : contextInfo )
{
yamlFile << g_level3Start << "priority: " << ctxInfo.m_priority << "\n";
if( !ctxInfo.m_formattedContext.empty())
{
yamlFile << g_level3Next << "description: " << ctxInfo.m_formattedContext << "\n";
}
for( auto const & [key, value] : ctxInfo.m_attributes )
{
yamlFile << g_level3Next << ErrorContext::attributeToString( key ) << ": " << value << "\n";
}
}
}
// error cause
if( !errMsg.m_cause.empty() )
{
yamlFile << g_level1Next << "cause: >-\n";
streamMultilineYamlAttribute( errMsg.m_cause, yamlFile, g_level2Next );
}
// Location of the error in the code
if( !errMsg.m_file.empty() )
{
yamlFile << g_level1Next << "sourceLocation:\n";
yamlFile << g_level2Next << "file: " << errMsg.m_file << "\n";
if( errMsg.m_line > 0 )
{
yamlFile << g_level2Next << "line: " << errMsg.m_line << "\n";
}
}
// Information about the stack trace
if( !errMsg.m_sourceCallStack.empty() )
{
yamlFile << g_level1Next << "sourceCallStack:\n";
for( size_t i = 0; i < errMsg.m_sourceCallStack.size(); i++ )
{
yamlFile << ( errMsg.m_isValidStackTrace ?
GEOS_FMT( "{}frame{}: {}\n", g_level3Start, i, errMsg.m_sourceCallStack[i] ) :
GEOS_FMT( "{}{}\n", g_level3Start, errMsg.m_sourceCallStack[i] ) );
}
}
yamlFile << "\n";
yamlFile.flush();
errMsg = DiagnosticMsg();
}
else
{
GEOS_LOG_RANK( GEOS_FMT( "Unable to open error file for writing.\n- Error file: {}\n", m_filename ) );
}
}
void ErrorLogger::flushErrorMsg( DiagnosticMsg & errMsg )
{
writeToLogStream( errMsg );
if( isOutputFileEnabled() )
{
writeToYamlStream( errMsg );
}
}
void ErrorLogger::flushCurrentExceptionMessage()
{
writeToLogStream( m_getCurrentExceptionMsg );
if( isOutputFileEnabled() )
{
writeToYamlStream( m_getCurrentExceptionMsg );
}
}
} /* namespace geos */