Debian Codegraph @

src/Main/sentryIntegration.cxx

raw symbols SCIP
1 // sentryIntegration.cxx - Interface with Sentry.io crash reporting
2 //
3 // SPDX-FileCopyrightText: (C) 2018 James Turner <[email protected]>
4 // SPDX-License-Identifier: GPL-2.0-or-later
5
6 #include "config.h"
7
8 #include "sentryIntegration.hxx"
9
10 #include <cstring> // for strcmp
11
12 #include <simgear/debug/ErrorReportingCallback.hxx>
13 #include <simgear/debug/LogCallback.hxx>
14 #include <simgear/debug/Reporting.hxx>
15 #include <simgear/debug/logstream.hxx>
16
17 #include <simgear/io/iostreams/sgstream.hxx>
18 #include <simgear/misc/sg_path.hxx>
19 #include <simgear/props/props.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/structure/exception.hxx>
22
23 #include <Main/fg_init.hxx>
24 #include <Main/fg_props.hxx>
25 #include <Main/globals.hxx>
26
27 #include <flightgearBuildId.h>
28
29 bool doesStringMatchPrefixes(const std::string& s, const std::initializer_list<const char*>& prefixes)
30 {
31 if (s.empty())
32 return false;
33
34
35 for (auto c : prefixes) {
36 if (s.find(c) == 0)
37 return true;
38 }
39
40 return false;
41 }
42
43 auto OSG_messageWhitelist = {
44 "PNG lib warning : iCCP: known incorrect sRGB profile",
45 "PNG lib warning : iCCP: profile 'ICC Profile': 1000000h: invalid rendering intent",
46 "osgDB ac3d reader: detected surface with less than 3",
47 "osgDB ac3d reader: detected line with less than 2",
48 "Detected particle system using segment(s) with less than 2 vertices"};
49
50 auto exception_messageWhitelist = {
51 "position is invalid, NaNs", ///< avoid spam when NaNs occur
52 "bad AI flight plan", ///< adjusting logic to avoid this is tricky
53 "couldn't find shader", ///< handled separately
54 "(EMEXEC)", ///< Emesary log spam
55 /// suppress noise from user-entered METAR values : we special case
56 /// when live metar fails to parse
57 "metar data bogus",
58 "metar data incomplete"
59 };
60
61 auto general_messageWhitelist = {
62 " -- Recipient", ///< emmessary overrun message, note leading whitespace
63 "Overrun: GlobalTransmitter", ///< emmesary overrun message
64 };
65
66 // we don't want sentry enabled for the test suite
67 #if defined(HAVE_SENTRY) && !defined(BUILDING_TESTSUITE)
68
69 static bool static_sentryEnabled = false;
70 static std::string static_sentryUUID;
71
72 #include <sentry.h>
73
74 namespace {
75
76 // this callback is invoked whenever an instance of sg_throwable is created.
77 // therefore we can log the stack trace at that point
78 void sentryTraceSimgearThrow(const std::string& msg, const std::string& origin, const sg_location& loc)
79 {
80 if (!static_sentryEnabled)
81 return;
82
83 if (doesStringMatchPrefixes(msg, exception_messageWhitelist)) {
84 return;
85 }
86
87 sentry_value_t exc = sentry_value_new_object();
88 sentry_value_set_by_key(exc, "type", sentry_value_new_string("Exception"));
89
90 std::string message = msg;
91 sentry_value_t info = sentry_value_new_object();
92 if (!origin.empty()) {
93 sentry_value_set_by_key(info, "origin", sentry_value_new_string(origin.c_str()));
94 }
95
96 if (loc.isValid()) {
97 const auto ls = loc.asString();
98 sentry_value_set_by_key(info, "location", sentry_value_new_string(ls.c_str()));
99 }
100
101 sentry_set_context("what", info);
102 sentry_value_set_by_key(exc, "value", sentry_value_new_string(message.c_str()));
103
104 sentry_value_t event = sentry_value_new_event();
105 sentry_value_set_by_key(event, "exception", exc);
106
107 sentry_event_value_add_stacktrace(event, nullptr, 0);
108 sentry_capture_event(event);
109 }
110
111 class SentryLogCallback : public simgear::LogCallback
112 {
113 public:
114 SentryLogCallback() : simgear::LogCallback(SG_ALL, SG_WARN)
115 {
116 }
117
118 bool doProcessEntry(const simgear::LogEntry& e) override
119 {
120 // we need original priority here, so we don't record MANDATORY_INFO
121 // or DEV_ messages, which would get noisy.
122 const auto op = e.originalPriority;
123 if ((op != SG_WARN) && (op != SG_ALERT)) {
124 return true;
125 }
126
127 if ((e.debugClass == SG_OSG) && doesStringMatchPrefixes(e.message, OSG_messageWhitelist)) {
128 return true;
129 }
130
131 if (doesStringMatchPrefixes(e.message, general_messageWhitelist)) {
132 return true;
133 }
134
135 if (e.message == _lastLoggedMessage) {
136 _lastLoggedCount++;
137 return true;
138 }
139
140 if (_lastLoggedCount > 0) {
141 flightgear::addSentryBreadcrumb("(repeats " + std::to_string(_lastLoggedCount) + " times)", "info");
142 _lastLoggedCount = 0;
143 }
144
145 _lastLoggedMessage = e.message;
146 flightgear::addSentryBreadcrumb(e.message, (op == SG_WARN) ? "warning" : "error");
147 return true;
148 }
149
150 private:
151 std::string _lastLoggedMessage;
152 int _lastLoggedCount = 0;
153 };
154
155 const auto missingShaderPrefix = std::string{"Missing shader"};
156
157 string_list anon_missingShaderList;
158
159 bool isNewMissingShader(const std::string& path)
160 {
161 auto it = std::find(anon_missingShaderList.begin(), anon_missingShaderList.end(), path);
162 if (it != anon_missingShaderList.end()) {
163 return false;
164 }
165
166 anon_missingShaderList.push_back(path);
167 return true;
168 }
169
170 void sentrySimgearReportCallback(const std::string& msg, const std::string& more, bool isFatal)
171 {
172 // don't duplicate reports for missing shaders, once per sessions
173 // is sufficient
174 using simgear::strutils::starts_with;
175 if (starts_with(msg, missingShaderPrefix)) {
176 if (!isNewMissingShader(more)) {
177 return;
178 }
179 }
180
181 sentry_value_t exc = sentry_value_new_object();
182 if (isFatal) {
183 sentry_value_set_by_key(exc, "type", sentry_value_new_string("Fatal Error"));
184 } else {
185 sentry_value_set_by_key(exc, "type", sentry_value_new_string("Exception"));
186 }
187
188 sentry_value_set_by_key(exc, "value", sentry_value_new_string(msg.c_str()));
189
190 sentry_value_t event = sentry_value_new_event();
191 sentry_value_set_by_key(event, "exception", exc);
192
193 sentry_event_value_add_stacktrace(event, nullptr, 0);
194 sentry_capture_event(event);
195 }
196
197 void sentryReportBadAlloc()
198 {
199 if (simgear::ReportBadAllocGuard::isSet()) {
200 sentry_value_t sentryMessage = sentry_value_new_object();
201 sentry_value_set_by_key(sentryMessage, "type", sentry_value_new_string("Fatal Error"));
202 sentry_value_set_by_key(sentryMessage, "formatted", sentry_value_new_string("bad allocation"));
203
204 sentry_value_t event = sentry_value_new_event();
205 sentry_value_set_by_key(event, "message", sentryMessage);
206
207 sentry_event_value_add_stacktrace(event, nullptr, 0);
208 sentry_capture_event(event);
209 }
210
211 throw std::bad_alloc(); // allow normal processing
212 }
213
214 } // namespace
215
216 namespace flightgear {
217
218 bool sentryReportCommand(const SGPropertyNode* args, SGPropertyNode* root)
219 {
220 if (!static_sentryEnabled) {
221 SG_LOG(SG_GENERAL, SG_WARN, "Sentry.io not enabled at startup");
222 return false;
223 }
224
225 sentry_value_t exc = sentry_value_new_object();
226 sentry_value_set_by_key(exc, "type", sentry_value_new_string("Report"));
227
228 const auto message = args->getStringValue("message");
229 sentry_value_set_by_key(exc, "value", sentry_value_new_string(message.c_str()));
230
231 sentry_value_t event = sentry_value_new_event();
232 sentry_value_set_by_key(event, "exception", exc);
233 // capture the C++ stack-trace. Probably not that useful but can't hurt
234 sentry_event_value_add_stacktrace(event, nullptr, 0);
235
236 sentry_capture_event(event);
237
238 return true;
239 }
240
241 bool sentrySendError(const SGPropertyNode* args, SGPropertyNode* root)
242 {
243 if (!static_sentryEnabled) {
244 SG_LOG(SG_GENERAL, SG_WARN, "Sentry.io not enabled at startup");
245 return false;
246 }
247
248 try {
249 throw sg_io_exception("Invalid flurlbe", sg_location("/Some/dummy/path/bar.txt", 100, 200));
250 } catch (sg_exception& e) {
251 SG_LOG(SG_GENERAL, SG_WARN, "caught dummy exception");
252 }
253
254 return true;
255 }
256
257 std::string sentryUserId()
258 {
259 if (!static_sentryUUID.empty()) {
260 return static_sentryUUID;
261 }
262
263 const auto uuidPath = fgHomePath() / "sentry_uuid.txt";
264 if (!uuidPath.exists()) {
265 return {};
266 }
267
268 sg_ifstream f(uuidPath);
269 std::getline(f, static_sentryUUID);
270 return static_sentryUUID;
271 }
272
273 void initSentry(bool quiet)
274 {
275 sentry_options_t* options = sentry_options_new();
276 // API key is defined in config.h, set in an environment variable prior
277 // to running CMake, so it can be customised. Env var at build time is:
278 // FLIGHTGEAR_SENTRY_API_KEY
279 sentry_options_set_dsn(options, SENTRY_API_KEY);
280
281 if (strcmp(FG_BUILD_TYPE, "Dev") == 0) {
282 sentry_options_set_environment(options, "dev");
283 sentry_options_set_release(options, "flightgear-dev@" REVISION);
284 } else if (strcmp(FG_BUILD_TYPE, "Nightly") == 0) {
285 sentry_options_set_environment(options, "dev");
286 // we use the build year and month here to cluster nightly builds in Sentry.
287 // the idea being that this is sufficient granularity to notice when an issue
288 // first occurs, and then bisect the commits. We could switch to using
289 // year and week number, but this makes more noise in sentry.
290 sentry_options_set_release(options, "flightgear-nightly@" BUILD_MONTH);
291 sentry_options_set_environment(options, "testing");
292 } else if (strcmp(FG_BUILD_TYPE, "Release") == 0) {
293 // RC builds are for testing
294 if (strncmp(BUILD_SUFFIX, "rc", 2) == 0) {
295 sentry_options_set_environment(options, "testing");
296 } else {
297 sentry_options_set_environment(options, "production");
298 }
299
300 sentry_options_set_release(options, FLIGHTGEAR_VERSION);
301 } else {
302 // unknown build type
303 sentry_options_set_environment(options, "dev");
304 }
305
306 const auto buildString = std::to_string(JENKINS_BUILD_NUMBER);
307 sentry_options_set_dist(options, buildString.c_str());
308
309 // for dev / nightly builds, put Sentry in debug mode
310 if (!quiet && strcmp(FG_BUILD_TYPE, "Release")) {
311 sentry_options_set_debug(options, 1);
312 }
313
314 SGPath dataPath = fgHomePath() / "sentry_db";
315 #if defined(SG_WINDOWS)
316 const auto homePathString = dataPath.wstr();
317 sentry_options_set_database_pathw(options, homePathString.c_str());
318
319 const auto logPath = (fgHomePath() / "fgfs.log").wstr();
320 sentry_options_add_attachmentw(options, logPath.c_str());
321 #else
322 const auto homePathString = dataPath.utf8Str();
323 sentry_options_set_database_path(options, homePathString.c_str());
324
325 const auto logPath = (fgHomePath() / "fgfs.log").utf8Str();
326 sentry_options_add_attachment(options, logPath.c_str());
327 #endif
328
329 const auto uuidPath = fgHomePath() / "sentry_uuid.txt";
330 bool generateUuid = true;
331 std::string uuid;
332 if (uuidPath.exists()) {
333 sentryUserId(); // will cache into static_sentryUUID as a side-effect
334
335 // if we read enough bytes, that this is a valid UUID, then accept it
336 if (static_sentryUUID.length() >= 36) {
337 generateUuid = false;
338 }
339 }
340
341 // we need to generate a new UUID
342 if (generateUuid) {
343 // use the Sentry APi to generate one
344 sentry_uuid_t su = sentry_uuid_new_v4();
345 char bytes[38];
346 sentry_uuid_as_string(&su, bytes);
347 bytes[37] = 0;
348
349 static_sentryUUID = std::string{bytes};
350 // write it back to disk for next time
351 sg_ofstream f(uuidPath);
352 f << static_sentryUUID << std::endl;
353 }
354
355 if (sentry_init(options) == 0) {
356 static_sentryEnabled = true;
357 sentry_value_t user = sentry_value_new_object();
358 sentry_value_t userUuidV = sentry_value_new_string(static_sentryUUID.c_str());
359 sentry_value_set_by_key(user, "id", userUuidV);
360 sentry_set_user(user);
361
362 sglog().addCallback(new SentryLogCallback);
363 setThrowCallback(sentryTraceSimgearThrow);
364 simgear::setErrorReportCallback(sentrySimgearReportCallback);
365
366 std::set_new_handler(sentryReportBadAlloc);
367 } else {
368 SG_LOG(SG_GENERAL, SG_WARN, "Failed to init Sentry reporting");
369 static_sentryEnabled = false;
370 }
371 }
372
373 void delayedSentryInit()
374 {
375 if (!static_sentryEnabled)
376 return;
377
378 // allow the user to opt-out of sentry.io features
379 if (!fgGetBool("/sim/startup/sentry-crash-reporting-enabled", true)) {
380 SG_LOG(SG_GENERAL, SG_INFO, "Disabling Sentry.io reporting");
381 sentry_shutdown();
382 static_sentryEnabled = false;
383 return;
384 }
385
386 globals->get_commands()->addCommand("sentry-report", &sentryReportCommand);
387 globals->get_commands()->addCommand("sentry-exception", &sentrySendError);
388
389 // expose the anonymous user UUID to the property tree, so users
390 // can share it if they wish
391 fgSetString("/sim/crashreport/sentry-user-id", static_sentryUUID);
392 }
393
394 void shutdownSentry()
395 {
396 if (static_sentryEnabled) {
397 sentry_shutdown();
398 static_sentryEnabled = false;
399 }
400 }
401
402 bool isSentryEnabled()
403 {
404 return static_sentryEnabled;
405 }
406
407 void addSentryBreadcrumb(const std::string& msg, const std::string& level)
408 {
409 if (!static_sentryEnabled)
410 return;
411
412 sentry_value_t crumb = sentry_value_new_breadcrumb("default", msg.c_str());
413 sentry_value_set_by_key(crumb, "level", sentry_value_new_string(level.c_str()));
414 sentry_add_breadcrumb(crumb);
415 }
416
417 void addSentryTag(const char* tag, const char* value)
418 {
419 if (!static_sentryEnabled)
420 return;
421
422 if (!tag || !value)
423 return;
424
425 sentry_set_tag(tag, value);
426 }
427
428 void updateSentryTag(const std::string& tag, const std::string& value)
429 {
430 if (tag.empty() || value.empty())
431 return;
432
433 if (!static_sentryEnabled)
434 return;
435
436 sentry_remove_tag(tag.c_str());
437 sentry_set_tag(tag.c_str(), value.c_str());
438 }
439
440 void sentryReportNasalError(const std::string& msg, const string_list& stack)
441 {
442 if (!static_sentryEnabled)
443 return;
444 #if 0
445 sentry_value_t exc = sentry_value_new_object();
446 sentry_value_set_by_key(exc, "type", sentry_value_new_string("Exception"));
447 sentry_value_set_by_key(exc, "value", sentry_value_new_string(msg.c_str()));
448
449 sentry_value_t stackData = sentry_value_new_list();
450 for (const auto& nasalFrame : stack) {
451 sentry_value_append(stackData, sentry_value_new_string(nasalFrame.c_str()));
452 }
453 sentry_value_set_by_key(exc, "stack", stackData);
454
455
456 sentry_value_t event = sentry_value_new_event();
457 sentry_value_set_by_key(event, "exception", exc);
458
459 // add the Nasal stack trace data
460
461 // capture the C++ stack-trace. Probably not that useful but can't hurt
462 sentry_event_value_add_stacktrace(event, nullptr, 0);
463
464 sentry_capture_event(event);
465
466 #endif
467 }
468
469 void sentryReportException(const std::string& msg, const std::string& location)
470 {
471 if (!static_sentryEnabled)
472 return;
473
474 sentry_value_t exc = sentry_value_new_object();
475 sentry_value_set_by_key(exc, "type", sentry_value_new_string("Exception"));
476
477
478 sentry_value_t info = sentry_value_new_object();
479 if (!location.empty()) {
480 sentry_value_set_by_key(info, "location", sentry_value_new_string(location.c_str()));
481 }
482 sentry_set_context("what", info);
483
484 sentry_value_set_by_key(exc, "value", sentry_value_new_string(msg.c_str()));
485
486 sentry_value_t event = sentry_value_new_event();
487 sentry_value_set_by_key(event, "exception", exc);
488
489 // capture the C++ stack-trace. Probably not that useful but can't hurt
490 sentry_event_value_add_stacktrace(event, nullptr, 0);
491 sentry_capture_event(event);
492 }
493
494 void sentryReportFatalError(const std::string& msg, const std::string& more)
495 {
496 if (!static_sentryEnabled)
497 return;
498
499 sentry_value_t sentryMessage = sentry_value_new_object();
500 sentry_value_set_by_key(sentryMessage, "type", sentry_value_new_string("Fatal Error"));
501
502 sentry_value_t info = sentry_value_new_object();
503 if (!more.empty()) {
504 sentry_value_set_by_key(info, "more", sentry_value_new_string(more.c_str()));
505 }
506
507 sentry_set_context("what", info);
508 sentry_value_set_by_key(sentryMessage, "formatted", sentry_value_new_string(msg.c_str()));
509
510 sentry_value_t event = sentry_value_new_event();
511 sentry_value_set_by_key(event, "message", sentryMessage);
512
513 sentry_event_value_add_stacktrace(event, nullptr, 0);
514 sentry_capture_event(event);
515 }
516
517 void sentryReportUserError(const std::string& aggregate, const std::string& parameter, const std::string& details)
518 {
519 if (!static_sentryEnabled)
520 return;
521
522 sentry_value_t sentryMessage = sentry_value_new_object();
523 sentry_value_set_by_key(sentryMessage, "type", sentry_value_new_string("Error"));
524
525 sentry_value_t info = sentry_value_new_object();
526 sentry_value_set_by_key(info, "details", sentry_value_new_string(details.c_str()));
527
528 sentry_set_context("what", info);
529
530 auto m = aggregate;
531 if (!parameter.empty()) {
532 m += ":" + parameter;
533 }
534
535 sentry_value_t event = sentry_value_new_event();
536 sentry_value_set_by_key(event, "message", sentry_value_new_string(m.c_str()));
537
538 sentry_capture_event(event);
539 }
540
541 } // namespace flightgear
542
543 #else
544
545 // stubs for non-sentry case
546
547 namespace flightgear {
548
549 void initSentry()
550 {
551 }
552
553 void shutdownSentry()
554 {
555 }
556
557 void delayedSentryInit()
558 {
559 }
560
561 bool isSentryEnabled()
562 {
563 return false;
564 }
565
566 std::string sentryUserId()
567 {
568 return {};
569 }
570
571
572 void addSentryBreadcrumb(const std::string&, const std::string&)
573 {
574 }
575
576 void addSentryTag(const char*, const char*)
577 {
578 }
579
580 void updateSentryTag(const std::string&, const std::string&)
581 {
582 }
583
584
585 void sentryReportNasalError(const std::string&, const string_list&)
586 {
587 }
588
589 void sentryReportException(const std::string&, const std::string&)
590 {
591 }
592
593 void sentryReportFatalError(const std::string&, const std::string&)
594 {
595 }
596
597 void sentryReportUserError(const std::string&, const std::string&, const std::string&)
598 {
599 }
600
601 } // namespace flightgear
602
603 #endif
604
605 // common helpers
606
607 namespace flightgear {
608
609 void addSentryTag(const std::string& tag, const std::string& value)
610 {
611 if (tag.empty() || value.empty())
612 return;
613
614 addSentryTag(tag.c_str(), value.c_str());
615 }
616
617 } // namespace flightgear