Debian Codegraph @

src/Main/ErrorReporter.cxx

raw symbols SCIP
1 /*
2 * SPDX-FileName: ErrorReporter.cxx
3 * SPDX-FileComment: This file is part of the program FlightGear
4 * SPDX-FileCopyrightText: Copyright (C) 2021 James Turner
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include "config.h"
9 #include "fg_props.hxx"
10
11 #include "ErrorReporter.hxx"
12
13 #include <algorithm>
14 #include <ctime> // for strftime, etc
15 #include <deque>
16 #include <map>
17 #include <mutex>
18 #include <string>
19
20 #include <simgear/debug/ErrorReportingCallback.hxx>
21 #include <simgear/debug/LogCallback.hxx>
22 #include <simgear/timing/timestamp.hxx>
23
24 #include <simgear/io/iostreams/sgstream.hxx>
25 #include <simgear/structure/commands.hxx>
26
27 #include <GUI/MessageBox.hxx>
28 #include <GUI/dialog.hxx>
29 #include <GUI/new_gui.hxx>
30
31 #include <Main/fg_props.hxx>
32 #include <Main/globals.hxx>
33 #include <Main/locale.hxx>
34 #include <Main/options.hxx>
35 #include <Main/sentryIntegration.hxx>
36 #include <Model/validateSharedModels.hxx>
37 #include <Scripting/NasalClipboard.hxx> // clipboard access
38
39 using simgear::LoadFailure;
40 using std::string;
41
42 namespace {
43
44 const double MinimumIntervalBetweenDialogs = 5.0;
45 const double NoNewErrorsTimeout = 8.0;
46
47 // map of context values; we allow a stack of values for
48 // cases such as sub-sub-model loading where we might process repeated
49 // nested model XML files
50 using PerThreadErrorContextStack = std::map<std::string, string_list>;
51
52 // context storage. This is per-thread so parallel osgDB threads don't
53 // confuse each other
54 static thread_local PerThreadErrorContextStack thread_errorContextStack;
55 /**
56 Define the aggregation points we use for errors, to direct the user towards the likely
57 source of problems.
58 */
59 enum class Aggregation {
60 MainAircraft,
61 HangarAircraft, // handle hangar aircraft differently
62 CustomScenery,
63 TerraSync,
64 AddOn,
65 Scenario,
66 InputDevice,
67 FGData,
68 MultiPlayer,
69 Unknown, ///< error coudln't be attributed more specifcially
70 OutOfMemory, ///< separate category to give it a custom message
71 SharedModels, ///< special category, for when shared models are not found
72 Traffic,
73 ShadersEffects,
74 NetworkFailure, ///< category for issues related to (local) connectivity
75 };
76
77 // these should correspond to simgear::ErrorCode enum
78 // they map to translateable strings in fgdata/Translations/sys.xml
79
80 string_list static_errorIds = {
81 "error-missing-shader",
82 "error-loading-texture",
83 "error-xml-model-load",
84 "error-3D-model-load",
85 "error-btg-load",
86 "error-scenario-load",
87 "error-dialog-load",
88 "error-audio-fx-load",
89 "error-xml-load-command",
90 "error-aircraft-systems",
91 "error-input-device-config",
92 "error-ai-traffic-schedule",
93 "error-terrasync"};
94
95 string_list static_errorTypeIds = {
96 "error-type-unknown",
97 "error-type-not-found",
98 "error-type-out-of-memory",
99 "error-type-bad-header",
100 "error-type-bad-data",
101 "error-type-misconfigured",
102 "error-type-io",
103 "error-type-network"};
104
105
106 string_list static_categoryIds = {
107 "error-category-aircraft",
108 "error-category-aircraft-from-hangar",
109 "error-category-custom-scenery",
110 "error-category-terrasync",
111 "error-category-addon",
112 "error-category-scenario",
113 "error-category-input-device",
114 "error-category-fgdata",
115 "error-category-multiplayer",
116 "error-category-unknown",
117 "error-category-out-of-memory",
118 "error-category-shared-models",
119 "error-category-traffic",
120 "error-category-shaders",
121 "error-category-network"};
122
123 class RecentLogCallback : public simgear::LogCallback
124 {
125 public:
126 RecentLogCallback() : simgear::LogCallback(SG_ALL, SG_INFO)
127 {
128 }
129
130 bool doProcessEntry(const simgear::LogEntry& e) override
131 {
132 std::ostringstream os;
133 if (e.file != nullptr) {
134 os << e.file << ":" << e.line << ":\t";
135 }
136
137
138 os << e.message;
139
140 std::lock_guard<std::mutex> g(_lock); // begin access to shared state
141 _recentLogEntries.push_back(os.str());
142
143 while (_recentLogEntries.size() > _preceedingLogMessageCount) {
144 _recentLogEntries.pop_front();
145 }
146
147 return true;
148 }
149
150 string_list copyRecentLogEntries() const
151 {
152 std::lock_guard<std::mutex> g(_lock); // begin access to shared state
153
154 string_list r(_recentLogEntries.begin(), _recentLogEntries.end());
155 return r;
156 }
157
158 private:
159 mutable std::mutex _lock;
160 size_t _preceedingLogMessageCount = 6;
161
162 using LogDeque = std::deque<string>;
163 LogDeque _recentLogEntries;
164 };
165
166 std::string lastPathComponent(const std::string& d)
167 {
168 const auto lastSlash = d.rfind('/');
169 return d.substr(lastSlash + 1);
170 }
171
172 } // namespace
173
174 namespace flightgear {
175
176 class ErrorReporter::ErrorReporterPrivate
177 {
178 public:
179 bool _reportsDirty = false;
180 std::mutex _lock;
181 SGTimeStamp _nextShowTimeout;
182 bool _haveDonePostInit = false;
183 bool _isEnabled = true;
184
185 bool _enabled = true;
186 SGPropertyNode_ptr _enabledNode;
187 SGPropertyNode_ptr _displayNode;
188 SGPropertyNode_ptr _activeErrorNode;
189 SGPropertyNode_ptr _mpReportNode;
190 bool _popupEnabled = true;
191
192 using ErrorContext = std::map<std::string, std::string>;
193 /**
194 @brief structure representing a single error which has occurred
195 */
196 struct ErrorOcurrence {
197 simgear::ErrorCode code;
198 simgear::LoadFailure type;
199 string detailedInfo;
200 sg_location origin;
201 time_t when;
202 string_list log;
203 ErrorContext context;
204
205 bool hasContextKey(const std::string& key) const
206 {
207 return context.find(key) != context.end();
208 }
209
210 std::string getContextValue(const std::string& key) const
211 {
212 auto it = context.find(key);
213 if (it == context.end())
214 return {};
215
216 return it->second;
217 }
218 };
219
220 using OccurrenceVec = std::vector<ErrorOcurrence>;
221
222 std::unique_ptr<RecentLogCallback> _logCallback;
223 bool _logCallbackRegistered = false;
224
225 string _terrasyncPathPrefix;
226 string _fgdataPathPrefix;
227 string _aircraftDirectoryName;
228
229 /**
230 @brief heuristic to identify relative paths as origination from the main aircraft as opposed
231 to something else. This is based on containing the aircraft directory name.
232 */
233 bool isMainAircraftPath(const std::string& path) const;
234
235 bool isAnyAircraftPath(const std::string& path) const;
236
237 static bool isFGDataPath(const std::string& path);
238
239 /**
240 @brief structure representing one or more errors, aggregated together
241
242 This is what we send to Sentry, or present to the user, after combining occurrences from
243 the same / related sources, or duplicates.
244 */
245 struct AggregateReport {
246 Aggregation type;
247 std::string parameter; ///< base on type, the specific point. For example the add-on ID, AI model ident or custom scenery path
248 SGTimeStamp lastErrorTime;
249
250 bool haveShownToUser = false;
251 OccurrenceVec errors;
252 bool isCritical = false;
253 bool isMessage = false;
254
255 bool addOccurence(const ErrorOcurrence& err);
256
257 using OcurrencePredicate = std::function<bool(const ErrorOcurrence&)>;
258 bool allOccurences(OcurrencePredicate pred) const;
259 };
260
261
262 using AggregateErrors = std::vector<AggregateReport>;
263 AggregateErrors _aggregated;
264 int _activeReportIndex = -1;
265 string_list _significantProperties; ///< properties we want to include in reports, for debugging
266
267 /**
268 find the appropriate agrgegate for an error, based on its context
269 */
270 AggregateErrors::iterator getAggregateForOccurence(const ErrorOcurrence& oc);
271
272 AggregateErrors::iterator getAggregate(Aggregation ag, const std::string& param = {});
273
274 AggregateErrors::iterator mainAircraftAggregate();
275
276
277 void collectError(simgear::LoadFailure type, simgear::ErrorCode code, const std::string& details, const sg_location& location)
278 {
279 ErrorOcurrence occurrence{code, type, details, location, time(nullptr), string_list(), ErrorContext()};
280
281 // snapshot the top of the context stacks into our occurrence data
282 for (const auto& c : thread_errorContextStack) {
283 occurrence.context[c.first] = c.second.back();
284 }
285
286 occurrence.log = _logCallback->copyRecentLogEntries();
287
288 std::lock_guard<std::mutex> g(_lock); // begin access to shared state
289 auto it = getAggregateForOccurence(occurrence);
290
291 // add to the occurrence, if it's not a duplicate
292 if (!it->addOccurence(occurrence)) {
293 return; // duplicate, nothing else to do
294 }
295
296 // log it once we know it's not a duplicate
297 SG_LOG(SG_GENERAL, SG_ALERT, "Error:" << static_errorTypeIds.at(static_cast<int>(type)) << " from " << static_errorIds.at(static_cast<int>(code)) << "::" << details << "\n\t" << location.asString());
298
299 if (!_enabled) {
300 return;
301 }
302
303 it->lastErrorTime.stamp();
304 _reportsDirty = true;
305
306 const auto ty = it->type;
307 // decide if it's a critical error or not
308 // aircraft errors are critical if they occur during initial
309 // aircraft load, otherwise we just show the warning
310 if (!_haveDonePostInit && (ty == Aggregation::MainAircraft)) {
311 it->isCritical = true;
312 }
313 }
314
315 void collectContext(const std::string& key, const std::string& value)
316 {
317 if (value == "POP") {
318 auto it = thread_errorContextStack.find(key);
319 assert(it != thread_errorContextStack.end());
320 assert(!it->second.empty());
321 it->second.pop_back();
322 if (it->second.empty()) {
323 thread_errorContextStack.erase(it);
324 }
325 } else {
326 thread_errorContextStack[key].push_back(value);
327 }
328 }
329
330 void presentErrorToUser(AggregateReport& report)
331 {
332 const int catId = static_cast<int>(report.type);
333 auto catLabel = globals->get_locale()->getLocalizedString(static_categoryIds.at(catId), "sys");
334
335 catLabel = simgear::strutils::replace(catLabel, "%VALUE%", report.parameter);
336
337 _displayNode->setStringValue("category", catLabel);
338
339
340 auto ns = globals->get_locale()->getLocalizedString("error-next-steps", "sys");
341 _displayNode->setStringValue("next-steps", ns);
342
343
344 // remove any existing error children
345 _displayNode->removeChildren("error");
346
347 std::ostringstream detailsTextStream;
348
349 // add all the discrete errors as child nodes with all their information
350 for (const auto& e : report.errors) {
351 SGPropertyNode_ptr errNode = _displayNode->addChild("error");
352 const auto em = globals->get_locale()->getLocalizedString(static_errorIds.at(static_cast<int>(e.code)), "sys");
353 errNode->setStringValue("message", em);
354 errNode->setIntValue("code", static_cast<int>(e.code));
355
356 const auto et = globals->get_locale()->getLocalizedString(static_errorTypeIds.at(static_cast<int>(e.type)), "sys");
357 errNode->setStringValue("type-message", et);
358 errNode->setIntValue("type", static_cast<int>(e.type));
359 errNode->setStringValue("details", e.detailedInfo);
360
361 detailsTextStream << em << ": " << et << "\n";
362 detailsTextStream << "(" << e.detailedInfo << ")\n";
363
364 if (e.origin.isValid()) {
365 errNode->setStringValue("location", e.origin.asString());
366 detailsTextStream << " from:" << e.origin.asString() << "\n";
367 }
368
369 detailsTextStream << "\n";
370 } // of errors within the report iteration
371
372 _displayNode->setStringValue("details-text", detailsTextStream.str());
373 _activeErrorNode->setBoolValue(true);
374
375 report.haveShownToUser = true;
376
377 // compute index; slightly clunky, find the report in _aggregated
378 auto it = std::find_if(_aggregated.begin(), _aggregated.end(), [report](const AggregateReport& a) {
379 if (a.type != report.type) return false;
380 return report.parameter.empty() ? true : report.parameter == a.parameter;
381 });
382 assert(it != _aggregated.end());
383 _activeReportIndex = static_cast<int>(std::distance(_aggregated.begin(), it));
384 _displayNode->setIntValue("index", _activeReportIndex);
385 _displayNode->setBoolValue("have-next", _activeReportIndex < (int)_aggregated.size() - 1);
386 _displayNode->setBoolValue("have-previous", _activeReportIndex > 0);
387 }
388
389 void sendReportToSentry(AggregateReport& report)
390 {
391 if (report.type == Aggregation::InputDevice) {
392 // for non-official input configs, don't report, it's just noise
393 // https://gitlab.com/flightgear/flightgear/-/issues/3177
394 if (report.allOccurences([](const ErrorOcurrence& oc) {
395 return !isFGDataPath(oc.origin.getPath());
396 })) {
397 return;
398 }
399 }
400
401 // don't report socket or local IO issues to Sentry
402 // https://gitlab.com/flightgear/fgmeta/-/issues/33
403 if (report.type == Aggregation::NetworkFailure) {
404 return;
405 }
406
407 if (report.type == Aggregation::TerraSync) {
408 if (report.allOccurences([](const ErrorOcurrence& oc) {
409 return (oc.type == LoadFailure::IOError) || (oc.type == LoadFailure::NetworkError);
410 })) {
411 return;
412 }
413 }
414
415 const int catId = static_cast<int>(report.type);
416 flightgear::sentryReportUserError(static_categoryIds.at(catId),
417 report.parameter,
418 _displayNode->getStringValue());
419 }
420
421 void writeReportToStream(const AggregateReport& report, std::ostream& os) const;
422 void writeContextToStream(const ErrorOcurrence& error, std::ostream& os) const;
423 void writeLogToStream(const ErrorOcurrence& error, std::ostream& os) const;
424 void writeSignificantPropertiesToStream(std::ostream& os) const;
425
426 bool dismissReportCommand(const SGPropertyNode* args, SGPropertyNode*);
427 bool saveReportCommand(const SGPropertyNode* args, SGPropertyNode*);
428 bool showErrorReportCommand(const SGPropertyNode* args, SGPropertyNode*);
429
430 /**
431 * @brief check if the report is still adding new errors, we avoid showing the UI
432 * until all the errors are collected/
433 */
434 bool reportIsOngoing(const AggregateReport& report) const;
435 };
436
437 auto ErrorReporter::ErrorReporterPrivate::mainAircraftAggregate()
438 -> AggregateErrors::iterator
439 {
440 const auto fullId = fgGetString("/sim/aircraft-id");
441
442 // we use the dir name so we combine reports from different variants, on Sentry
443 const auto aircraftDirName = lastPathComponent(fgGetString("/sim/aircraft-dir"));
444
445 const auto isFromPackage = fgGetBool("/sim/aircraft-from-package");
446
447 if (!isFromPackage) {
448 return getAggregate(Aggregation::MainAircraft, aircraftDirName);
449 }
450
451 return getAggregate(Aggregation::HangarAircraft, aircraftDirName);
452 }
453
454 auto ErrorReporter::ErrorReporterPrivate::getAggregateForOccurence(const ErrorReporter::ErrorReporterPrivate::ErrorOcurrence& oc)
455 -> AggregateErrors::iterator
456 {
457 // all OOM errors go to a dedicated category. This is so we don't blame
458 // out of memory on the aircraft/scenery/etc, when it's not the underlying
459 // cause.
460 if (oc.type == simgear::LoadFailure::OutOfMemory) {
461 return getAggregate(Aggregation::OutOfMemory, {});
462 }
463
464 // errors about shared models typically indicate that the shared Models are
465 // missing or out of date.
466 if ((oc.type == simgear::LoadFailure::NotFound) || (oc.type == simgear::LoadFailure::BadData)) {
467 if (oc.detailedInfo.find("OBJECT_SHARED") != std::string::npos) {
468 return getAggregate(Aggregation::SharedModels);
469 }
470 }
471
472 if (oc.hasContextKey("primary-aircraft")) {
473 return mainAircraftAggregate();
474 }
475
476 if (oc.hasContextKey("multiplayer")) {
477 return getAggregate(Aggregation::MultiPlayer, {});
478 }
479
480 // traffic cases: need to handle errors in the traffic files (schedule, rwyuse)
481 // but also errors loading aircraft models associated with traffic
482 if (oc.code == simgear::ErrorCode::AITrafficSchedule) {
483 return getAggregate(Aggregation::Traffic, {});
484 }
485
486 if (oc.hasContextKey("traffic-aircraft-callsign")) {
487 return getAggregate(Aggregation::Traffic, {});
488 }
489
490 // all TerraSync coded errors go there: this is errors for the
491 // actual download process (eg, failed to write to disk)
492 if (oc.code == simgear::ErrorCode::TerraSync) {
493 const auto details = oc.detailedInfo;
494 if ((details.find("socket error") != std::string::npos) ||
495 (details.find("SSL connect error") != std::string::npos) ||
496 (details.find("Couldn't resolve host name") != std::string::npos)) {
497 return getAggregate(Aggregation::NetworkFailure, {});
498 }
499
500 if (oc.type == simgear::LoadFailure::NetworkError) {
501 return getAggregate(Aggregation::NetworkFailure, {});
502 }
503
504 return getAggregate(Aggregation::TerraSync, {});
505 }
506
507 if (oc.hasContextKey("terrain-stg") || oc.hasContextKey("btg")) {
508 // determine if it's custom scenery, TerraSync or FGData
509
510 // bucket is no use here, we need to check the BTG/XML/STG path etc.
511 // STG is probably the best bet. This ensures if a custom scenery
512 // STG references a model, XML or texture in FGData or TerraSync
513 // incorrectly, we attribute the error to the scenery, which is
514 // likely what we want/expect
515 auto path = oc.hasContextKey("terrain-stg") ? oc.getContextValue("terrain-stg") : oc.getContextValue("btg");
516
517 // try generic paths
518 if (simgear::strutils::starts_with(path, _fgdataPathPrefix)) {
519 return getAggregate(Aggregation::FGData, {});
520 } else if (simgear::strutils::starts_with(path, _terrasyncPathPrefix)) {
521 return getAggregate(Aggregation::TerraSync, {});
522 }
523
524 // custom scenery, find out the prefix. Order matters here because
525 // TerraSync path is added to FG scenery list, so we check those first
526 for (const auto& sceneryPath : globals->get_fg_scenery()) {
527 const auto pathStr = sceneryPath.utf8Str();
528 if (simgear::strutils::starts_with(path, pathStr)) {
529 return getAggregate(Aggregation::CustomScenery, pathStr);
530 }
531 }
532
533 // shouldn't ever happen
534 return getAggregate(Aggregation::CustomScenery, {});
535 }
536
537 // assume only FGData can define materials, for now.
538 if (oc.hasContextKey("materials")) {
539 return getAggregate(Aggregation::FGData);
540 }
541
542 if (oc.hasContextKey("scenario-path")) {
543 const auto scenarioPath = oc.getContextValue("scenario-path");
544 return getAggregate(Aggregation::Scenario, scenarioPath);
545 }
546
547 if (oc.hasContextKey("input-device")) {
548 return getAggregate(Aggregation::InputDevice, oc.getContextValue("input-device"));
549 }
550
551 if (oc.code == simgear::ErrorCode::AircraftSystems) {
552 if (isMainAircraftPath(oc.origin.asString())) {
553 return mainAircraftAggregate();
554 }
555
556 if (isFGDataPath(oc.origin.asString())) {
557 return getAggregate(Aggregation::FGData);
558 }
559 }
560
561 // start guessing :)
562 // from this point on we're using less reliable inferences about where the
563 // error came from, trying to avoid 'unknown'
564 if (isMainAircraftPath(oc.origin.asString())) {
565 return mainAircraftAggregate();
566 }
567
568 // GUI dialog errors often have no context
569 if (oc.code == simgear::ErrorCode::GUIDialog) {
570 // check if it's an aircraft dialog
571 if (isMainAircraftPath(oc.origin.asString())) {
572 const auto aircraftDirName = lastPathComponent(fgGetString("/sim/aircraft-dir"));
573 return getAggregate(Aggregation::MainAircraft, aircraftDirName);
574 }
575
576 // check if it's an add-on and use that
577 return getAggregate(Aggregation::FGData);
578 }
579
580 // because we report shader errors from the main thread, they don't
581 // get attributed. Collect them into their own category, which also
582 // means we can display a more specific message
583 if (oc.code == simgear::ErrorCode::LoadEffectsShaders) {
584 // we use the effect name to split shader errors
585 return getAggregate(Aggregation::ShadersEffects, oc.getContextValue("effect"));
586 }
587
588 // if we've got this far, and the path looks like an aircraft path, assume it was a cross-aircraft
589 // error, and report as such
590 // see https://gitlab.com/flightgear/flightgear/-/issues/3008
591 if (isAnyAircraftPath(oc.origin.asString())) {
592 const auto aircraftDirName = lastPathComponent(fgGetString("/sim/aircraft-dir"));
593 return getAggregate(Aggregation::MainAircraft, aircraftDirName);
594 }
595
596 return getAggregate(Aggregation::Unknown);
597 }
598
599 auto ErrorReporter::ErrorReporterPrivate::getAggregate(Aggregation ag, const std::string& param)
600 -> AggregateErrors::iterator
601 {
602 auto it = std::find_if(_aggregated.begin(), _aggregated.end(), [ag, &param](const AggregateReport& a) {
603 if (a.type != ag) return false;
604 return param.empty() ? true : param == a.parameter;
605 });
606
607 if (it == _aggregated.end()) {
608 AggregateReport r;
609 r.type = ag;
610 r.parameter = param;
611 _aggregated.push_back(r);
612 it = _aggregated.end() - 1;
613 }
614
615 switch (ag) {
616 case Aggregation::OutOfMemory:
617 case Aggregation::NetworkFailure:
618 it->isMessage = true;
619 default:
620 break;
621 }
622
623 return it;
624 }
625
626 void ErrorReporter::ErrorReporterPrivate::writeReportToStream(const AggregateReport& report, std::ostream& os) const
627 {
628 os << "FlightGear " << VERSION << " error report, created at ";
629 {
630 char buf[64];
631 time_t now = time(nullptr);
632 strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&now));
633 os << buf << std::endl;
634 }
635
636 os << "Category:" << static_categoryIds.at(static_cast<int>(report.type)) << std::endl;
637 if (!report.parameter.empty()) {
638 os << "\tParameter:" << report.parameter << std::endl;
639 }
640
641 os << std::endl; // insert a blank line after header data
642
643 int index = 1;
644 char whenBuf[64];
645
646 for (const auto& err : report.errors) {
647 os << "Error " << index++ << std::endl;
648 os << "\tcode:" << static_errorIds.at(static_cast<int>(err.code)) << std::endl;
649 os << "\ttype:" << static_errorTypeIds.at(static_cast<int>(err.type)) << std::endl;
650
651 strftime(whenBuf, sizeof(whenBuf), "%H:%M:%S GMT", gmtime(&err.when));
652 os << "\twhen:" << whenBuf << std::endl;
653
654 os << "\t" << err.detailedInfo << std::endl;
655 os << "\tlocation:" << err.origin.asString() << std::endl;
656 writeContextToStream(err, os);
657 writeLogToStream(err, os);
658 os << std::endl; // trailing blank line
659 }
660
661 os << "Command line / launcher / fgfsrc options" << std::endl;
662 for (auto o : Options::sharedInstance()->extractOptions()) {
663 os << "\t" << o << "\n";
664 }
665 os << std::endl;
666
667 writeSignificantPropertiesToStream(os);
668 }
669
670 void ErrorReporter::ErrorReporterPrivate::writeSignificantPropertiesToStream(std::ostream& os) const
671 {
672 os << "Properties:" << std::endl;
673 for (const auto& ps : _significantProperties) {
674 auto node = fgGetNode(ps);
675 if (!node) {
676 os << "\t" << ps << ": not defined\n";
677 } else {
678 os << "\t" << ps << ": " << node->getStringValue() << "\n";
679 }
680 }
681 os << std::endl;
682 }
683
684
685 bool ErrorReporter::ErrorReporterPrivate::dismissReportCommand(const SGPropertyNode* args, SGPropertyNode*)
686 {
687 std::lock_guard<std::mutex> g(_lock);
688 _activeErrorNode->setBoolValue(false);
689
690 if (args->getBoolValue("dont-show")) {
691 // TODO implement dont-show behaviour
692 }
693
694 // clear any values underneath displayNode?
695
696 _nextShowTimeout.stamp();
697 _reportsDirty = true; // set this so we check for another report to present
698 _activeReportIndex = -1;
699
700 return true;
701 }
702
703 bool ErrorReporter::ErrorReporterPrivate::showErrorReportCommand(const SGPropertyNode* args, SGPropertyNode*)
704 {
705 auto gui = globals->get_subsystem<NewGUI>();
706
707 std::lock_guard<std::mutex> g(_lock);
708 if (_aggregated.empty()) {
709 _displayNode->setStringValue("category", "No errors to report");
710 _displayNode->setIntValue("index", -1);
711 _displayNode->setBoolValue("have-next", false);
712 _displayNode->setBoolValue("have-previous", false);
713
714 if (!gui->getDialog("error-report")) {
715 gui->showDialog("error-report");
716 }
717 return true;
718 }
719
720 const auto numAggregates = static_cast<int>(_aggregated.size());
721 if (args->getBoolValue("next")) {
722 _activeReportIndex++;
723 if (_activeReportIndex >= numAggregates) {
724 return false;
725 }
726 } else if (args->getBoolValue("previous")) {
727 if (_activeReportIndex < 1) {
728 return false;
729 }
730 _activeReportIndex--;
731 } else if (args->hasChild("index")) {
732 _activeReportIndex = args->getIntValue("index");
733 if ((_activeReportIndex < 0) || (_activeReportIndex >= numAggregates)) {
734 return false;
735 }
736 } else {
737 _activeReportIndex = 0;
738 }
739
740 auto& report = _aggregated.at(_activeReportIndex);
741 presentErrorToUser(report);
742
743 if (!gui->getDialog("error-report")) {
744 gui->showDialog("error-report");
745 }
746 return true;
747 }
748
749 bool ErrorReporter::ErrorReporterPrivate::saveReportCommand(const SGPropertyNode* args, SGPropertyNode*)
750 {
751 if (_activeReportIndex < 0) {
752 return false;
753 }
754
755 const auto& report = _aggregated.at(_activeReportIndex);
756
757 const string where = args->getStringValue("where");
758
759 string when;
760 {
761 char buf[64];
762 time_t now = time(nullptr);
763 strftime(buf, sizeof(buf), "%Y%m%d", gmtime(&now));
764 when = buf;
765 }
766
767 if (where.empty() || (where == "!desktop")) {
768 SGPath p = SGPath::desktop() / ("flightgear_error_" + when + ".txt");
769 int uniqueCount = 2;
770 while (p.exists()) {
771 p = SGPath::desktop() / ("flightgear_error_" + when + "_" + std::to_string(uniqueCount++) + ".txt");
772 }
773
774 sg_ofstream f(p, std::ios_base::out);
775 writeReportToStream(report, f);
776 } else if (where == "!clipboard") {
777 std::ostringstream os;
778 writeReportToStream(report, os);
779 NasalClipboard::getInstance()->setText(os.str());
780 }
781
782 return true;
783 }
784
785
786 void ErrorReporter::ErrorReporterPrivate::writeContextToStream(const ErrorOcurrence& error, std::ostream& os) const
787 {
788 os << "\tcontext:\n";
789 for (const auto& c : error.context) {
790 os << "\t\t" << c.first << " = " << c.second << "\n";
791 }
792 }
793
794 void ErrorReporter::ErrorReporterPrivate::writeLogToStream(const ErrorOcurrence& error, std::ostream& os) const
795 {
796 os << "\tpreceeding log:\n";
797 for (const auto& c : error.log) {
798 os << "\t\t" << c << "\n";
799 }
800 }
801
802 bool ErrorReporter::ErrorReporterPrivate::AggregateReport::addOccurence(const ErrorOcurrence& err)
803 {
804 auto it = std::find_if(errors.begin(), errors.end(), [err](const ErrorOcurrence& ext) {
805 // check if the two occurrences match for the purposes of
806 // de-duplication.
807 return (ext.code == err.code) &&
808 (ext.type == err.type) &&
809 (ext.detailedInfo == err.detailedInfo) &&
810 (ext.origin.asString() == err.origin.asString());
811 });
812
813 if (it != errors.end()) {
814 return false; // duplicate, don't add
815 }
816
817 errors.push_back(err);
818 lastErrorTime.stamp();
819 return true;
820 }
821
822 bool ErrorReporter::ErrorReporterPrivate::isFGDataPath(const std::string& path)
823 {
824 for (const auto& dp : globals->get_data_paths()) {
825 if (path.find(dp.utf8Str()) == 0) {
826 return true;
827 }
828 }
829
830 return false;
831 }
832
833 bool ErrorReporter::ErrorReporterPrivate::AggregateReport::allOccurences(OcurrencePredicate p) const
834 {
835 auto it = std::find_if(errors.begin(), errors.end(), [p](const ErrorOcurrence& ext) {
836 return !p(ext);
837 });
838
839 return it == errors.end();
840 }
841
842 bool ErrorReporter::ErrorReporterPrivate::isMainAircraftPath(const std::string& path) const
843 {
844 const auto pos = path.find(_aircraftDirectoryName);
845 return pos != std::string::npos;
846 }
847
848 /**
849 * @brief helper to determine if a file looks like it belongs to an aircraft.
850 *
851 * This is used to detect potential cross-aircraft packaging bugs which often lead to
852 * 'not found' error reports. So we're looking for paths which look plausibly like any
853 * aircraft path, even though @ref isMainAircraftPath didn't match on them.
854 */
855 bool ErrorReporter::ErrorReporterPrivate::isAnyAircraftPath(const std::string& path) const
856 {
857 const auto pos = path.find("Aircraft/");
858 if (pos == 0) {
859 // relative path which starts with "Aircraft/"
860 return true;
861 }
862
863 // TODO: decide if we also include paths which contain 'Aircraft' as a component
864 return false;
865 }
866
867 bool ErrorReporter::ErrorReporterPrivate::reportIsOngoing(const AggregateReport& report) const
868 {
869 // don't wait for these to end, since they might continue forever
870 if ((report.type == Aggregation::NetworkFailure) || (report.type == Aggregation::OutOfMemory)) {
871 return false;
872 }
873
874 SGTimeStamp n = SGTimeStamp::now();
875 const auto ageSec = (n - report.lastErrorTime).toSecs();
876 return (ageSec < NoNewErrorsTimeout);
877 }
878
879
880 ////////////////////////////////////////////
881
882 ErrorReporter::ErrorReporter() : d(new ErrorReporterPrivate)
883 {
884 d->_logCallback.reset(new RecentLogCallback);
885
886 // define significant properties
887 d->_significantProperties = {
888 "/sim/aircraft-id",
889 "/sim/aircraft-dir",
890 "/sim/rendering/gl-version",
891 "/sim/rendering/gl-renderer",
892 "/sim/rendering/gl-shading-language-version",
893 "/sim/rendering/max-texture-size",
894 "/sim/rendering/max-texture-units",
895 "/sim/rendering/shaders/skydome",
896 "/sim/rendering/shaders/water",
897 "/sim/rendering/shaders/model",
898 "/sim/rendering/shaders/landmass",
899 "/sim/rendering/shaders/vegetation-effects",
900 "/sim/rendering/shaders/transition",
901 "/sim/rendering/max-paged-lod",
902 "/sim/rendering/photoscenery/enabled",
903 "/sim/rendering/preset-description",
904 "/sim/rendering/multithreading-mode",
905 "/sim/rendering/multi-sample-buffers",
906 "/sim/rendering/multi-samples",
907 "/scenery/use-vpb"};
908 }
909
910 ErrorReporter::~ErrorReporter()
911 {
912 // if we are deleted withut being shutdown(), ensure we clean
913 // up our logging callback
914 if (d->_logCallbackRegistered) {
915 sglog().removeCallback(d->_logCallback.get());
916 }
917 }
918
919 void ErrorReporter::bind()
920 {
921 SGPropertyNode_ptr n = fgGetNode("/sim/error-report", true);
922
923 d->_enabledNode = n->getNode("enabled", true);
924 if (!d->_enabledNode->hasValue()) {
925 d->_enabledNode->setBoolValue(false); // default to off for now
926 }
927
928 d->_displayNode = n->getNode("display", true);
929 d->_activeErrorNode = n->getNode("active", true);
930 d->_mpReportNode = n->getNode("mp-report-enabled", true);
931 }
932
933 void ErrorReporter::unbind()
934 {
935 d->_enabledNode.clear();
936 d->_displayNode.clear();
937 d->_activeErrorNode.clear();
938 }
939
940 void ErrorReporter::preinit()
941 {
942 ErrorReporterPrivate* p = d.get();
943 simgear::setFailureCallback([p](simgear::LoadFailure type, simgear::ErrorCode code, const std::string& details, const sg_location& location) {
944 p->collectError(type, code, details, location);
945 });
946
947 simgear::setErrorContextCallback([p](const std::string& key, const std::string& value) {
948 p->collectContext(key, value);
949 });
950
951 sglog().addCallback(d->_logCallback.get());
952 d->_logCallbackRegistered = true;
953
954 // cache these values here
955 d->_fgdataPathPrefix = globals->get_fg_root().utf8Str();
956 d->_terrasyncPathPrefix = globals->get_terrasync_dir().utf8Str();
957
958 const auto aircraftPath = SGPath::fromUtf8(fgGetString("/sim/aircraft-dir"));
959 d->_aircraftDirectoryName = aircraftPath.file();
960 }
961
962 void ErrorReporter::init()
963 {
964 // we want to disable errors in developer mode, but since self-compiled
965 // builds default to developer-mode=true, need an override so people
966 // can see errors if they want
967 const auto developerMode = fgGetBool("sim/developer-mode");
968 const auto disableInDeveloperMode = !d->_enabledNode->getParent()->getBoolValue("enable-in-developer-mode");
969 const auto dd = developerMode && disableInDeveloperMode;
970
971 if (dd || !d->_enabledNode->getBoolValue()) {
972 d->_isEnabled = false;
973 } else {
974 d->_isEnabled = true;
975 }
976
977 // most work is done in preinit(), because errors can occur early in startup, before
978 // subsystems are being initialized
979 globals->get_commands()->addCommand("dismiss-error-report", d.get(), &ErrorReporterPrivate::dismissReportCommand);
980 globals->get_commands()->addCommand("save-error-report-data", d.get(), &ErrorReporterPrivate::saveReportCommand);
981 globals->get_commands()->addCommand("show-error-report", d.get(), &ErrorReporterPrivate::showErrorReportCommand);
982 }
983
984 void ErrorReporter::update(double dt)
985 {
986 bool showDialog = false;
987 bool showPopup = false;
988 bool havePendingReports = false;
989 bool showMessage = false;
990
991 // beginning of locked section
992 {
993 std::lock_guard<std::mutex> g(d->_lock);
994
995 if (!d->_enabledNode->getBoolValue()) {
996 return;
997 }
998
999 // we are into the update phase (postinit has occurred). We treat errors
1000 // after this point with lower severity, to avoid popups into a flight
1001 d->_haveDonePostInit = true;
1002
1003 SGTimeStamp n = SGTimeStamp::now();
1004
1005 // ensure we delay between successive error dialogs
1006 const auto timeSinceLastDialog = (n - d->_nextShowTimeout).toSecs();
1007 if (timeSinceLastDialog < MinimumIntervalBetweenDialogs) {
1008 return;
1009 }
1010
1011 if (!d->_reportsDirty) {
1012 return;
1013 }
1014
1015 if (d->_activeReportIndex >= 0) {
1016 return; // already showing a report
1017 }
1018
1019 // check if any reports are due
1020
1021 // check if an error is current active
1022 for (auto& report : d->_aggregated) {
1023 if (report.type == Aggregation::MultiPlayer) {
1024 if (!d->_mpReportNode->getBoolValue()) {
1025 // mark it as shown, to suppress it
1026 report.haveShownToUser = true;
1027 }
1028 }
1029
1030 // if we have shown the special 'missing shared models' warning,
1031 // don't also report it here.
1032 if (report.type == Aggregation::SharedModels) {
1033 if (flightgear::haveShownSharedModelsError()) {
1034 report.haveShownToUser = true;
1035 }
1036 }
1037
1038 if (report.haveShownToUser) {
1039 // unless we ever re-show?
1040 continue;
1041 }
1042
1043 if (d->reportIsOngoing(report)) {
1044 havePendingReports = true;
1045 continue;
1046 }
1047
1048 d->presentErrorToUser(report);
1049 if (report.isCritical) {
1050 showDialog = true;
1051 } else if (report.isMessage) {
1052 showMessage = true;
1053 } else {
1054 showPopup = true;
1055 }
1056
1057 if (d->_isEnabled) {
1058 d->sendReportToSentry(report);
1059 }
1060
1061 // if we show one report, don't consider any others for now
1062 break;
1063 } // of active aggregates iteration
1064
1065 if (!havePendingReports) {
1066 d->_reportsDirty = false;
1067 }
1068 } // end of locked section
1069
1070 if (!d->_isEnabled || flightgear::isHeadlessMode()) {
1071 showDialog = false;
1072 showPopup = false;
1073 showMessage = false;
1074 }
1075
1076 // show messages: these are local configuration pieces
1077 // so always warn them to the user, eg DNS/network failure, out-of-memory, or
1078 // missing shared models.
1079 if (showMessage) {
1080 SGPropertyNode_ptr popupArgs(new SGPropertyNode);
1081 popupArgs->setStringValue("message", d->_displayNode->getStringValue("category"));
1082 globals->get_commands()->execute("show-error-message-popup", popupArgs, nullptr);
1083 }
1084
1085 // do not call into another subsystem with our lock held,
1086 // as this can trigger deadlocks
1087 if (showDialog) {
1088 auto gui = globals->get_subsystem<NewGUI>();
1089 gui->showDialog("error-report");
1090 // this needs a bit more thought, disabling for the now
1091 #if 0
1092 // pause the sim when showing the popup
1093 SGPropertyNode_ptr pauseArgs(new SGPropertyNode);
1094 pauseArgs->setBoolValue("force-pause", true);
1095 globals->get_commands()->execute("do_pause", pauseArgs);
1096 #endif
1097 } else if (showPopup && d->_popupEnabled) {
1098 SGPropertyNode_ptr popupArgs(new SGPropertyNode);
1099 popupArgs->setIntValue("index", d->_activeReportIndex);
1100 globals->get_commands()->execute("show-error-notification-popup", popupArgs, nullptr);
1101 }
1102 }
1103
1104 void ErrorReporter::shutdown()
1105 {
1106 globals->get_commands()->removeCommand("dismiss-error-report");
1107 globals->get_commands()->removeCommand("save-error-report-data");
1108 globals->get_commands()->removeCommand("show-error-report");
1109
1110 // during a reset we don't want to touch the log callback; it was added in
1111 // preinit, which does not get repeated on a reset
1112 const bool inReset = fgGetBool("/sim/signals/reinit", false);
1113 if (!inReset) {
1114 sglog().removeCallback(d->_logCallback.get());
1115 d->_logCallbackRegistered = false;
1116 }
1117 }
1118
1119 std::string ErrorReporter::threadSpecificContextValue(const std::string& key)
1120 {
1121 auto it = thread_errorContextStack.find(key);
1122 if (it == thread_errorContextStack.end())
1123 return {};
1124
1125 return it->second.back();
1126 }
1127
1128
1129 } // namespace flightgear
1130
1131 // Register the subsystem.
1132 SGSubsystemMgr::Registrant<flightgear::ErrorReporter> registrantErrorReporter(
1133 SGSubsystemMgr::GENERAL);