Repository navigation
Expand file tree
/
Copy pathbrowser_runtime_entry.cpp
More file actions
307 lines (305 loc) · 16.9 KB
/
Copy pathbrowser_runtime_entry.cpp
File metadata and controls
307 lines (305 loc) · 16.9 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
#include "src/common/system/runtime_paths.h"
#include <Loop.h>
#include <spdlog/spdlog.h>
#include "src/entrypoints/desktop/browser_runtime_options.h"
#include "src/backend/media/live/tests/support/live_capture_fixture.h"
#include <vector>
#include <pthread.h>
#include <signal.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/signalfd.h>
#include <unistd.h>
#include "src/common/io/scoped_fd.h"
#include "src/common/types/exception_message.h"
#include <cstdlib>
#include <array>
#include <cerrno>
#include <charconv>
#include <exception>
#include <execinfo.h>
#include <filesystem>
#include <memory>
#include <optional>
#include <random>
#include <stop_token>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <utility>
#include "src/controller/services/firefox/firefox_process_owner.h"
#include "src/controller/services/diagnostics/diagnostics_client.h"
#include "src/controller/services/settings/settings_location.h"
#include "src/controller/services/training/train_command.h"
#include "src/controller/shell/application_shell.h"
import mmltk.common.logging.mmltk_logging;
namespace mmltk::entrypoints::desktop {
namespace {
// Ordinary std::terminate diagnostics only; this is not a signal handler.
[[noreturn]] void integration_terminate_trace() noexcept {
const auto failure = std::current_exception();
const auto detail = mmltk::common::types::exception_message(failure, "terminated without an active exception", "uncaught nonstandard exception");
mmltk::common::logging::report_fatal("native termination", detail);
std::array<void*, 40U> frames{};
const int count = ::backtrace(frames.data(), static_cast<int>(frames.size()));
::backtrace_symbols_fd(frames.data(), count, STDERR_FILENO);
std::abort();
}
class UwsLoopOwner final {
public:
UwsLoopOwner() : loop_(uWS::Loop::get()) {}
~UwsLoopOwner() {
if (loop_ != nullptr) loop_->free();
}
UwsLoopOwner(const UwsLoopOwner&) = delete;
UwsLoopOwner& operator=(const UwsLoopOwner&) = delete;
private:
uWS::Loop* loop_ = nullptr;
};
[[nodiscard]] bool integration_requested() noexcept {
const char* const integration = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_INTEGRATION");
return integration != nullptr && std::string_view{integration} == "1";
}
[[nodiscard]] std::array<char, 32U> firefox_error_detail(const int error) noexcept {
std::array<char, 32U> detail{};
if (error == 0) return detail;
constexpr std::string_view prefix{"errno="};
for (std::size_t index = 0U; index < prefix.size(); ++index) detail[index] = prefix[index];
static_cast<void>(std::to_chars(detail.data() + prefix.size(), detail.data() + detail.size() - 1U, error));
return detail;
}
[[nodiscard]] int fail_closed(
mmltk::controller::shell::ApplicationShell& shell, const std::string_view stage, const std::string_view detail = {}, const std::optional<int> status = std::nullopt) noexcept {
mmltk::common::logging::report_fatal(stage, detail, status);
shell.request_shutdown(mmltk::controller::shell::ApplicationShutdownReason::InfrastructureFailure);
static_cast<void>(shell.shutdown());
return 1;
}
class SignalWaiter final {
public:
explicit SignalWaiter(mmltk::controller::shell::ApplicationShell& shell, const int diagnostics_terminal)
: thread_([&shell, diagnostics_terminal](const std::stop_token stop) {
sigset_t signals{};
if (::sigemptyset(&signals) != 0 || ::sigaddset(&signals, SIGINT) != 0 || ::sigaddset(&signals, SIGTERM) != 0) {
shell.request_shutdown(mmltk::controller::shell::ApplicationShutdownReason::InfrastructureFailure);
return;
}
mmltk::common::io::ScopedFd signal_fd{::signalfd(-1, &signals, SFD_CLOEXEC)};
pollfd events[]{{.fd = signal_fd.get(), .events = POLLIN, .revents = 0}, {.fd = diagnostics_terminal, .events = POLLIN, .revents = 0}};
int ready = -1;
if (signal_fd.get() >= 0) {
do { ready = ::poll(events, 2U, -1); } while (ready < 0 && errno == EINTR);
}
if (stop.stop_requested()) return;
signalfd_siginfo signal{};
if (ready < 0 || events[1].revents != 0 || ::read(signal_fd.get(), &signal, sizeof(signal)) != static_cast<ssize_t>(sizeof(signal))) {
shell.request_shutdown(mmltk::controller::shell::ApplicationShutdownReason::InfrastructureFailure);
return;
}
shell.request_shutdown(
signal.ssi_signo == SIGINT ? mmltk::controller::shell::ApplicationShutdownReason::SignalInterrupt : mmltk::controller::shell::ApplicationShutdownReason::SignalTerminate);
}) {}
~SignalWaiter() {
thread_.request_stop();
if (thread_.joinable()) static_cast<void>(::pthread_kill(thread_.native_handle(), SIGTERM));
}
SignalWaiter(const SignalWaiter&) = delete;
SignalWaiter& operator=(const SignalWaiter&) = delete;
private:
std::jthread thread_;
};
[[nodiscard]] std::string session_token() {
// The server checks this capability before accepting the only local page.
// It is intentionally process-local and only authenticates this page.
std::string value{"mmltk-"};
value += std::to_string(static_cast<unsigned long long>(std::random_device{}()));
return value;
}
[[nodiscard]] std::filesystem::path firefox_log_file() {
const char* const configured = std::getenv("MMLTK_FIREFOX_LOG_FILE");
return configured != nullptr && configured[0] != '\0' ? std::filesystem::path{configured} : std::filesystem::path{};
}
[[nodiscard]] std::filesystem::path configured_root(const char* const environment_name, const char* const installed_root) {
const char* const configured = std::getenv(environment_name);
return configured != nullptr && configured[0] != '\0' ? std::filesystem::path{configured} : std::filesystem::path{installed_root};
}
[[nodiscard]] int integration_control_fd() noexcept {
const char* const configured = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_EXPLORE_CONTROL_FD");
if (configured == nullptr || configured[0] == '\0') return -1;
int descriptor = -1;
const std::string_view text{configured};
const auto parsed = std::from_chars(text.data(), text.data() + text.size(), descriptor);
if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || descriptor < 0 || ::fcntl(descriptor, F_SETFD, FD_CLOEXEC) != 0) return -1;
return descriptor;
}
[[nodiscard]] std::string query_value(const std::string_view value) {
constexpr char digits[] = "0123456789ABCDEF";
std::string result;
result.reserve(value.size());
for (const unsigned char character : value) {
if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') || character == '-' || character == '_' || character == '.' ||
character == '~') {
result.push_back(static_cast<char>(character));
} else {
result.push_back('%');
result.push_back(digits[character >> 4U]);
result.push_back(digits[character & 0x0fU]);
}
}
return result;
}
[[nodiscard]] mmltk::controller::services::SettingsLocation production_settings_location() {
std::error_code error;
const std::filesystem::path working_directory = std::filesystem::current_path(error);
if (error) { return mmltk::controller::services::SettingsLocation{std::string_view{}}; }
return mmltk::controller::services::SettingsLocation{(working_directory / ".mmltk-data" / "gui.json").string()};
}
} // namespace
} // namespace mmltk::entrypoints::desktop
int main(int argc, char** argv) {
using namespace mmltk::entrypoints::desktop;
const bool integration = integration_requested();
const char* const integration_dpi = integration ? std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_DPI") : nullptr;
const bool integration_high_dpi = integration_dpi != nullptr && std::string_view{integration_dpi} == "1.5";
try {
{
auto logging_config = mmltk::common::logging::config_from_env({});
if (logging_config.enabled()) { logging_config.app_name = "mmltk-browser-host"; }
mmltk::common::logging::initialize(logging_config);
mmltk::common::logging::trace([](auto& logger) { logger.trace("workspace Wayland native runtime logging initialized"); });
}
const char* const terminate_trace = integration ? std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_TERMINATE_TRACE") : nullptr;
if (terminate_trace != nullptr && std::string_view{terminate_trace} == "1" && mmltk::common::logging::enabled(spdlog::level::trace)) {
std::array<void*, 1U> warm{};
static_cast<void>(::backtrace(warm.data(), static_cast<int>(warm.size())));
std::set_terminate(&integration_terminate_trace);
}
UwsLoopOwner loop_owner;
if (!mmltk::controller::services::block_browser_runtime_signals()) {
mmltk::common::logging::report_fatal("browser runtime signal-mask setup", "failed");
return 1;
}
std::vector<std::string_view> arguments;
for (int index = 1; index < argc; ++index) arguments.emplace_back(argv[index]);
auto runtime = parse_browser_runtime_options(arguments);
mmltk::controller::shell::ApplicationShellConfig config;
config.training_executable = mmltk::controller::services::resolve_sibling_mmltk_cli(mmltk::common::system::runtime_paths::current_executable_path());
const char* const pixel_trace = std::getenv("MMLTK_GUI_PIXEL_TRACE");
const char* const lifecycle_trace = std::getenv("MMLTK_GUI_TRACE_FILE");
const bool pixel_probes = pixel_trace != nullptr && std::string_view{pixel_trace} == "1" && lifecycle_trace != nullptr && *lifecycle_trace != '\0';
config.pixel_probes = pixel_probes;
config.presentation = std::move(runtime.presentation);
config.h2d_dataloader = runtime.h2d_dataloader;
std::string integration_file_dialog_root;
if (integration) {
std::error_code error;
integration_file_dialog_root = std::filesystem::current_path(error).string();
if (error || integration_file_dialog_root.empty()) {
mmltk::common::logging::report_fatal("integration working-directory discovery failed", error.message());
return 1;
}
config.file_dialog_launch_directory = integration_file_dialog_root;
if (const char* scenario = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_VIEWER_SCENARIO"); scenario && std::string_view{scenario} == "keypoints") {
auto input = std::make_shared<mmltk::backend::media::live::test_support::LiveCaptureFixture>(std::filesystem::path{integration_file_dialog_root} / "live-capture.fifo");
config.live.capture_device = input->path();
config.live.capture_api = input->api();
config.live.capture_custody = std::move(input);
}
const int explore_control = integration_control_fd();
if (explore_control < 0) {
mmltk::common::logging::report_fatal("Explore acceptance control descriptor", "rejected");
return 1;
}
config.explore.acceptance = std::make_shared<mmltk::controller::ExploreAcceptanceGate>(explore_control);
const char* const completion_gate = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_COMPLETION_GATE");
if (completion_gate != nullptr && std::string_view{completion_gate} == "1") {
config.completion_acceptance = std::make_shared<mmltk::controller::PresentationAcceptanceGate>();
config.explore.acceptance->SetReadObserver(config.explore.acceptance.get(),
[](void* owner, std::uint64_t generation, std::uint32_t index) { static_cast<mmltk::controller::ExploreAcceptanceGate*>(owner)->AwaitVisibleRead(generation, index); });
}
const char* const pending_supersession = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_PENDING_SUPERSESSION");
config.pending_supersession_acceptance = pending_supersession != nullptr && std::string_view{pending_supersession} == "1";
if (config.pending_supersession_acceptance && !config.completion_acceptance) config.completion_acceptance = std::make_shared<mmltk::controller::PresentationAcceptanceGate>();
}
if (lifecycle_trace != nullptr && *lifecycle_trace != '\0') {
config.diagnostics = mmltk::controller::services::DiagnosticsClient{std::filesystem::path{lifecycle_trace}};
if (integration) config.diagnostic_delivery = mmltk::controller::services::RuntimeDiagnosticDelivery::Complete;
}
config.settings_location = production_settings_location();
const int diagnostics_terminal = config.diagnostic_delivery == mmltk::controller::services::RuntimeDiagnosticDelivery::Complete ? config.diagnostics.terminal_fd() : -1;
mmltk::controller::shell::ApplicationShell shell{std::move(config)};
try {
const std::filesystem::path assets = configured_root("MMLTK_BROWSER_APP_ASSET_ROOT_OVERRIDE", MMLTK_BROWSER_APP_ASSET_ROOT);
std::string page_query;
if (integration) {
page_query = "mmltk_integration=1";
if (const char* fixture = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_PIXEL_FIXTURE"); fixture != nullptr && std::string_view{fixture} == "1") page_query += "&mmltk_integration_pixel_fixture=1";
if (const char* scenario = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_VIEWER_SCENARIO"); scenario != nullptr) page_query += "&mmltk_integration_viewer_scenario=" + query_value(scenario);
if (const char* square = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_SQUARE_SOURCE"); square != nullptr) page_query += "&mmltk_integration_square_source=" + query_value(square);
if (const char* square = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_SQUARE_COMPILED"); square != nullptr) page_query += "&mmltk_integration_square_compiled=" + query_value(square);
const char* const window_close = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_WINDOW_CLOSE");
if (window_close != nullptr && std::string_view{window_close} == "1") page_query += "&mmltk_integration_window_close=1";
const char* const source = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_DATASET_SOURCE");
const char* const compiled = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_COMPILED_DIRECTORY");
const char* const resolution = std::getenv("MMLTK_RUN_WORKSPACE_WAYLAND_RESOLUTION");
if (source == nullptr || compiled == nullptr || resolution == nullptr) return fail_closed(shell, "integration dataset configuration missing");
page_query += "&mmltk_integration_dataset_source=" + query_value(source);
page_query += "&mmltk_integration_compiled_directory=" + query_value(compiled);
page_query += "&mmltk_integration_resolution=" + query_value(resolution);
}
if (lifecycle_trace != nullptr && *lifecycle_trace != '\0') {
if (!page_query.empty()) page_query += '&';
page_query += "mmltk_surface_trace=1";
}
if (pixel_probes) {
if (!page_query.empty()) page_query += '&';
page_query += "mmltk_pixel_trace=1";
}
if (!shell.start_browser_host({.asset_root = assets, .session_token = session_token(), .page_query = std::move(page_query)})) { return fail_closed(shell, "browser host start failed"); }
auto& server = shell.browser_server();
if (!server.running()) { return fail_closed(shell, "browser server stopped during startup"); }
auto page = server.page_url();
if (!page) return fail_closed(shell, "browser page URL unavailable");
const auto process_start = shell.start_firefox(
{.executable = configured_root("MMLTK_FIREFOX_RUNTIME_ROOT_OVERRIDE", MMLTK_FIREFOX_RUNTIME_ROOT) / "firefox",
.page_url = std::move(*page),
.log_file = firefox_log_file(),
.crash_file = std::filesystem::current_path() / ".mmltk-data" / "firefox-crash.jsonl",
.integration = integration,
.integration_high_dpi = integration_high_dpi});
if (process_start == mmltk::controller::services::FirefoxProcessStartResult::Terminal) {
const auto firefox = shell.firefox_lifecycle();
const auto detail = firefox_error_detail(firefox.error_code);
return fail_closed(shell, "Firefox process start failed", detail.data(), firefox.status);
}
SignalWaiter signal_waiter{shell, diagnostics_terminal};
shell.run();
const auto firefox = shell.firefox_lifecycle();
const int status = mmltk::controller::services::browser_runtime_exit_status(firefox, shell.healthy());
if (status != 0) {
using mmltk::controller::services::FirefoxProcessTerminal;
if (firefox.terminal == FirefoxProcessTerminal::Signaled) {
// The process owner records SIGSEGV at observation time, including when
// it can recover. Other terminal signals are reported here once.
if (firefox.status != 128 + SIGSEGV) mmltk::common::logging::report_fatal("Firefox", "terminated by signal", firefox.status - 128);
} else if (firefox.terminal == FirefoxProcessTerminal::StartupFailed) {
const auto detail = firefox_error_detail(firefox.error_code);
mmltk::common::logging::report_fatal("Firefox process infrastructure failure", detail.data(), firefox.status);
} else if (firefox.terminal == FirefoxProcessTerminal::Exited && firefox.status != 0)
mmltk::common::logging::report_fatal("Firefox", "child exited unsuccessfully", firefox.status);
else
mmltk::common::logging::report_fatal("browser runtime", "application health failure", status);
}
return status;
} catch (const std::exception& error) { return fail_closed(shell, "browser host runtime exception", error.what()); } catch (...) {
return fail_closed(shell, "browser host unknown runtime exception");
}
} catch (const std::exception& error) {
mmltk::common::logging::report_fatal("browser host construction exception", error.what());
return 1;
} catch (...) {
mmltk::common::logging::report_fatal("browser host construction", "unknown exception");
return 1;
}
}